Springboot-结合ehcache实现文章浏览量功能(通过ip唯一)

本文介绍如何利用EhCache缓存框架优化单机应用中的文章浏览量统计功能,避免重复计数同一IP地址的多次点击,并减少数据库操作,提升服务器效率。

背景

想要实现一个单机应用,就是普通的浏览量功能实现,如果同一个ip地址点击的文章多次的话,只能算是一次点击,因为是分布式,所以不想安装Redis服务。
EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点,是Hibernate中默认的CacheProvider。
所以自己实现了一个使用缓存添加浏览量的功能,减少服务器的负担,要经常操作数据库。

前提条件

  1. 添加依赖 版本2.6.11用这个,较高版本在删掉了一些方法,高版本未实现
<!-- ehcache缓存   -->
    <dependency>
      <groupId>net.sf.ehcache</groupId>
      <artifactId>ehcache-core</artifactId>
      <version>2.6.11</version>
    </dependency>
  </dependencies>
  1. 在resources包下添加ehcache.xml 相关配置说明可以百度
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" dynamicConfig="false">
    <diskStore path="java.io.tmpdir"/>

    <!--日点击量缓存-->
    <cache name="dayHits" maxEntriesLocalHeap="500" eternal="true" overflowToDisk="true">
    </cache>

</ehcache>
  1. 修改application.yml文件
 # 缓存
 spring:
  cache:
    ehcache:
      config: ehcache.xml

controller

ApiResponse 只是我自定义返回的一个实体对象

/**
 * @description: 文章控制类
 * @author: yuxiang
 * @create: 2019-11-30 15:34
 **/
@RequestMapping("/article")
@RestController
public class ArticleController {

    @Autowired
    private ArticleService articleService;
   

    //缓存
    private static CacheManager cacheManager = CacheManager.newInstance();
    private static Long viewArticleTime = System.currentTimeMillis();

    /**
     * 增加浏览量
     * @param id
     * @return
     */
    @PostMapping("visitCount")
    public ApiResponse visitCount(@RequestParam("id")String id, HttpServletRequest request){
        ApiResponse response = new ApiResponse();

        try {
            Integer count = cacheCount(id, IpUtil.getIpAddr(request));
            response.setMsg("浏览量添加成功");
            response.setObj(count);
        }catch (Exception e){
            e.printStackTrace();
            return new ApiResponse<>(-1,"服务器错误,添加浏览量失败");
        }

        return response;
    }
    
    /**
     * 缓存点击量方法
     * @param articleId
     * @return
     */
    public Integer cacheCount(String articleId,String Ip){
        ArticleEntity articleEntity = articleService.findById(articleId);
        //查询缓存
        Ehcache cache = cacheManager.getEhcache("dayHits");
        Element element = cache.get(Ip+articleId+"_count");
        Integer count = 0;
        if(element!=null){
            //如果缓存存在,则不增加count
            count = (Integer) element.getValue();
        }else{
            count = articleEntity.getVisitCount()== null?0:articleEntity.getVisitCount();
            count++;
            cache.put(new Element(Ip+articleId+"_count",count));
        }
        cache.put(new Element(Ip+articleId+"_dayHitsDate",new SimpleDateFormat("yyyy-MM-dd").format(TimeUtil.getDayZero())));
        System.out.println("==========================>>>"+new SimpleDateFormat("yyyy-MM-dd").format(TimeUtil.getDayZero()));
        //超过有效时间更新数据库
        Long time = System.currentTimeMillis();
        if(time > (viewArticleTime+ 300000)){
            viewArticleTime = time;
            articleEntity.setVisitCount(count);
            articleService.saveArticle(articleEntity);
            cache.removeAll();
        }
        return count;
    }

}

工具类

重要:获取ip地址工具类

/**
 * @description: ip工具类
 * @author: yuxiang
 * @create: 2019-12-01 17:57
 **/
public class IpUtil {


    public static String getIpAddr(HttpServletRequest request){

        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();

        return ipAddress;
    }
}

/**
 * @Description 时间工具类
 * @Author yuxiang
 * @CreatedDate 2019/7/27 18:58
 */
public class TimeUtil {


    /**
     * 返回今天零点
     * @return
     */
    public  static Long getDayZero() {
        Calendar calendar = Calendar.getInstance();
        Long zero = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        return zero;
    }
    /**
     * 根据截至时间戳返回今天零点
     * @return
     */
    public  static Long getDayZero(Long endTime) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(endTime);
        Long zero = calendar.getTime().getTime() / (1000 * 3600 * 24) * (1000 * 3600 * 24) - TimeZone.getDefault().getRawOffset();
        return zero;
    }
    /**
     * 获取当前时间
     * @return
     */
    public  static Long getCurrent() {
        Calendar calendar = Calendar.getInstance();
        Long zero = calendar.getTime().getTime();
        return zero;
    }
}
参考

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

还是存在一些bug吧,这个能达到一天之内重复ip点击同一文章算一次点击,有时间再修改一下逻辑过来,对ehcache不是很熟悉,如果用注解的话,又达不到Redis根据key获取值的效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值