一、redis是什么?

Redis 是一个使用 C 语言写成的,开源、基于内存、可选持久性的、非关系型,key-value数据库java,Redis 支持的数据类型:String(字符串),list(列表),hash(字典),set(集合),zset(有序集合)。

二、springBoot整合redis缓存的步骤

1. 引入jar包

  1. <dependency>
  2. <groupId>org.springframework.boot</groupId>
  3. <artifactId>spring-boot-starter-data-redis</artifactId>
  4. </dependency>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  8. </dependency>

2. 完整pom内容

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  3. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  4. <modelVersion>4.0.0</modelVersion>
  5. <parent>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-parent</artifactId>
  8. <version>2.6.3</version>
  9. <relativePath/> <!-- lookup parent from repository -->
  10. </parent>
  11. <groupId>com.example</groupId>
  12. <artifactId>demo</artifactId>
  13. <version>0.0.1-SNAPSHOT</version>
  14. <name>springboot-redis</name>
  15. <description>Demo project for Spring Boot</description>
  16. <properties>
  17. <java.version>1.8</java.version>
  18. </properties>
  19. <dependencies>
  20. <dependency>
  21. <groupId>org.springframework.boot</groupId>
  22. <artifactId>spring-boot-starter-data-jdbc</artifactId>
  23. </dependency>
  24. <dependency>
  25. <groupId>org.springframework.boot</groupId>
  26. <artifactId>spring-boot-starter-data-redis</artifactId>
  27. </dependency>
  28. <dependency>
  29. <groupId>org.springframework.boot</groupId>
  30. <artifactId>spring-boot-starter-data-redis-reactive</artifactId>
  31. </dependency>
  32. <dependency>
  33. <groupId>org.springframework.boot</groupId>
  34. <artifactId>spring-boot-starter-jdbc</artifactId>
  35. </dependency>
  36. <dependency>
  37. <groupId>org.springframework.boot</groupId>
  38. <artifactId>spring-boot-starter-web</artifactId>
  39. </dependency>
  40. <dependency>
  41. <groupId>mysql</groupId>
  42. <artifactId>mysql-connector-java</artifactId>
  43. <scope>runtime</scope>
  44. </dependency>
  45. <dependency>
  46. <groupId>org.projectlombok</groupId>
  47. <artifactId>lombok</artifactId>
  48. <optional>true</optional>
  49. </dependency>
  50. <dependency>
  51. <groupId>org.springframework.boot</groupId>
  52. <artifactId>spring-boot-starter-test</artifactId>
  53. <scope>test</scope>
  54. </dependency>
  55. <dependency>
  56. <groupId>io.projectreactor</groupId>
  57. <artifactId>reactor-test</artifactId>
  58. <scope>test</scope>
  59. </dependency>
  60. <dependency>
  61. <groupId>org.mybatis.spring.boot</groupId>
  62. <artifactId>mybatis-spring-boot-starter</artifactId>
  63. <version>1.3.1</version>
  64. </dependency>
  65. </dependencies>
  66. <build>
  67. <plugins>
  68. <plugin>
  69. <groupId>org.springframework.boot</groupId>
  70. <artifactId>spring-boot-maven-plugin</artifactId>
  71. <configuration>
  72. <excludes>
  73. <exclude>
  74. <groupId>org.projectlombok</groupId>
  75. <artifactId>lombok</artifactId>
  76. </exclude>
  77. </excludes>
  78. </configuration>
  79. </plugin>
  80. </plugins>
  81. </build>
  82. </project>

3. application配置内容

  1. spring:
  2. datasource:
  3. # 数据源基本配置
  4. username: root
  5. password: 123456
  6. driver-class-name: com.mysql.cj.jdbc.Driver
  7. url: jdbc:mysql://数据库地址:3306/springBootAll?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false
  8. cache:
  9. type: redis
  10. redis:
  11. database: 8 #声明使用几号数据库
  12. host: 127.0.0.1 # Redis server host.
  13. password: jxkth123456 # Login password of the redis server.
  14. port: 6379 # Redis server port.
  15. ssl: false # Whether to enable SSL support.
  16. timeout: 5000 # Connection timeout
  17. expire: 3600 # 过期时间
  18. mybatis:
  19. mapper-locations: classpath:mapper/*.xml
  20. server:
  21. port: 8081

4.redis序列化配置

  1. @Configuration
  2. @EnableCaching
  3. public class RedisConfig extends CachingConfigurerSupport {
  4. //过期时间1天
  5. private Duration timeToLive = Duration.ofDays(1);
  6. @Bean
  7. public RedisCacheManager redisCacheManager(RedisConnectionFactory connectionFactory) {
  8. //默认1
  9. RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  10. .entryTtl(this.timeToLive)
  11. .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(keySerializer()))
  12. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(valueSerializer()))
  13. .disableCachingNullValues();
  14. RedisCacheManager redisCacheManager = RedisCacheManager.builder(connectionFactory)
  15. .cacheDefaults(config)
  16. .transactionAware()
  17. .build();
  18. return redisCacheManager;
  19. }
  20. @Bean(name = "redisTemplate")
  21. public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
  22. RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
  23. redisTemplate.setConnectionFactory(redisConnectionFactory);
  24. redisTemplate.setKeySerializer(keySerializer());
  25. redisTemplate.setHashKeySerializer(keySerializer());
  26. redisTemplate.setValueSerializer(valueSerializer());
  27. redisTemplate.setHashValueSerializer(valueSerializer());
  28. return redisTemplate;
  29. }
  30. private RedisSerializer<String> keySerializer() {
  31. return new StringRedisSerializer();
  32. }
  33. private RedisSerializer<Object> valueSerializer() {
  34. return new GenericJackson2JsonRedisSerializer();
  35. }
  36. }

5. service服务

  1. @Service
  2. public class UserService {
  3. @Resource
  4. UserDao userDao;
  5. /***
  6. * description: 使用注解声明使用缓存,用缓存的键值为userService:用户id,
  7. * 缓存内容为查询的用户对象
  8. * @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
  9. * @Cacheable 作用和配置方法
  10. */
  11. @Cacheable(value = "userService",key = "#userId")
  12. public User findUserById(Long userId){
  13. return userDao.findUserById(userId);
  14. }
  15. /**
  16. *@CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和
  17. * @Cacheable 不同的是,它每次都会触发真实方法的调用
  18. * @CachePut 作用和配置方法
  19. */
  20. @CacheEvict(value = "userService",key = "#user.id")
  21. public void updateUser(User user){
  22. userDao.updateUser(user);
  23. }
  24. /***
  25. * description:删除对象,并删除缓存
  26. * @CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
  27. * @CacheEvict 作用和配置方法
  28. */
  29. @CacheEvict(value = "userService",key = "#userId")
  30. public int deleteUserById(Long userId){
  31. return userDao.deleteUserById(userId);
  32. }
  33. }

controller,dao,和xml中的查询语句与常规查询语句和方法一致,此处不多赘述。
重点:使用@Cachecable主键声明使用缓存,因为已经配置好了使用redis作为缓存组件,所以可以在redis中查询到缓存对象。

6. 常用缓存注解说明

  1. @Cacheable
    @Cacheable 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存
    @Cacheable 作用和配置方法
    8.整合redis缓存组件 - 图1
  2. @CachePut
    @CachePut 的作用 主要针对方法配置,能够根据方法的请求参数对其结果进行缓存,和 @Cacheable 不同的是,它每次都会触发真实方法的调用
    @CachePut 作用和配置方法
    8.整合redis缓存组件 - 图2
  3. @CacheEvict
    @CachEvict 的作用 主要针对方法配置,能够根据一定的条件对缓存进行清空
    @CacheEvict 作用和配置方法
    8.整合redis缓存组件 - 图3

7. 缓存截图

8.整合redis缓存组件 - 图4

总结

项目源码