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
  • 相关阅读:
    Tomcat常用配置
    java开发规范总结_命名规范
    Android学习笔记(广播机制)
    Java Web 实现Mysql 数据库备份与还原
    interfaces
    windows phone 1
    正在写。。
    Exceptions
    类的非常简单的应用
    say hello
  • 原文地址:https://www.cnblogs.com/cnndevelop/p/6836757.html
Copyright © 2011-2022 走看看