您的位置:首页 > 数据库 > Redis

从零开始搭建自己的网站十八:redis管理点击量并定时存入数据库

2018-03-26 23:23 471 查看
上篇文章讲了如何配置redis,这篇文章我们就来配置定时器,定时把缓存在redis中的点击量更新到数据库中。Springboot中配置定时器就比较简单了。
1、在application中添加注解@EnableScheduling

2、配置定时任务serviceImpl代码,每天凌晨3点定时更新点击量,具体cron语法,感兴趣的童鞋可以自己去查阅,或者以后我再专门写一篇文章。
@Component
public class QuartzServiceImpl implements QuartzService {

private static final Logger logger = LoggerFactory.getLogger(QuartzServiceImpl.class);

@Autowired
private RedisClient redisClient;

@Autowired
private CountDao countDao;

/**
* 每天凌晨3点定时更新点击量
*/
@Override
@Scheduled(cron = "0 0 3 * * *")
public void timeToSaveClick() {
logger.info("开启保存点击量和评论量定时器:" + LocalDateTime.now());
List<Count> list = redisClient.getList(KeyType.GET_COUNT_LIST.getValue());
if (null != list && list.size() > 0) {
countDao.updateAllClick(list);
} else {
logger.info("redis缓存获取点击量失败:" + LocalDateTime.now());
}

}
}
mybatis中批量更新代码
<update id="updateAllClick" parameterType="java.util.List">
update artcount
<trim prefix="set" suffixOverrides=",">
<trim prefix="click =case" suffix="end,">
<foreach collection="list" item="item" index="index">
when id=#{item.id} then #{item.click}
</foreach>
</trim>
</trim>
where id in
<foreach collection="list" index="index" item="item" separator="," open="(" close=")">
#{item.id,jdbcType=BIGINT}
</foreach>
</update>
3、修改点击页面增加点击数到redis的逻辑  点击量serviceImpl代码
@Service
public class CountServiceImpl implements CountService {

private static final Logger logger = LoggerFactory.getLogger(CountServiceImpl.class);

@Autowired
private CountDao countDao;

@Autowired
private RedisClient redisClient;

@Override
public List<Count> getCountList() {
//先判断redis缓存是否存在
List<Count> list = redisClient.getList(KeyType.GET_COUNT_LIST.getValue());
if (null != list && list.size() > 0) {
return list;
} else {
list = countDao.getCountList();
try {
redisClient.setList(KeyType.GET_COUNT_LIST.getValue(), list);
} catch (Exception e) {
logger.error("redis缓存点击量list失败:", e);
}
return list;
}
}

@Override
public void addClickByArticleId(int id) {
List<Count> list = redisClient.getList(KeyType.GET_COUNT_LIST.getValue());
if (null != list && list.size() > 0) {
for (Count count : list) {
if (count.getArticleId() == id) {
count.setClick(count.getClick() + 1);
break;
}
}
try {
redisClient.setList(KeyType.GET_COUNT_LIST.getValue(), list);
} catch (Exception e) {
logger.error("更新redis点击量缓存list失败:", e);
countDao.addClickByArticleId(id);
}
} else {
countDao.addClickByArticleId(id);
}
}
@Override
public void addCommentByArticleId(int articleId) {
countDao.addCommentByArticleId(articleId);
}
}

欢迎转载,转载请注明出处 http://www.dingyinwu.com/article/58.html 如果文章中有任何问题或者可以改进的地方,请大家多提提意见,我会非常感激。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息