高併發下瀏覽量入庫設計

1、背景

文章瀏覽量統計,low的作法是:用戶每次瀏覽,前端會發送一個GET請求獲取一篇文章詳情時,會把這篇文章的瀏覽量+1,存進數據庫裏。前端

1.1 這麼作,有幾個問題:

  1. GET請求的業務邏輯裏進行了數據的寫操做!
  2. 併發高的話,數據庫壓力太大;
  3. 同時,若是文章作了緩存和搜索引擎如Elasticsearch的存儲,同步更新緩存和Elasticsearch更新同步更新太耗時,不更新就會致使數據不一致性。

1.2 解決方案

  • HyperLogLog

HyperLogLogProbabilistic data Structures的一種,這類數據結構的基本大的思路就是使用統計機率上的算法,犧牲數據的精準性來節省內存的佔用空間及提高相關操做的性能。java

  • 設計思路
  1. 爲保證真實的博文瀏覽量,根據用戶訪問的ip和文章id,進行惟一校驗,即同一個用戶屢次訪問同一篇文章,改文章訪問量只增長1;
  2. 將用戶的瀏覽量用opsForHyperLogLog().add(key,value)的存儲在Redis中,在半夜瀏覽量低的時候,經過定時任務,將瀏覽量更新至數據庫中。

2、 手把手實現

2.1 項目配置

  • sql
DROP TABLE IF EXISTS `article`;

CREATE TABLE `article` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `title` varchar(100) NOT NULL COMMENT '標題',
  `content` varchar(1024) NOT NULL COMMENT '內容',
  `url` varchar(100) NOT NULL COMMENT '地址',
	`views` bigint(20) NOT NULL COMMENT '瀏覽量',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '建立時間',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

INSERT INTO article VALUES(1,'測試文章','content','url',10,NULL);
複製代碼

插入了一條數據,並設計訪問量已經爲10了,便於測試。mysql

  • 項目依賴pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!--mysql-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>1.3.2</version>
</dependency>
<!-- redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
    <version>2.0</version>
</dependency>
<!-- lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
複製代碼
  • application.yml
spring:
  # 數據庫配置
 datasource:
 url: jdbc:mysql://47.98.178.84:3306/dev
 username: dev
 password: password
 driver-class-name: com.mysql.cj.jdbc.Driver
 redis:
 host: 47.98.178.84
 port: 6379
 database: 1
 password: password
 timeout: 60s  # 鏈接超時時間,2.0 中該參數的類型爲Duration,這裏在配置的時候須要指明單位
    # 鏈接池配置,2.0中直接使用jedis或者lettuce配置鏈接池(使用lettuce,依賴中必須包含commons-pool2包)
 lettuce:
 pool:
        # 最大空閒鏈接數
 max-idle: 500
        # 最小空閒鏈接數
 min-idle: 50
        # 等待可用鏈接的最大時間,負數爲不限制
 max-wait:  -1s
        # 最大活躍鏈接數,負數爲不限制
 max-active: -1


# mybatis
mybatis:
 mapper-locations: classpath:mapper/*.xml
# type-aliases-package: cn.van.redis.view.entity
複製代碼

2.2 瀏覽量的切面設計

  • 自定義一個註解,用於新增文章瀏覽量到Redis
@Target({ElementType.PARAMETER, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface PageView {
    /** * 描述 */
    String description() default "";
}
複製代碼
  • 切面處理
@Aspect
@Configuration
@Slf4j
public class PageViewAspect {

    @Autowired
    private RedisUtils redisUtil;

    /**
     * 切入點
     */
    @Pointcut("@annotation(cn.van.redis.view.annotation.PageView)")
    public void PageViewAspect() {

    }

    /**
     * 切入處理
     * @param joinPoint
     * @return
     */
    @Around("PageViewAspect()")
    public  Object around(ProceedingJoinPoint joinPoint) {
        Object[] object = joinPoint.getArgs();
        Object articleId = object[0];
        log.info("articleId:{}", articleId);
        Object obj = null;
        try {
            String ipAddr = IpUtils.getIpAddr();
            log.info("ipAddr:{}", ipAddr);
            String key = "articleId_" + articleId;
            // 瀏覽量存入redis中
            Long num = redisUtil.add(key,ipAddr);
            if (num == 0) {
                log.info("該ip:{},訪問的瀏覽量已經新增過了", ipAddr);
            }
            obj = joinPoint.proceed();
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return obj;
    }
}
複製代碼
  • 工具類RedisUtils.java
@Component
public  class RedisUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /** * 刪除緩存 * @param key 能夠傳一個值 或多個 */
    public void del(String... key) {
        redisTemplate.delete(key[0]);
    }

    /** * 計數 * @param key * @param value */
    public Long add(String key, Object... value) {
        return redisTemplate.opsForHyperLogLog().add(key,value);
    }
    /** * 獲取總數 * @param key */
    public Long size(String key) {
        return redisTemplate.opsForHyperLogLog().size(key);
    }

}
複製代碼
  • 工具類 IpUtils.java

該工具類我在Mac下測試沒問題,Windows下若是有問題,請反饋給我git

@Slf4j
public class IpUtils {

    public static String getIpAddr() {
        try {
            Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
            InetAddress ip = null;
            while (allNetInterfaces.hasMoreElements()) {
                NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
                if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
                    continue;
                } else {
                    Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        ip = addresses.nextElement();
                        if (ip != null && ip instanceof Inet4Address) {
                            log.info("獲取到的ip地址:{}", ip.getHostAddress());
                            return ip.getHostAddress();
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.error("獲取ip地址失敗,{}",e);
        }
        return null;
    }
}
複製代碼

2.3 同步任務ArticleViewTask.java

ArticleService.java裏面的代碼比較簡單,詳見文末源碼。github

@Component
@Slf4j
public class ArticleViewTask {

    @Resource
    private RedisUtils redisUtil;
    @Resource
    ArticleService articleService;

	// 天天凌晨一點執行
    @Scheduled(cron = "0 0 1 * * ? ")
    @Transactional(rollbackFor=Exception.class)
    public void createHyperLog() {
        log.info("瀏覽量入庫開始");

        List<Long> list = articleService.getAllArticleId();
        list.forEach(articleId ->{
            // 獲取每一篇文章在redis中的瀏覽量,存入到數據庫中
            String key  = "articleId_"+articleId;
            Long view = redisUtil.size(key);
            if(view>0){
                ArticleDO articleDO = articleService.getById(articleId);
                Long views = view + articleDO.getViews();
                articleDO.setViews(views);
                int num = articleService.updateArticleById(articleDO);
                if (num != 0) {
                    log.info("數據庫更新後的瀏覽量爲:{}", views);
                    redisUtil.del(key);
                }
            }
        });
        log.info("瀏覽量入庫結束");
    }

}
複製代碼

2.4 測試接口PageController.java

@RestController
@Slf4j
public class PageController {

    @Autowired
    private ArticleService articleService;

    @Autowired
    private RedisUtils redisUtil;

    /** * 訪問一篇文章時,增長其瀏覽量:重點在的註解 * @param articleId:文章id * @return */
    @PageView
    @RequestMapping("/{articleId}")
    public String getArticle(@PathVariable("articleId") Long articleId) {
        try{
            ArticleDO blog = articleService.getById(articleId);
            log.info("articleId = {}", articleId);
            String key = "articleId_"+articleId;
            Long view = redisUtil.size(key);
            log.info("redis 緩存中瀏覽數:{}", view);
            //直接從緩存中獲取並與以前的數量相加
            Long views = view + blog.getViews();
            log.info("文章總瀏覽數:{}", views);
        } catch (Throwable e) {
            return  "error";
        }
        return  "success";
    }
}
複製代碼

這裏,具體的Service中的方法由於都被我放在Controller中處理了,因此就是剩下簡單的Mapper調用了,這裏就不浪費時間了,詳見文末源碼。(按理說,這些邏輯處理,應該放在Service處理的,請按實際狀況優化)web

3、 測試

啓動項目,測試訪問量,先請求http://localhost:8080/1,日誌打印以下:redis

2019-03-2623:50:50.047  INFO 2970 --- [nio-8080-exec-1]  cn.van.redis.view.aspect.PageViewAspect  : articleId:1
2019-03-2623:50:50.047  INFO 2970 --- [nio-8080-exec-1] cn.van.redis.view.utils.IpUtils          : 獲取到的ip地址:192.168.1.104
2019-03-2623:50:50.047  INFO 2970 --- [nio-8080-exec-1] cn.van.redis.view.aspect.PageViewAspect  : ipAddr:192.168.1.104
2019-03-2623:50:50.139  INFO 2970 --- [nio-8080-exec-1] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2019-03-2623:50:50.140  INFO 2970 --- [nio-8080-exec-1] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
2019-03-2623:50:50.349  INFO 2970 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Starting...
2019-03-2623:50:50.833  INFO 2970 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Start completed.
2019-03-2623:50:50.872  INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController    : articleId = 1
2019-03-2623:50:50.899  INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController    : redis 緩存中瀏覽數:1
2019-03-2623:50:50.900  INFO 2970 --- [nio-8080-exec-1] c.v.r.v.web.controller.PageController    : 文章總瀏覽數:11
複製代碼

觀察一下,數據庫,訪問量確實沒有增長,本機再次訪問,發現,日誌打印以下:算法

2019-03-2623:51:14.658  INFO 2970 --- [nio-8080-exec-3] 
cn.van.redis.view.aspect.PageViewAspect  : articleId:1
2019-03-2623:51:14.658  INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.utils.IpUtils          : 獲取到的ip地址:192.168.1.104
2019-03-2623:51:14.658  INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.aspect.PageViewAspect  : ipAddr:192.168.1.104
2019-03-2623:51:14.692  INFO 2970 --- [nio-8080-exec-3] cn.van.redis.view.aspect.PageViewAspect  : 該ip:192.168.1.104,訪問的瀏覽量已經新增過了
2019-03-2623:51:14.752  INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController    : articleId = 1
2019-03-2623:51:14.760  INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController    : redis 緩存中瀏覽數:1
2019-03-2623:51:14.761  INFO 2970 --- [nio-8080-exec-3] c.v.r.v.web.controller.PageController    : 文章總瀏覽數:11
複製代碼
  • 定時任務觸發,日誌打印以下
2019-03-27 01:00:00.265  INFO 2974 --- [   scheduling-1] cn.van.redis.view.task.ArticleViewTask   : 瀏覽量入庫開始
2019-03-27 01:00:00.448  INFO 2974 --- [   scheduling-1] io.lettuce.core.EpollProvider            : Starting without optional epoll library
2019-03-27 01:00:00.449  INFO 2974 --- [   scheduling-1] io.lettuce.core.KqueueProvider           : Starting without optional kqueue library
2019-03-27 01:00:00.663  INFO 2974 --- [   scheduling-1] cn.van.redis.view.task.ArticleViewTask   : 數據庫更新後的瀏覽量爲:11
2019-03-27 01:00:00.682  INFO 2974 --- [   scheduling-1] cn.van.redis.view.task.ArticleViewTask   : 瀏覽量入庫結束
複製代碼

觀察一下數據庫,發現數據庫中的瀏覽量增長到11,同時,Redis中的瀏覽量沒了,說明成功!spring

4、總結

4.1 技術交流

  1. 風塵博客
  2. 風塵博客-博客園
  3. 風塵博客-CSDN

關注公衆號,瞭解更多:sql

風塵博客

4.2 源碼地址

Github 示例代碼

相關文章
相關標籤/搜索