一、简述方法
通过设置redis的key来实现每天自动重置次数。可以这样来设置customerid + new date()(用年月日表示)。那么取值的时候,必须为当天。做到了以一天为周期的key的变化。
二、代码
private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
/**
* 设置用户每天各种点击请求次数缓存
*/
public void setRequestNumCache(String customerId, String type, Integer count) {
String day = dateFormat.format(new Date());
String key = type + day + "_" + customerId;
cacheManager.set(key, count, 24 * 60 * 60 * 2);
}
/**
* 获得用户每天各种点击请求的次数
*
*/
public Integer getReqNumCache(String customerId, String type) {
String day = dateFormat.format(new Date());
String key = type + day + "_" + customerId;
Object val = cacheManager.get(key);
if (val == null) {
return 0;
}
if (val instanceof Integer) {
return (Integer) val;
}
return null;
}