在实现积分项目业务中,对不同场景设置了不同的key-value缓存到了redis中。但是因为对不同业务的key需要缓存的时间不尽相同,这里自定义工具类来实现。
设置redis缓存key,截取部分代码:
try{
//cacheManager就相当从redis链接池获取一个连接,具体工厂类获取在后面备注
cacheManager = (RedisCacheManager) CacheManagerFactory.getCacheManager();
totalMonCount = Float.parseFloat(cacheManager.getString(monthKey)) + centCount;
if (centLimitByMonth != -1){
if (totalMonCount > centLimitByMonth) {
// 超出月上限不再累计
logger.error("exceeds the month limit cents! [" + totalMonCount + "] code:[" + code + "]");
return null;
}
}
//当未超出月额度,此时要对日额度进行判断;只需判断其是否超出日上限积分
if (dayKey != null){
//累积积分;因为签到其实是没有每日积分的,是按次数规则累积的;但为了统一,直接用centCount代替(都是签一次1分)
totalDayCount = Float.parseFloat(cacheManager.getString(dayKey)) + centCount;
if (centLimitByDay != -1){
if (totalDayCount > centLimitByDay){
logger.info("[ERROR]teacher everyday assign cents > month limit! total: ["+totalDayCount+"]");
return null;
}
}
cacheManager.set(dayKey,totalDayCount.toString(),DateUtil.getSecsToEndOfCurrentDay());
}
//对月限制key进行积分累加
//每月1号凌晨1点启动脚本删除,同时设置了保存到月底缓存时间双重保障
cacheManager.set(monthKey, totalMonCount.toString(), DateUtil.getSecsToEndOfCurrentDay());
logger.info("==monthkey:"+monthKey+"---value:"+totalMonCount);
}
...
}catch(Exception e){
logger.error("===cache redis fail!");
e.printStackTrace();
}finally {
if (cacheManager != null){
cacheManager.close();
}
}
//工厂类获取redis链接
public class CacheManagerFactory {
private static ICacheManager cacheManager;
private CacheManagerFactory(){
};
public static ICacheManager getCacheManager(){
if(cacheManager == null){
synchronized (CacheManagerFactory.class) {
if(cacheManager == null){
JedisPooler jedisPooler = RedisPoolerFactory.getJedisPooler();
cacheManager = new RedisCacheManager(jedisPooler);
}
}
}
return cacheManager;
}
}
//redis链接池工厂类获取链接
public class