在springboot中使用EHcache 如何实现文章浏览量的更新与缓存

发布时间:2020-11-18 15:26:31 作者:Leah
来源:亿速云 阅读:272

在springboot中使用EHcache 如何实现文章浏览量的更新与缓存?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

问题描述

当我们需要统计文章的浏览量的时候,最常规的做法就是:

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&#63;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();

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

推荐阅读:
  1. Spring Boot如何使用EhCache演示
  2. 怎么在SpringBoot中使用Redis和Ehcache缓存Shiro

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

springboot hcache ehcache

上一篇:jdk如何在Ubuntu环境中安装

下一篇:Oracle数据库如何实现连接Java并操作

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》