一.jdk

  1. //获取cpu核数
  2. Runtime.getRuntime().availableProcessors()
  3. //扩容为当前两倍
  4. Cell[] rs = new Cell[n << 1];
  5. //寻址
  6. tab[i = (n - 1) & hash])
  7. //返回Java虚拟机中的堆内存总量
  8. long initialMemory = Runtime.getRuntime( ).totalMemory();
  9. 返回java虚拟机试图使用的最大堆内存量
  10. long maxMemory = Runtime.getRuntime( ).maxMemory();
  11. //输出响应内容
  12. PrintWriter out = response.getWriter();
  13. out.print(configInfoBase.getContent());
  14. out.flush();
  15. out.close();
  16. //输出文件内容
  17. File file = new File("test");
  18. file .getChannel().transferTo(0L, fis.getChannel().size(), Channels.newChannel(response.getOutputStream()));
  19. //判断是否是父子关系,结果是true,证明B可以转换成A
  20. A.isAssignableFrom(B)

1.1创建单例的两种方式

①.双重检锁+volatile

  1. public class VolatileTest {
  2. private static volatile VolatileTest sinleton;
  3. private VolatileTest(){
  4. }
  5. public static VolatileTest getInstance(){
  6. if (sinleton == null){
  7. synchronized (sinleton){
  8. if (sinleton == null) {
  9. //1.分配内存空间 2.初始化对象 3.设置instance指向刚分配的内存地址
  10. //如果不加volatile修饰可能会导致2和3顺序对调
  11. sinleton = new VolatileTest();
  12. }
  13. }
  14. }
  15. return sinleton;
  16. }
  17. }

②.静态内部类

  1. public class VolatileTest {
  2. private VolatileTest(){
  3. }
  4. private static class VolatileHolder{
  5. private static final VolatileTest INSTANCE = new VolatileTest();
  6. }
  7. public static VolatileTest getInstance(){
  8. return VolatileHolder.INSTANCE;
  9. }
  10. }

1.2jdk的spi机制

  1. resourcesMETA-INFOservices目录下定义接口的全路径接口名,在文件里定义实现类的全路径名,一个一行。
  2. 使用ServiceLoader.load(接口类)获取实现类

java方法以及框架总结 - 图1

1.3获取ip地址

  1. public static String getRemoteIp(HttpServletRequest request) {
  2. String xForwardedFor = request.getHeader("X-Forwarded-For");
  3. if (!StringUtils.isBlank(xForwardedFor)) {
  4. return xForwardedFor.split(",")[0].trim();
  5. }
  6. String nginxHeader = request.getHeader("X-Real-IP");
  7. return StringUtils.isBlank(nginxHeader) ? request.getRemoteAddr() : nginxHeader;
  8. }

二.Nacos

  1. 字符串null转换为""
  2. this.logName = Objects.toString(this.logName, "");

2.1获取ip信息

  1. #获取ip信息
  2. commons.util工具类
  3. InetUtils inetUtils;
  4. this.ip = this.inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
  5. #网络接口名在大多数操作系统上(包括WindowsLinuxUnix)是以eth开头,后面是网络接口的索引号,从0开始。如本机安了三块网卡,那么网络接口名就依次是eth0eth1eth2.NetworkInterface对象的toString方法可以返回网络接口的名称、显示名和这个网络接口上绑字的所有IP地址等信息
  6. NetworkInterface netInterface = NetworkInterface.getByName(this.networkInterface);

2.2创建观察者

  1. #创建观察者
  2. public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycle {
  3. private static final Logger log = LoggerFactory.getLogger(NacosWatch.class);
  4. private final NacosDiscoveryProperties properties;
  5. private final TaskScheduler taskScheduler;
  6. private final AtomicLong nacosWatchIndex;
  7. private final AtomicBoolean running;
  8. private ApplicationEventPublisher publisher;
  9. private ScheduledFuture<?> watchFuture;
  10. private Set<String> cacheServices;
  11. private HashMap<String, EventListener> subscribeListeners;
  12. public NacosWatch(NacosDiscoveryProperties properties) {
  13. this(properties, getTaskScheduler());
  14. }
  15. public NacosWatch(NacosDiscoveryProperties properties, TaskScheduler taskScheduler) {
  16. this.nacosWatchIndex = new AtomicLong(0L);
  17. this.running = new AtomicBoolean(false);
  18. this.cacheServices = new HashSet();
  19. this.subscribeListeners = new HashMap();
  20. this.properties = properties;
  21. this.taskScheduler = taskScheduler;
  22. }
  23. private static ThreadPoolTaskScheduler getTaskScheduler() {
  24. ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler();
  25. taskScheduler.initialize();
  26. return taskScheduler;
  27. }
  28. }

2.3反射

  1. #反射创建类
  2. public static NamingService createNamingService(Properties properties) throws NacosException {
  3. try {
  4. Class<?> driverImplClass = Class.forName("com.alibaba.nacos.client.naming.NacosNamingService");
  5. Constructor constructor = driverImplClass.getConstructor(Properties.class);
  6. NamingService vendorImpl = (NamingService)constructor.newInstance(properties);
  7. return vendorImpl;
  8. } catch (Throwable var4) {
  9. throw new NacosException(-400, var4);
  10. }
  11. }

2.4心跳定时任务

  1. /**
  2. * nacos心跳定时任务
  3. */
  4. @Slf4j
  5. public class BeatThread {
  6. private ScheduledExecutorService executorService;
  7. public void task(){
  8. log.info("进入task中");
  9. executorService = new ScheduledThreadPoolExecutor(1, new ThreadFactory() {
  10. @Override
  11. public Thread newThread(Runnable r) {
  12. Thread thread = new Thread(r);
  13. thread.setDaemon(true);
  14. thread.setName(String.valueOf(new Random().nextInt(10)));
  15. return thread;
  16. }
  17. });
  18. executorService.schedule(new BeatTask(),1,TimeUnit.SECONDS);
  19. }
  20. class BeatTask implements Runnable {
  21. public BeatTask() {
  22. }
  23. @Override
  24. public void run() {
  25. log.info("进入线程任务中了");
  26. executorService.schedule(new BeatTask(),1,TimeUnit.SECONDS);
  27. }
  28. }
  29. }

2.5故障转移

  1. public String reqAPI(String api, Map<String, String> params, List<String> servers, String method) {
  2. params.put("namespaceId", this.getNamespaceId());
  3. if (CollectionUtils.isEmpty(servers) && StringUtils.isEmpty(this.nacosDomain)) {
  4. throw new IllegalArgumentException("no server available");
  5. } else {
  6. Exception exception = new Exception();
  7. if (servers != null && !servers.isEmpty()) {
  8. Random random = new Random(System.currentTimeMillis());
  9. int index = random.nextInt(servers.size());
  10. for(int i = 0; i < servers.size(); ++i) {
  11. String server = (String)servers.get(index);
  12. try {
  13. return this.callServer(api, params, server, method);
  14. } catch (NacosException var11) {
  15. exception = var11;
  16. LogUtils.NAMING_LOGGER.error("request {} failed.", server, var11);
  17. } catch (Exception var12) {
  18. exception = var12;
  19. LogUtils.NAMING_LOGGER.error("request {} failed.", server, var12);
  20. }
  21. index = (index + 1) % servers.size();
  22. }
  23. throw new IllegalStateException("failed to req API:" + api + " after all servers(" + servers + ") tried: " + ((Exception)exception).getMessage());
  24. } else {
  25. int i = 0;
  26. while(i < 3) {
  27. try {
  28. return this.callServer(api, params, this.nacosDomain);
  29. } catch (Exception var13) {
  30. exception = var13;
  31. LogUtils.NAMING_LOGGER.error("[NA] req api:" + api + " failed, server(" + this.nacosDomain, var13);
  32. ++i;
  33. }
  34. }
  35. throw new IllegalStateException("failed to req API:/api/" + api + " after all servers(" + servers + ") tried: " + ((Exception)exception).getMessage());
  36. }
  37. }
  38. }