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

 

转载于:https://www.cnblogs.com/cnndevelop/p/6836757.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值