文章浏览量统计,low的做法是:用户每次浏览,前端会发送一个GET请求获取一篇文章详情时,会把这篇文章的浏览量+1,存进数据库里。

  1. 在GET请求的业务逻辑里进行了数据的写操作!
  2. 并发高的话,数据库压力太大;
  3. 同时,如果文章做了缓存和搜索引擎如ElasticSearch的存储,同步更新缓存和ElasticSearch更新同步更新太耗时,不更新就会导致数据不一致性。
  • HyperLogLog

HyperLogLogProbabilistic data Structures的一种,这类数据结构的基本大的思路就是使用统计概率上的算法,牺牲数据的精准性来节省内存的占用空间及提升相关操作的性能。

  • 设计思路
  1. 为保证真实的博文浏览量,根据用户访问的ip和文章id,进行唯一校验,即同一个用户多次访问同一篇文章,改文章访问量只增加1;
  2. 将用户的浏览量用opsForHyperLogLog().add(key,value)的存储在Redis中,在半夜浏览量低的时候,通过定时任务,将浏览量更新至数据库中。
  • sql
  1. DROP TABLE IF EXISTS `article`;
  2. CREATE TABLE `article` (
  3. `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  4. `title` varchar(100) NOT NULL COMMENT '标题',
  5. `content` varchar(1024) NOT NULL COMMENT '内容',
  6. `url` varchar(100) NOT NULL COMMENT '地址',
  7. `views` bigint(20) NOT NULL COMMENT '浏览量',
  8. `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  9. PRIMARY KEY (`id`)
  10. ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
  11. INSERT INTO article VALUES(1,'测试文章','content','url',10,NULL);

插入了一条数据,并设计访问量已经为10了,便于测试。

  • 项目依赖pom.xml
  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-web</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-aop</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-test</artifactId>
  12. </dependency>
  13. <!--mysql-->
  14. <dependency>
  15. <groupId>mysql</groupId>
  16. <artifactId>mysql-connector-java</artifactId>
  17. </dependency>
  18. <!-- mybatis -->
  19. <dependency>
  20. <groupId>org.mybatis.spring.boot</groupId>
  21. <artifactId>mybatis-spring-boot-starter</artifactId>
  22. <version>1.3.2</version>
  23. </dependency>
  24. <!-- redis -->
  25. <dependency>
  26. <groupId>org.springframework.boot</groupId>
  27. <artifactId>spring-boot-starter-data-redis</artifactId>
  28. </dependency>
  29. <dependency>
  30. <groupId>org.apache.commons</groupId>
  31. <artifactId>commons-pool2</artifactId>
  32. <version>2.0</version>
  33. </dependency>
  34. <!-- lombok-->
  35. <dependency>
  36. <groupId>org.projectlombok</groupId>
  37. <artifactId>lombok</artifactId>
  38. <optional>true</optional>
  39. </dependency>
  • application.yml
  1. spring:
  2. # 数据库配置
  3. datasource:
  4. url: jdbc:mysql://47.98.178.84:3306/dev
  5. username: dev
  6. password: password
  7. driver-class-name: com.mysql.cj.jdbc.Driver
  8. redis:
  9. host: 47.98.178.84
  10. port: 6379
  11. database: 1
  12. password: password
  13. timeout: 60s # 连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
  14. # 连接池配置,2.0中直接使用jedis或者lettuce配置连接池(使用lettuce,依赖中必须包含commons-pool2包)
  15. lettuce:
  16. pool:
  17. # 最大空闲连接数
  18. max-idle: 500
  19. # 最小空闲连接数
  20. min-idle: 50
  21. # 等待可用连接的最大时间,负数为不限制
  22. max-wait: -1s
  23. # 最大活跃连接数,负数为不限制
  24. max-active: -1
  25. # mybatis
  26. mybatis:
  27. mapper-locations: classpath:mapper/*.xml
  28. # type-aliases-package: cn.van.redis.view.entity
  • 自定义一个注解,用于新增文章浏览量到Redis
  1. @Target({ElementType.PARAMETER, ElementType.METHOD})
  2. @Retention(RetentionPolicy.RUNTIME)
  3. @Documented
  4. public @interface PageView {
  5. /**
  6. * 描述
  7. */
  8. String description() default "";
  9. }
  • 切面处理
  1. @Aspect
  2. @Configuration
  3. @Slf4j
  4. public class PageViewAspect {
  5. @Autowired
  6. private RedisUtils redisUtil;
  7. /**
  8. * 切入点
  9. */
  10. @Pointcut("@annotation(cn.van.redis.view.annotation.PageView)")
  11. public void PageViewAspect() {
  12. }
  13. /**
  14. * 切入处理
  15. * @param joinPoint
  16. * @return
  17. */
  18. @Around("PageViewAspect()")
  19. public Object around(ProceedingJoinPoint joinPoint) {
  20. Object[] object = joinPoint.getArgs();
  21. Object articleId = object[0];
  22. log.info("articleId:{}", articleId);
  23. Object obj = null;
  24. try {
  25. String ipAddr = IpUtils.getIpAddr();
  26. log.info("ipAddr:{}", ipAddr);
  27. String key = "articleId_" + articleId;
  28. // 浏览量存入redis中
  29. Long num = redisUtil.add(key,ipAddr);
  30. if (num == 0) {
  31. log.info("该ip:{},访问的浏览量已经新增过了", ipAddr);
  32. }
  33. obj = joinPoint.proceed();
  34. } catch (Throwable e) {
  35. e.printStackTrace();
  36. }
  37. return obj;
  38. }
  39. }
  • 工具类RedisUtils.java
  1. @Component
  2. public class RedisUtils {
  3. @Resource
  4. private RedisTemplate<String, Object> redisTemplate;
  5. /**
  6. * 删除缓存
  7. * @param key 可以传一个值 或多个
  8. */
  9. public void del(String... key) {
  10. redisTemplate.delete(key[0]);
  11. }
  12. /**
  13. * 计数
  14. * @param key
  15. * @param value
  16. */
  17. public Long add(String key, Object... value) {
  18. return redisTemplate.opsForHyperLogLog().add(key,value);
  19. }
  20. /**
  21. * 获取总数
  22. * @param key
  23. */
  24. public Long size(String key) {
  25. return redisTemplate.opsForHyperLogLog().size(key);
  26. }
  27. }
  • 工具类 IpUtils.java

该工具类我在Mac下测试没问题,Windows下如果有问题,请反馈给我

  1. @Slf4j
  2. public class IpUtils {
  3. public static String getIpAddr() {
  4. try {
  5. Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
  6. InetAddress ip = null;
  7. while (allNetInterfaces.hasMoreElements()) {
  8. NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
  9. if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
  10. continue;
  11. } else {
  12. Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
  13. while (addresses.hasMoreElements()) {
  14. ip = addresses.nextElement();
  15. if (ip != null && ip instanceof Inet4Address) {
  16. log.info("获取到的ip地址:{}", ip.getHostAddress());
  17. return ip.getHostAddress();
  18. }
  19. }
  20. }
  21. }
  22. } catch (Exception e) {
  23. log.error("获取ip地址失败,{}",e);
  24. }
  25. return null;
  26. }
  27. }

ArticleService.java里面的代码比较简单,详见文末源码。

  1. @Component
  2. @Slf4j
  3. public class ArticleViewTask {
  4. @Resource
  5. private RedisUtils redisUtil;
  6. @Resource
  7. ArticleService articleService;
  8. // 每天凌晨一点执行
  9. @Scheduled(cron = "0 0 1 * * ? ")
  10. @Transactional(rollbackFor=Exception.class)
  11. public void createHyperLog() {
  12. log.info("浏览量入库开始");
  13. List<Long> list = articleService.getAllArticleId();
  14. list.forEach(articleId ->{
  15. // 获取每一篇文章在redis中的浏览量,存入到数据库中
  16. String key = "articleId_"+articleId;
  17. Long view = redisUtil.size(key);
  18. if(view>0){
  19. ArticleDO articleDO = articleService.getById(articleId);
  20. Long views = view + articleDO.getViews();
  21. articleDO.setViews(views);
  22. int num = articleService.updateArticleById(articleDO);
  23. if (num != 0) {
  24. log.info("数据库更新后的浏览量为:{}", views);
  25. redisUtil.del(key);
  26. }
  27. }
  28. });
  29. log.info("浏览量入库结束");
  30. }
  31. }
  1. @RestController
  2. @Slf4j
  3. public class PageController {
  4. @Autowired
  5. private ArticleService articleService;
  6. @Autowired
  7. private RedisUtils redisUtil;
  8. /**
  9. * 访问一篇文章时,增加其浏览量:重点在的注解
  10. * @param articleId:文章id
  11. * @return
  12. */
  13. @PageView
  14. @RequestMapping("/{articleId}")
  15. public String getArticle(@PathVariable("articleId") Long articleId) {
  16. try{
  17. ArticleDO blog = articleService.getById(articleId);
  18. log.info("articleId = {}", articleId);
  19. String key = "articleId_"+articleId;
  20. Long view = redisUtil.size(key);
  21. log.info("redis 缓存中浏览数:{}", view);
  22. //直接从缓存中获取并与之前的数量相加
  23. Long views = view + blog.getViews();
  24. log.info("文章总浏览数:{}", views);
  25. } catch (Throwable e) {
  26. return "error";
  27. }
  28. return "success";
  29. }
  30. }

这里,具体的Service中的方法因为都被我放在Controller中处理了,所以就是剩下简单的Mapper调用了,这里就不浪费时间了,详见文末源码。(按理说,这些逻辑处理,应该放在Service处理的,请按实际情况优化)

启动项目,测试访问量,先请求http://localhost:8080/1,日志打印如下:

  1. 2019-03-2623:50:50.047 INFO 2970 --- [nio-8080-exec-1] cn.van.redis.view.aspect.PageViewAspect : articleId:1
  2. 2019-03-2623:50:50.047 INFO 2970 --- [nio-8080-exec-1] cn.van.redis.view.utils.IpUtils : 获取到的ip地址:192.168.1.104
  3. 2019-03-2623:50:50.047 INFO 2970 --- [nio-8080-exec-1] cn.van.redis.view.aspect.PageViewAspect : ipAddr:192.168.1.104
  4. 2019-03-2623:50:50.139 INFO 2970 --- [nio-8080-exec-1] io.lettuce.core.EpollProvider : Starting without optional epoll library
  5. 2019-03-2623:50:50.140 INFO 2970 --- [nio-8080-exec-1] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
  6. 2019-03-2623:50:50.349 INFO 2970 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
  7. 2019-03-2623:50:50.833 INFO 2970 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
  8. 2019-03-2623:50:50.872 INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController : articleId = 1
  9. 2019-03-2623:50:50.899 INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController : redis 缓存中浏览数:1
  10. 2019-03-2623:50:50.900 INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController : 文章总浏览数:11

观察一下,数据库,访问量确实没有增加,本机再次访问,发现,日志打印如下:

  1. 2019-03-2623:51:14.658 INFO 2970 --- [nio-8080-exec-3]
  2. cn.van.redis.view.aspect.PageViewAspect : articleId:1
  3. 2019-03-2623:51:14.658 INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.utils.IpUtils : 获取到的ip地址:192.168.1.104
  4. 2019-03-2623:51:14.658 INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.aspect.PageViewAspect : ipAddr:192.168.1.104
  5. 2019-03-2623:51:14.692 INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.aspect.PageViewAspect : ip:192.168.1.104,访问的浏览量已经新增过了
  6. 2019-03-2623:51:14.752 INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController : articleId = 1
  7. 2019-03-2623:51:14.760 INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController : redis 缓存中浏览数:1
  8. 2019-03-2623:51:14.761 INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController : 文章总浏览数:11
  • 定时任务触发,日志打印如下
  1. 2019-03-27 01:00:00.265 INFO 2974 --- [ scheduling-1] cn.van.redis.view.task.ArticleViewTask : 浏览量入库开始
  2. 2019-03-27 01:00:00.448 INFO 2974 --- [ scheduling-1] io.lettuce.core.EpollProvider : Starting without optional epoll library
  3. 2019-03-27 01:00:00.449 INFO 2974 --- [ scheduling-1] io.lettuce.core.KqueueProvider : Starting without optional kqueue library
  4. 2019-03-27 01:00:00.663 INFO 2974 --- [ scheduling-1] cn.van.redis.view.task.ArticleViewTask : 数据库更新后的浏览量为:11
  5. 2019-03-27 01:00:00.682 INFO 2974 --- [ scheduling-1] cn.van.redis.view.task.ArticleViewTask : 浏览量入库结束

观察一下数据库,发现数据库中的浏览量增加到11,同时,Redis中的浏览量没了,说明成功!

Github 示例代码

版权声明:本文为vandusty原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/vandusty/p/11415882.html