1.Spring Boot 2.X 学习之缓存

Spring Boot 2.X 整合Redis缓存


Gitee仓库地址:https://gitee.com/tadechen/sprintboot-01-cache

1. 通过Docker安装Redis

  1. 在命令行中使用命令docker pull redis:latest安装Redis最新版Docker
  2. 在命令行中使用命令docker run -itd --name redis-test -p 6379:6379 redis运行Redis镜像,并将端口映射到6379端

2. 在Maven中配置Spring BootRedis

pom.xml:

<?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.4.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.zyx</groupId>
    <artifactId>sprintboot-01-cache</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>sprintboot-01-cache</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.4.1</version>
        </dependency>
        <dependency>
            <groupId>com.zaxxer</groupId>
            <artifactId>HikariCP</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</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>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.yml:

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:///cache?serverTimezone=Asia/Shanghai
    username: root
    password: *******
    type: com.zaxxer.hikari.HikariDataSource
    hikari:
      pool-name: CACHE_POOL
      maximum-pool-size: 50
      minimum-idle: 5
  redis:
    host: localhost


mybatis-plus:
  type-aliases-package: com.zyx.sprintboot01cache.entity
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

3. 自定义RedisCacheManager

由于Spring Boot 2.x版本修改后,与1.x不同,new RedisCacheManager()该方法的参数列表修改,无需重新定义RedisTemplate,可以直接使用RedisCacheManager.builder直接创建RedisCacheManager.代码如下:

package com.zyx.sprintboot01cache.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;

/**
 * @ClassName: RedisManager
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2021/2/5 20:30
 */
@Configuration
public class RedisManager {

    @Bean
    public RedisCacheManager myCacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        config = config.serializeValuesWith(
                RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
        RedisCacheManager.RedisCacheManagerBuilder builder =
                RedisCacheManager.builder(redisConnectionFactory).cacheDefaults(config);
        return builder.build();
    }

}

4. 开启Spring Boot缓存注解

Spring Boot启动类上添加@EnableCaching注解

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cache.annotation.EnableCaching;

@SpringBootApplication
@EnableCaching
public class Sprintboot01CacheApplication {
    public static void main(String[] args) {
        SpringApplication.run(Sprintboot01CacheApplication.class, args);
    }
}

5.在Service层使用Redis缓存

/**
* @Cacheable
* 标注的方法 执行之前 先来检查缓存中有没有这个数据,默认按照参数的值作为key去查询缓存,
* 如果没有就运行方法并将结果放入缓存,以后再来调用就可以直接使用缓存中的数据
*/
@Cacheable(cacheNames = {"emp"}, key = "#id")
public Employee getEmp(Integer id) {
    System.out.println("查询" + id + "号员工");
    Employee employee = employeeMapper.selectById(id);
    return employee;
}

/**
* @CachePut 在方法 执行之后 将返回结果缓存
* 注: 修改后直接返回emp对象,如果不指定key为对象的id,会导致无法覆盖上面查询时的缓存数据
* 因为查询时是按照id缓存,这里不指定缓存key为id,将默认按照对象字符串序列化结果作为key存储
* emp::Employee(id=1, lastName=null, email=4@qq.com, gender=null, dId=null)
*/
@CachePut(value = "emp", key = "#result.id")
public Employee update(Employee emp) {
    System.out.println("更新" + emp);
    int i = employeeMapper.updateById(emp);
    return emp;
}

/**
* @CacheEvict 删除缓存
* 默认是在方法执行完成后运行,防止删除出现异常,事务回滚,防止删除了缓存
*  key:指定要清除的数据
*  allEntries = true:指定清除这个缓存中所有的数据
*  beforeInvocation = false:缓存的清除是否在方法之前执行
*      默认代表缓存清除操作是在方法执行之后执行;如果出现异常缓存就不会清除
*  beforeInvocation = true:
*      代表清除缓存操作是在方法运行之前执行,无论方法是否出现异常,缓存都清除
*/
@CacheEvict(value = "emp", key = "#id")
public void deleteEmp(Integer id) {
    System.out.println("delete emp: " + id);
}

// @Caching 定义复杂的缓存规则
@Caching(
     cacheable = {
         @Cacheable(/*value="emp",*/key = "#lastName")
     },
     put = {
         @CachePut(/*value="emp",*/key = "#result.id"),
         @CachePut(/*value="emp",*/key = "#result.email")
     }
)

6. 缓存数据结果

{
  "@class": "com.zyx.sprintboot01cache.entity.Employee",
  "id": 1,
  "lastName": null,
  "email": "4@qq.com",
  "gender": null,
  "did": null
}
posted @ 2021-01-22 20:44  Thoughtful_z  阅读(105)  评论(0)    收藏  举报