一.jdk
//获取cpu核数
Runtime.getRuntime().availableProcessors()
//扩容为当前两倍
Cell[] rs = new Cell[n << 1];
//寻址
tab[i = (n - 1) & hash])
//返回Java虚拟机中的堆内存总量
long initialMemory = Runtime.getRuntime( ).totalMemory();
返回java虚拟机试图使用的最大堆内存量
long maxMemory = Runtime.getRuntime( ).maxMemory();
//输出响应内容
PrintWriter out = response.getWriter();
out.print(configInfoBase.getContent());
out.flush();
out.close();
//输出文件内容
File file = new File("test");
file .getChannel().transferTo(0L, fis.getChannel().size(), Channels.newChannel(response.getOutputStream()));
//判断是否是父子关系,结果是true,证明B可以转换成A
A.isAssignableFrom(B)
1.1创建单例的两种方式
①.双重检锁+volatile
public class VolatileTest {
private static volatile VolatileTest sinleton;
private VolatileTest(){
}
public static VolatileTest getInstance(){
if (sinleton == null){
synchronized (sinleton){
if (sinleton == null) {
//1.分配内存空间 2.初始化对象 3.设置instance指向刚分配的内存地址
//如果不加volatile修饰可能会导致2和3顺序对调
sinleton = new VolatileTest();
}
}
}
return sinleton;
}
}
②.静态内部类
public class VolatileTest {
private VolatileTest(){
}
private static class VolatileHolder{
private static final VolatileTest INSTANCE = new VolatileTest();
}
public static VolatileTest getInstance(){
return VolatileHolder.INSTANCE;
}
}
1.2jdk的spi机制
在resources下META-INFO的services目录下定义接口的全路径接口名,在文件里定义实现类的全路径名,一个一行。
使用ServiceLoader.load(接口类)获取实现类
1.3获取ip地址
public static String getRemoteIp(HttpServletRequest request) {
String xForwardedFor = request.getHeader("X-Forwarded-For");
if (!StringUtils.isBlank(xForwardedFor)) {
return xForwardedFor.split(",")[0].trim();
}
String nginxHeader = request.getHeader("X-Real-IP");
return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
}
二.Nacos
字符串null转换为""
this.logName = Objects.toString(this.logName, "");
2.1获取ip信息
#获取ip信息
commons.util工具类
InetUtils inetUtils;
this.ip = this.inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
#网络接口名在大多数操作系统上(包括Windows、Linux和Unix)是以eth开头,后面是网络接口的索引号,从0开始。如本机安了三块网卡,那么网络接口名就依次是eth0、eth1和eth2.NetworkInterface对象的toString方法可以返回网络接口的名称、显示名和这个网络接口上绑字的所有IP地址等信息
NetworkInterface netInterface = NetworkInterface.getByName(this.networkInterface);
2.2创建观察者
#创建观察者
public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
private final NacosDiscoveryProperties properties;
private final TaskScheduler taskScheduler;
private final AtomicLong nacosWatchIndex;
private final AtomicBoolean running;
private ApplicationEventPublisher publisher;
private ScheduledFuture<?> watchFuture;
private Set<String> cacheServices;
private HashMap<String, EventListener> subscribeListeners;
public NacosWatch(NacosDiscoveryProperties properties) {
this(properties, getTaskScheduler());
}
public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) {
this.nacosWatchIndex = new AtomicLong(0L);
this.running = new AtomicBoolean(false);
this.cacheServices = new HashSet();
this.subscribeListeners = new HashMap();
this.properties = properties;
this.taskScheduler = taskScheduler;
}
private static ThreadPoolTaskScheduler getTaskScheduler() {
ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
taskScheduler.initialize();
return taskScheduler;
}
}
2.3反射
#反射创建类
public static NamingService createNamingService(Properties properties) throws NacosException {
try {
Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
Constructor constructor = driverImplClass.getConstructor(Properties.class);
NamingService vendorImpl = (NamingService)constructor.newInstance(properties);
return vendorImpl;
} catch (Throwable var4) {
throw new NacosException(-400, var4);
}
}
2.4心跳定时任务
/**
* nacos心跳定时任务
*/
@Slf4j
public class BeatThread {
private ScheduledExecutorService executorService;
public void task(){
log.info("进入task中");
executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
Thread thread = new Thread(r);
thread.setDaemon(true);
thread.setName(String.valueOf(new Random().nextInt(10)));
return thread;
}
});
executorService.schedule(new BeatTask(),1,TimeUnit.SECONDS);
}
class BeatTask implements Runnable {
public BeatTask() {
}
@Override
public void run() {
log.info("进入线程任务中了");
executorService.schedule(new BeatTask(),1,TimeUnit.SECONDS);
}
}
}
2.5故障转移
public String reqAPI(String api, Map<String, String> params, List<String> servers, String method) {
params.put("namespaceId", this.getNamespaceId());
if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(this.nacosDomain)) {
throw new IllegalArgumentException("no server available");
} else {
Exception exception = new Exception();
if (servers != null && !servers.isEmpty()) {
Random random = new Random(System.currentTimeMillis());
int index = random.nextInt(servers.size());
for(int i = 0; i < servers.size(); ++i) {
String server = (String)servers.get(index);
try {
return this.callServer(api, params, server, method);
} catch (NacosException var11) {
exception = var11;
LogUtils.NAMING_LOGGER.error("request {} failed.", server, var11);
} catch (Exception var12) {
exception = var12;
LogUtils.NAMING_LOGGER.error("request {} failed.", server, var12);
}
index = (index + 1) % servers.size();
}
throw new IllegalStateException("failed to req API:" + api + " after all servers(" + servers + ") tried: " + ((Exception)exception).getMessage());
} else {
int i = 0;
while(i < 3) {
try {
return this.callServer(api, params, this.nacosDomain);
} catch (Exception var13) {
exception = var13;
LogUtils.NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + this.nacosDomain, var13);
++i;
}
}
throw new IllegalStateException("failed to req API:/api/" + api + " after all servers(" + servers + ") tried: " + ((Exception)exception).getMessage());
}
}
}