SpringDataRedis調用Redis底層解讀
- 在SpringBoot2.X之前還是直接使用的官方推薦的Jedis連接的Redis
- 在2.X之后換為了lettuce

- Jedis:采用直接連接,多線程操作不安全,如果想要避免不安全,使用Jedis pool連接池;BIO
- lettuce:底層采用Netty,實例可以在多個線程之間共享,不存在線程不安全的情況,可以減少線程數量;NIO
SpringBoot整合Redis(源碼分析)
- SpringBoot所有的配置類,都有一個自動配置類
- 自動配置類都會綁定一個properties文件
- 在源碼中找到Spring.factories

- 在里面搜索redis,找到AutoConfiguration

- 按ctrl+點擊進入類

- 找到redisproperties.class

- ctrl+點擊進入

- 里面就是全部的redis相關配置了,先簡單看一下,其他的后面再說

- 默認注入的Bean

- 但是默認的redisTemplate是存在一些問題的,他的key是Object類型的,但是我們期望的一般key都是String類型的這就需要強制類型轉換了,所以上面提出了,可以自己定義RedisTemplate
- 在配置配置文件時,如果需要配置連接池,就采用lettuce的,不要直接配置Redis的,配置了也不生效
- 查看注入時的RedisConnectionFactory

- 他是存在兩個子類的,分別是JedisConnectionFactory和LettuceConnectionFactory

- 為什么說直接JedisConnectionFactory不生效呢?是因為類中的很多依賴類都是不存在的

- 全都是爆紅線的,而lettuceConnectionFactory中的依賴就是全部存在的

- 所以配置時,采用lettuce的

- 不要直接配置jedis的

SpringBoot整合Redis(配置)
yml
- 拷貝properties創建一個yml格式的配置文件, 我還是很喜歡yml的

spring:
redis:
host: localhost
port: 6379
Maven
在項目創建的時候選擇,如果沒有選擇就添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
編寫測試
- 打開SpringBoot默認創建的測試類

- redisTemp操作數據類型的方法都是以opsFor開頭,后面是類型

- 比如opsForValue就是操作字符串的
- 然后后面的應用就和前面寫的API一樣了

- 常用的操作可以直接點就可以了
- 關於事物的
redisTemplate.unwatch(); redisTemplate.watch("key"); redisTemplate.multi(); redisTemplate.discard(); redisTemplate.exec();
關於數據庫的操作需要獲取鏈接后使用連接對象操作
RedisConnection connection = redisTemplate.getConnectionFactory().getConnection(); connection.flushAll(); connection.flushDb(); connection.close();
測試代碼及其執行結果
package co.flower.redis02springboot; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.RedisTemplate; @SpringBootTest class Redis02SpringbootApplicationTests { /** * 我居然直接就指定了泛型 RedisTemplate<String,Object>結果就直接報錯了,刪除泛型后成功 */ @Autowired private RedisTemplate redisTemplate; @Test void contextLoads() { // 英文測試 redisTemplate.opsForValue().set("name","xiaojiejie"); System.out.println(redisTemplate.opsForValue().get("name")); // 中文測試 redisTemplate.opsForValue().set("name","小姐姐"); System.out.println(redisTemplate.opsForValue().get("name")); } } 執行結果,SpringBoot的啟動加載和結束銷毀沒有粘貼 /***SpringBootStart****/ xiaojiejie 小姐姐 /***SpringBootStop*****/
作者:彼岸舞
時間:2021\05\05
內容關於:Redis
本文屬於作者原創,未經允許,禁止轉發
