当前位置: 移动技术网 > IT编程>开发语言>Java > springboot+EHcache 实现文章浏览量的缓存和超时更新

springboot+EHcache 实现文章浏览量的缓存和超时更新

2019年07月22日  | 移动技术网IT编程  | 我要评论

问题描述

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

1.访问文章链接}

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.保存访问看看效果吧。

以上所述是小编给大家介绍的springboot+ehcache 实现文章浏览量的缓存和超时更新,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网