基于redis实现昨日今日浏览量统计---案例

0.准备yml + pom

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/viewtest?serverTimezone=UTC
    username: root
    password: 1234
#Redis相关配置
  redis:
    host: localhost
    port: 6379
    #password: 123456
    database: 0 #操作的是0号数据库
    jedis:
      #Redis连接池配置
      pool:
        max-active: 8 #最大连接数
        max-wait: 1ms #连接池最大阻塞等待时间
        max-idle: 4 #连接池中的最大空闲连接
        min-idle: 0 #连接池中的最小空闲连接
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.12</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.daydream</groupId>
    <artifactId>viewTest</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>viewTest</name>
    <description>viewTest</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.3.1</version>
        </dependency>
        <dependency>
            <groupId>com.mysql</groupId>
            <artifactId>mysql-connector-j</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>2.7.2</version>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.9.0</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

1.程序启动时,将数据库中的昨日统计数据加载到redis,将今日的统计数据设置为0也加载到redis。

package com.daydream.common;

import com.daydream.service.ViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDate;

@Component
public class RunAfterStartup {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ViewService viewService;

    @EventListener(ApplicationReadyEvent.class)
    public void runAfterStartup() {
        // 查询昨日浏览量
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.plusDays(-1);
        String yesterdayViews = viewService.getViewData(yesterday);

        if (yesterdayViews == null || yesterdayViews == ""){
            yesterdayViews = "0";
        }

        // 加载昨日浏览量数据到redis
        redisTemplate.opsForValue().set("yesterday",yesterdayViews);
        // 将今日数据置为0后存到redis
        redisTemplate.opsForValue().set("today",0 + "");
    }
}

2.相关数据更新/查询时,只对redis更新/查询,不更新数据库,也不从数据库查询。

package com.daydream.controller;

import com.daydream.pojo.ViewDto;
import com.daydream.service.ViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;

@RestController
@RequestMapping("/views")
public class ViewController {
    @Autowired
    private RedisTemplate redisTemplate;
    @GetMapping("viewsData")
    public ViewDto getViewsData() {
        String yesterday = (String)redisTemplate.opsForValue().get("yesterday");
        String today = (String)redisTemplate.opsForValue().get("today");
        return new ViewDto(today,yesterday);
    }

    @GetMapping("update")
    public void updateViewsData() {
        String today = (String)redisTemplate.opsForValue().get("today");
        Integer newToday = Integer.parseInt(today) + 1;
        redisTemplate.opsForValue().set("today",newToday + "");
        System.out.println("redis数据成功+1,当前值:" + newToday);
    }
}

3.每天的晚上12点,利用定时注解@Scheduled(),将redis的今日数据持久化到数据库,将今日数据转为昨日数据,将今日数据初始化。(注意要在启动类加上开启定时任务注解—@EnableScheduling)

package com.daydream.common;
 
import com.daydream.service.ViewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
 
/**
 * 定时任务的使用
 **/
@Component
public class ScheduledTask {
    @Autowired
    ViewService viewService;
    @Autowired
    private RedisTemplate redisTemplate;

    @Scheduled(cron="0 0 12 * * ?")   //每天十二点执行一次
    //@Scheduled(cron = "0/5 * *  * * ? ")   //每5秒执行一次
    public void execute() throws InterruptedException {
        // 获取今日数据
        String today = (String)redisTemplate.opsForValue().get("today");
        // 将今日数据存到数据库
        viewService.insertViews(today);
        // 将redis今日数据置为昨日浏览量(昨日浏览量不会更新 放心删除)
        redisTemplate.opsForValue().set("yesterday",today);
        // 将今日浏览量置为0(此操作需要延时双删 以防缓存与数据库数据不一致)
        redisTemplate.opsForValue().set("today",0 + "");
        // 延时双删
        Thread.sleep(1000*2); // 休眠2秒
        redisTemplate.opsForValue().set("today",0 + "");
    }
}

此操作要用到service和mapper层相关类

package com.daydream.service;

import com.daydream.mapper.ViewMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;

@Service
public class ViewService {
    @Autowired
    private ViewMapper viewMapper;
    public String getViewData(LocalDate time) {
        return viewMapper.getViewData(time);
    }
    public void insertViews(String today) {
        LocalDate time = LocalDate.now().plusDays(-1);
        viewMapper.insertViews(time,today);
    }
}

package com.daydream.mapper;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDate;

@Mapper
public interface ViewMapper {
    @Select("select views from view_info where #{time} = time")
    String getViewData(@Param("time") LocalDate time);

    @Insert("insert into view_info(time, views)VALUES (#{time},#{today})")
    void insertViews(@Param("time") LocalDate time,@Param("today") String today);
}

4.问:这样操作,昨日的数据都是从redis拿的,那怎么保证拿到的数据就是存入数据库的数据呢?

我们在更新数据时,有一个操作,是先更新到数据库,然后更新redis中的数据。在更新redis的时候做了一个延时双删。将双删的间隔设置为1~2s。一般不会出现缓存和数据库数据不一致的问题。

5.redis为什么读写快?

基于内存、单线程

6.案例中的数据表设计

在这里插入图片描述

7.案例源码 【点击下载】

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值