springboot+EHcache 实现文章浏览量的缓存和超时更新
来源:互联网 发布:儿童英语网络课程好吗 编辑:程序博客网 时间:2024/06/05 07:02
问题描述
当我们需要统计文章的浏览量的时候,最常规的做法就是:
1.访问文章链接www.abc.com/article/{id}
2.在控制层获取Article实体
3.得到文章浏览量count并且count++
4.最后update实体Article。
这么做对没有访问量的网站来说很棒,如果网站访问量很大,这么不停的读写数据库,会对服务器造成很大的压力。
解决思路
引入Ehcache,将文章的访问量存在cache中,每点击一次文章,将cache中的count加1.在有效的时间内访问文章只是将cache中的数据+1,超过指定时间则进行一次数据库更新。
解决方案
本文是在springboot整合ehcache的环境下验证的。springboot版本1.5.2 。ehcache版本2.6.11。springboot整合ehcache的步骤很简单,下面简单提一下,在pom文件中引入ehcache依赖
<dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version></dependency>
在类路径下存放ehcache.xml文件。
在application.yml中指定:
spring: cache: jcache: config: classpath:ehcache.xml
最后在启动类标注@EnableCaching
引入缓存之后,接着我们的正题
- 在ehcache.xml文件中定义dayHits缓存
<cache name="dayHits" maxEntriesLocalHeap="500" eternal="true" overflowToDisk="true">
</cache>
表示保存当日点击量的 - 在controller层定义缓存点击量的方法
public Integer cacheCount(Long articleId){ Content content = contentRepository.findOne(articleId); Ehcache cache = cacheManager.getEhcache("dayHits"); Element element = cache.get(articleId+"_count"); Integer count = 0; if(element!=null){ count = (Integer) element.getValue(); }else{ count = content.getHits()== null?0:content.getHits(); } count++; cache.put(new Element(articleId+"_count",count)); cache.put(new Element(articleId+"_dayHitsDate",SystemUtils.getNowDate())); Long time = System.currentTimeMillis(); if(time > (viewArticleTime+ 300000)){ viewArticleTime = time; content.setHits(count); contentRepository.save(content); cache.removeAll(); } return count; }
3.在查看文章方法中进行调用。
@RequestMapping(value = "article/{id}",method = RequestMethod. GET) public String detail(@PathVariable Long id,ModelMap map){ Integer hits = cacheCount(id); }
4.其中局部变量的定义:
private static CacheManager cacheManager = CacheManager.newInstance(); private static Long viewArticleTime = System.currentTimeMillis();
5.保存访问看看效果吧。
0 0
- springboot+EHcache 实现文章浏览量的缓存和超时更新
- DiscuzX2.5 帖子页面更新浏览量 缓存机制
- spring和ehcache整合,实现基于注解的缓存实现
- 很不错的ehcache缓存文章
- SpringMVC Ehcache的缓存实现
- 刷新页面,js实现文章浏览量自动更新
- springboot【15】缓存之EhCache
- ehcache-02 : spring整合ehcache 注解实现查询缓存,并实现实时缓存更新或删除
- 四十一、如何准确的统计文章浏览量(pv)
- JNotify和EHcache实现缓存技术
- 更新文章浏览次数
- spring+ehcache实现的缓存查询参数。
- spring+ehcache实现的缓存查询参数
- 【phpcms-v9】phpcms-v9中首页、频道页、列表页如何显示文章的浏览量和评论数
- phpcms-v9中首页、频道页、列表页如何显示文章的浏览量和评论数
- hibernate的Ehcache和Oscache缓存应用
- ehcache 实现前端缓存
- Ehcache分布式缓存实现
- 嵌套的标题边框
- yum安装(卸载)本地rpm包
- WPF触屏Touch事件在嵌套控件中的响应问题
- 【Android】退出多个Activity方法(四)
- js判断变量是否是数组(跨浏览器和ECMA)
- springboot+EHcache 实现文章浏览量的缓存和超时更新
- 微信硬件开发系列教程AA1
- C/C++疑问之为何一般采用循环队列而不是顺序队列
- cocos2D 程序代码分析 3
- jquery选中option的方法
- Tomcat 8080端口被占用(命令解决)
- git clone命令详解
- 搭建ZABBIX监控
- 自动建立swap分区脚本