单例解决存储微信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

 

posted @   大浪不惊涛  阅读(451)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
点击右上角即可分享
微信分享提示