成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

SpringBoot整合Redis做緩存,實戰(zhàn)分享

存儲 存儲軟件 Redis
我們都知道,把首頁數據放到Redis里,能夠加快首頁數據的訪問速度。但是我們要如何準確又快速的將 Redis 整合到自己的 SpringBoot2.x 項目中呢?今天阿粉就帶大家爬一爬其中的門門道道。

 我們都知道,把首頁數據放到Redis里,能夠加快首頁數據的訪問速度。但是我們要如何準確又快速的將 Redis 整合到自己的 SpringBoot2.x 項目中呢?今天阿粉就帶大家爬一爬其中的門門道道。

[[331486]]

Redis 介紹

Redis 使用了浪費流量的文本協(xié)議,但因為它數據存儲在內存中的,相對而言,依然可以取得極高的訪問性能。并且 Redis 是線程安全的。

RESP 就是 Redis 序列化協(xié)議的簡稱。它是一種直觀的文本協(xié)議,優(yōu)勢在于實現異常簡單,解析性能極好。

Redis 協(xié)議里面雖然有大量冗余的回車換行符,但是這不影響它成為技術領域非常受歡迎的一個文本協(xié)議。在技術領域,性能并不總是一切,還有簡單性、易理解性和易實現性,這些都需要進行適當權衡。

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,多線程環(huán)境下非線程安全,除非使用連接池,為每個Jedis實例增加物理連接。而 Lettuce 基于 Netty 的連接實例(StatefulRedisConnection),可以在多個線程間并發(fā)訪問,且線程安全,滿足多線程環(huán)境下的并發(fā)訪問,同時它是可伸縮的設計,一個連接實例不夠的情況也可以按需增加連接實例。

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 保存的是字節(jié)序列,因為 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 設置的鍵值是二進制的字節(jié)流形式存儲的,從截圖中的 [Binary] 標識符也能看出:

自定義的 RedisTemplate 和 StringRedisTemplate 并不會有什么沖突,想用 String 存儲還是二進制的字節(jié)流形式存儲完全取決于你自己。

參考

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-01-13 07:39:07

2023-10-12 08:00:48

2020-01-10 15:42:13

SpringBootRedis數據庫

2024-12-24 08:44:55

ActiveMQRabbitMQ交換機

2015-12-28 10:48:44

RedisSpring緩存實例

2017-04-17 10:35:40

Spring BooRedis 操作

2018-09-12 19:46:53

數據庫MySQLRedis

2025-03-26 03:25:00

SpringGuavaCaffeine

2024-11-04 08:02:23

SpringRabbitMQ中間件

2023-02-14 07:47:20

SpringBootEhcache

2025-04-21 03:00:00

2018-02-09 11:05:42

Java代碼框架

2023-08-09 08:01:00

WebSockett服務器web

2020-08-19 08:55:47

Redis緩存數據庫

2022-03-09 18:54:30

HTTP緩存協(xié)議cache

2024-10-09 10:46:41

springboot緩存redis

2023-03-10 13:33:00

緩存穿透緩存擊穿緩存雪崩

2019-10-12 14:19:05

Redis數據庫緩存

2022-08-22 09:03:09

SpringbootRedis數據

2019-03-22 15:15:25

Redis緩存擊穿雪崩效應
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 久久久久国产一区二区三区四区 | 丁香久久 | 日本a网站 | 99这里只有精品视频 | 中文字幕 亚洲一区 | 中文字幕加勒比 | 成人av在线大片 | 欧美激情亚洲 | 99视频网站 | 羞羞视频在线观看免费观看 | 天天碰夜夜操 | 亚洲综合色视频在线观看 | 久久久久久免费精品一区二区三区 | av中文网 | 亚洲人成人一区二区在线观看 | 亚洲人成人一区二区在线观看 | 国产激情一区二区三区 | 欧美激情精品久久久久久 | 欧美不卡一区二区 | 天堂视频一区 | 国产精品亚洲二区 | 国产欧美一区二区三区在线看 | 美女激情av | 国产在线精品一区二区三区 | 国产日韩免费观看 | 国产日韩欧美一区二区在线播放 | 日韩中文字幕视频 | 国产中文字幕亚洲 | 国产精品日韩欧美 | 人人做人人澡人人爽欧美 | 欧美在线色视频 | 国产精品免费一区二区三区四区 | 久久亚洲一区二区 | 91精品国产91综合久久蜜臀 | 亚洲精品一区二区在线观看 | 99riav3国产精品视频 | 国产一级在线观看 | 亚洲欧美一区二区在线观看 | 99久久免费精品国产免费高清 | 精品日韩在线 | 久久久久久久久久性 |