SpringBoot整合Redis做缓存,实战分享

存储 存储软件 Redis
我们都知道,把首页数据放到Redis里,能够加快首页数据的访问速度。但是我们要如何准确又快速的将 Redis 整合到自己的 SpringBoot2.x 项目中呢?今天阿粉就带大家爬一爬其中的门门道道。

 我们都知道,把首页数据放到Redis里,能够加快首页数据的访问速度。但是我们要如何准确又快速的将 Redis 整合到自己的 SpringBoot2.x 项目中呢?今天阿粉就带大家爬一爬其中的门门道道。

[[331486]]

Redis 介绍

Redis 使用了浪费流量的文本协议,但因为它数据存储在内存中的,相对而言,依然可以取得极高的访问性能。并且 Redis 是线程安全的。

RESP 就是 Redis 序列化协议的简称。它是一种直观的文本协议,优势在于实现异常简单,解析性能极好。

Redis 协议里面虽然有大量冗余的回车换行符,但是这不影响它成为技术领域非常受欢迎的一个文本协议。在技术领域,性能并不总是一切,还有简单性、易理解性和易实现性,这些都需要进行适当权衡。

Redis 基础数据结构

1、字符串:(缓存)

  • key:value

value 可以是对象转换成的 JSON 字符串,也可以是对象序列化后的二进制字符串

2、列表:(异步队列) 类似linkedlist

  • 右边进左边出:队列
  • 右边进右边出:栈

3、字典(哈希) 类似hashmap:数组+链表

不过rehash是渐进式hash策略

4、集合:(去重)

  • 无序 set:类似hashset
  • 有序 zset:类似SortedSet和HashMap的结合体,内部实现是跳跃列表

Lettuce

随着 Spring Boot2.x 的到来,支持的组件越来越丰富,也越来越成熟,其中对 Redis 的支持不仅仅是丰富了它的API,更是替换掉底层 Jedis 的依赖,取而代之换成了 Lettuce。

虽然 Lettuce 和 Jedis 的都是连接 Redis Server 的客户端程序,但是 Jedis 在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个Jedis实例增加物理连接。而 Lettuce 基于 Netty 的连接实例(StatefulRedisConnection),可以在多个线程间并发访问,且线程安全,满足多线程环境下的并发访问,同时它是可伸缩的设计,一个连接实例不够的情况也可以按需增加连接实例。

Lettuce是可扩展的Redis客户端,用于构建无阻塞的Reactive应用程序.

Luttuce官网:https://lettuce.io/

谷歌翻译后的页面是:

原来这玩意儿叫生菜,你别说,看着图标还真有点像。

实操

项目中使用的 SpringBoot2.x 实现,如果之前是 SpringBoot1.x 则需要注意,底层已经由 Jedis 升级成了 Lettuce 。

3.1、引入依赖

除去 SpringBoot 项目需要的 jar 包外,另外还需要引入 redis 相关的依赖:

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

3.2、application.yml 配置文件

此处用到的 application.yml 文件,配置如下:

  1. spring: 
  2.   redis: 
  3.     # Redis默认情况下有16个分片,这里配置具体使用的分片。默认是索引为0的分片 
  4.     database: 1 
  5.     # Redis服务器地址 
  6.     host: 127.0.0.1 
  7.     # Redis服务器连接端口 
  8.     port: 6379 
  9.     # Redis服务器连接密码(默认为空) 
  10.     password: mmzsblog 
  11.     # 连接超时时间(毫秒) 
  12.     timeout: 2000s 
  13.  
  14.     # 配置文件中添加 lettuce.pool 相关配置,则会使用到lettuce连接池 
  15.     lettuce: 
  16.       pool: 
  17.         # 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1 
  18.         max-wait: 60s 
  19.         # 连接池中的最大空闲连接 默认 8 
  20.         max-idle: 10 
  21.         # 连接池中的最小空闲连接 默认 0 
  22.         min-idle: 10 
  23.         # 连接池最大连接数(使用负值表示没有限制) 默认 8 
  24.         max-activ: 8 

如果项目是由 SpringBoot1.x 升级到 SpringBoot2.x 的,要沿用 jedis 连接池配置时会用到配置 jedis 相关的属性:

  1. # 配置文件中添加 jedis.pool 相关配置,则会使用到 jedis 连接池 
  2.    jedis: 
  3.      pool: 
  4.        max-active: 10 
  5.        max-idle: 8 
  6.        min-idle: 0 
  7.        max-wait: 60s 

并且引用的 jar 包也需要调整:

  1. <dependency> 
  2.     <groupId>org.springframework.boot</groupId> 
  3.     <artifactId>spring-boot-starter-data-redis</artifactId> 
  4.     <exclusions> 
  5.         <exclusion> 
  6.             <groupId>io.lettuce</groupId> 
  7.             <artifactId>lettuce-core</artifactId> 
  8.         </exclusion> 
  9.     </exclusions> 
  10. </dependency> 
  11. <dependency> 
  12.     <groupId>redis.clients</groupId> 
  13.     <artifactId>jedis</artifactId> 
  14. </dependency> 

另外,这里再贴一下 Spring Boot 关于 RedisProperties 的所有配置项

  1. # REDIS RedisProperties 
  2. spring.redis.cluster.max-redirects= # Maximum number of redirects to follow when executing commands across the cluster. 
  3. spring.redis.cluster.nodes= # Comma-separated list of "host:port" pairs to bootstrap from
  4. spring.redis.database=0 # Database index used by the connection factory. 
  5. spring.redis.url= # Connection URL. Overrides host, port, and passwordUser is ignored. Example: redis://user:password@example.com:6379 
  6. spring.redis.host=localhost # Redis server host. 
  7. spring.redis.jedis.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. 
  8. spring.redis.jedis.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. 
  9. spring.redis.jedis.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. 
  10. spring.redis.jedis.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. 
  11. spring.redis.lettuce.pool.max-active=8 # Maximum number of connections that can be allocated by the pool at a given time. Use a negative value for no limit. 
  12. spring.redis.lettuce.pool.max-idle=8 # Maximum number of "idle" connections in the pool. Use a negative value to indicate an unlimited number of idle connections. 
  13. spring.redis.lettuce.pool.max-wait=-1ms # Maximum amount of time a connection allocation should block before throwing an exception when the pool is exhausted. Use a negative value to block indefinitely. 
  14. spring.redis.lettuce.pool.min-idle=0 # Target for the minimum number of idle connections to maintain in the pool. This setting only has an effect if it is positive. 
  15. spring.redis.lettuce.shutdown-timeout=100ms # Shutdown timeout. 
  16. spring.redis.password= # Login password of the redis server. 
  17. spring.redis.port=6379 # Redis server port. 
  18. spring.redis.sentinel.master= # Name of the Redis server. 
  19. spring.redis.sentinel.nodes= # Comma-separated list of "host:port" pairs. 
  20. spring.redis.ssl=false # Whether to enable SSL support. 
  21. spring.redis.timeout= # Connection timeout. 

3.3、自定义一个 RedisTemplate

这个看你自己,不自定义也不影响使用,只是说可能不那么顺手,所以阿粉习惯自定义一个。因为 Spring Boot 在 RedisAutoConfiguration 中默认配置了 RedisTemplate、StringRedisTemplate两个模板类,然而RedisTemplate并未指定key、value的序列化器。

  1. @Configuration 
  2. public class RestTemplateConfig { 
  3.     @Bean 
  4.     public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) { 
  5.         RedisTemplate<String, Serializable> template = new RedisTemplate<>(); 
  6.         template.setKeySerializer(new StringRedisSerializer()); 
  7.         template.setValueSerializer(new GenericJackson2JsonRedisSerializer()); 
  8.         template.setConnectionFactory(redisConnectionFactory); 
  9.         return template; 
  10.     } 

3.4、Person 实体类

声明一个 Person 实体类:

  1. /** 
  2.  * @author :created by mmzsblog 
  3.  * @date :created at 2020/06/23 16:41 
  4.  */ 
  5. @Data 
  6. @NoArgsConstructor 
  7. @AllArgsConstructor 
  8. public class Person implements Serializable { 
  9.  
  10.     private static final long serialVersionUID = -8183942491930372236L; 
  11.     private Long userId; 
  12.     private String username; 
  13.     private String password

3.5、测试

通过编写一个 UserController 来进行测试:

  1. @RestController 
  2. public class UserController { 
  3.     @Resource 
  4.     private RedisTemplate redisTemplate; 
  5.  
  6.     @Resource 
  7.     private StringRedisTemplate stringRedisTemplate; 
  8.  
  9.     @GetMapping("/set"
  10.     public String set() { 
  11.         stringRedisTemplate.opsForValue().set("one""1"); 
  12.          
  13.         // redisTemplate 保存的是字节序列,因为 RestTemplateConfig 自定义的时候指定了 key 和 value 的序列化器。 
  14.         redisTemplate.opsForValue().set("two""2"); 
  15.         redisTemplate.opsForValue().set("person", new Person(1L, "luffy""123456789")); 
  16.  
  17.         // 测试线程安全 
  18.         ExecutorService executorService = Executors.newFixedThreadPool(1000); 
  19.         IntStream.range(0, 1000).forEach(i -> { 
  20.             executorService.execute(() -> stringRedisTemplate.opsForValue().increment("num", 1)); 
  21.         }); 
  22.         return "Ok!"
  23.     } 
  24.  
  25.     @GetMapping("/get"
  26.     public String get() { 
  27.         String one = stringRedisTemplate.opsForValue().get("one"); 
  28.         if ("1".equals(one)) { 
  29.             System.out.println("key: one" + " || value: " + one); 
  30.         } 
  31.  
  32.         Object two = redisTemplate.opsForValue().get("two"); 
  33.         if ("2".equals(two.toString())) { 
  34.             System.out.println("key: two" + " || value: " + two); 
  35.         } 
  36.  
  37.         Person user = (Person) redisTemplate.opsForValue().get("person"); 
  38.         if ("luffy".equals(user.getUsername())) { 
  39.             System.out.println("key: person" + " || value: " + user); 
  40.         } 
  41.         return "Ok!"
  42.     } 

用RedisDesktopManager工具查看,数据如下:

用 StringRedisTemplate 设置的键值是String类型的:

用 RedisTemplate 设置的键值是二进制的字节流形式存储的,从截图中的 [Binary] 标识符也能看出:

自定义的 RedisTemplate 和 StringRedisTemplate 并不会有什么冲突,想用 String 存储还是二进制的字节流形式存储完全取决于你自己。

参考

https://lettuce.io/

Spring Boot官方文档 91.4

《Redis深度历险:核心原理和应用实践》

http://blog.battcn.com/2018/05/11/springboot/v2-nosql-redis/

https://www.jianshu.com/p/f7d11e7109b7

 

责任编辑:武晓燕 来源: Java极客技术
相关推荐

2023-10-12 08:00:48

2023-01-13 07:39:07

2020-01-10 15:42:13

SpringBootRedis数据库

2015-12-28 10:48:44

RedisSpring缓存实例

2017-04-17 10:35:40

Spring BooRedis 操作

2018-09-12 19:46:53

数据库MySQLRedis

2023-02-14 07:47:20

SpringBootEhcache

2018-02-09 11:05:42

Java代码框架

2022-08-22 09:03:09

SpringbootRedis数据

2023-08-09 08:01:00

WebSockett服务器web

2020-08-19 08:55:47

Redis缓存数据库

2023-05-31 08:56:24

2019-10-12 14:19:05

Redis数据库缓存

2023-03-10 13:33:00

缓存穿透缓存击穿缓存雪崩

2021-04-07 08:43:09

SpringBootRocketMQ开发技术

2019-09-10 10:48:10

RedisJava面试题

2019-03-22 15:15:25

Redis缓存击穿雪崩效应

2022-03-09 18:54:30

HTTP缓存协议cache

2023-03-20 09:17:13

策略模式Springboot

2023-02-22 09:16:22

点赞
收藏

51CTO技术栈公众号