zoukankan      html  css  js  c++  java
  • 单例解决存储微信Token信息保留两小时

      采用单例模式可以存储初始化数据,比如第一次对/api/test接口进行了访问,传入的信息为“123”,则在两个小时之内返回的信息依然是“123”,无论传入的参数是什么,如果有效时间过了两个小时,比如传入的是“456”,则返回的就是“456”,之前的“123”,就会被替换调

    @Slf4j
    @RestController
    public class SwindleController {
    
        @RequestMapping(method = RequestMethod.POST, value = "/api/test",
                produces = MediaType.APPLICATION_JSON_VALUE + ";charset=utf-8",
                headers = "Accept=application/json")
        @ResponseStatus(HttpStatus.OK)
        public String test(@RequestBody  String str) {
            String result = test.getImp(str);
            return result;
        }
    }
    public class test {
    
        private test() {
    
        }
    
        private static String imp;   //定义要存储的变量
        private static Date date;    //定义上一次存储信息的时间
    
        public static String getImp(String str) {
            int minus = 0;
            if (null != date) {
                minus = (int) (new Date().getTime() - date.getTime());
            }
            if (imp == null || minus > 3600000) {
                synchronized (test.class) {
                    if (imp == null || minus > 3600000) {
                        imp = str;
                        date = new Date();
                    }
                }
            }
            return imp;
        }
    }

     test类也可以写成这样

    public class test {
    
        private test() {
    
        }
    
        private static String imp;   //定义要存储的变量
        private static Date date;    //定义上一次存储信息的时间
    
        public static String getImp(String str) {
            int minus = 0;
            if (null != date) {
                minus = (int) ((new Date().getTime() - date.getTime()) / (60 * 60 * 1000));
            }
            if (imp == null || minus > 2) {
                synchronized (test.class) {
                    if (imp == null || minus > 2) {
                        imp = str;
                        date = new Date();
                    }
                }
            }
            return imp;
        }
    }
    技术交流群: 233513714
  • 相关阅读:
    java IO流详解
    java设计模式之单例模式(几种写法及比较)
    JS定时刷新页面及跳转页面
    遍历map的四种方法
    String 中去掉空格
    TSP问题_遗传算法(STL大量使用)
    无向图的深度优先生成树和广度优先生成树
    Prim算法求最小生成树
    哈夫曼编码_静态库
    中序线索化二叉树
  • 原文地址:https://www.cnblogs.com/cnndevelop/p/6836757.html
Copyright © 2011-2022 走看看