SpringBoot整合redis+lettuce的方法詳解
前言
Spring Boot提供了與Redis的集成框架,可以使用Lettuce作為Redis客戶端來(lái)進(jìn)行整合。
版本依賴
jdk 17
SpringBoot 3.1.0
環(huán)境準(zhǔn)備
依賴
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.0</version>
</parent>
<groupId>com.example</groupId>
<artifactId>RedisLettuceDemo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>RedisLettuceDemo</name>
<description>RedisLettuceDemo</description>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.32</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
</dependencies>配置
server:
port: 8080 # 設(shè)置訪問(wèn)端口
spring:
redis:
host: localhost
port: 6379
password: 123456
database: 0
ssl: false
pool:
maxIdle: 100
minIdle: 0
maxTotal: 100
maxWaitMillis: 500
testOnBorrow: false
testOnReturn: true
testWhileIdle: true實(shí)例
LettuceClientConfig
//Redis服務(wù)器地址
@Value("${spring.redis.host}")
private String host;
//Redis服務(wù)端口
@Value("${spring.redis.port}")
private Integer port;
//Redis密碼
@Value("${spring.redis.password}")
private String password;
//是否需要SSL
@Value("${spring.redis.ssl}")
private Boolean ssl;
//Redis默認(rèn)庫(kù),一共0~15
@Value("${spring.redis.database}")
private Integer database;
//Lettuce連接配置(Redis單機(jī)版實(shí)例)
@Bean(name = "redisClient")
public RedisClient redisClient() {
RedisURI uri = RedisURI.Builder.redis(this.host, this.port)
.withDatabase(this.database)
.build();
return RedisClient.create(uri);
}LettucePoolConfig
@Resource
RedisClient redisClient;
//設(shè)置可分配的最大Redis實(shí)例數(shù)量
@Value("${spring.redis.pool.maxTotal}")
private Integer maxTotal;
//設(shè)置最多空閑的Redis實(shí)例數(shù)量
@Value("${spring.redis.pool.maxIdle}")
private Integer maxIdle;
//歸還Redis實(shí)例時(shí),檢查有消息,如果失敗,則銷(xiāo)毀實(shí)例
@Value("${spring.redis.pool.testOnReturn}")
private Boolean testOnReturn;
//當(dāng)Redis實(shí)例處于空閑壯體啊時(shí)檢查有效性,默認(rèn)flase
@Value("${spring.redis.pool.testWhileIdle}")
private Boolean testWhileIdle;
//Apache-Common-Pool是一個(gè)對(duì)象池,用于緩存Redis連接,
//因?yàn)長(zhǎng)etture本身基于Netty的異步驅(qū)動(dòng),但基于Servlet模型的同步訪問(wèn)時(shí),連接池是必要的
//連接池可以很好的復(fù)用連接,減少重復(fù)的IO消耗與RedisURI創(chuàng)建實(shí)例的性能消耗
@Getter
GenericObjectPool<StatefulRedisConnection<String, String>> redisConnectionPool;
//Servlet初始化時(shí)先初始化Lettuce連接池
@PostConstruct
private void init() {
GenericObjectPoolConfig<StatefulRedisConnection<String, String>> redisPoolConfig
= new GenericObjectPoolConfig<>();
redisPoolConfig.setMaxIdle(this.maxIdle);
redisPoolConfig.setMinIdle(0);
redisPoolConfig.setMaxTotal(this.maxTotal);
redisPoolConfig.setTestOnReturn(this.testOnReturn);
redisPoolConfig.setTestWhileIdle(this.testWhileIdle);
redisPoolConfig.setMaxWaitMillis(1000);
this.redisConnectionPool =
ConnectionPoolSupport.createGenericObjectPool(() -> redisClient.connect(), redisPoolConfig);
}
//Servlet銷(xiāo)毀時(shí)先銷(xiāo)毀Lettuce連接池
@PreDestroy
private void destroy() {
redisConnectionPool.close();
redisClient.shutdown();
}LettuceUtil
@Autowired
LettucePoolConfig lettucePoolConfig;
//編寫(xiě)executeSync方法,在方法中,獲取Redis連接,利用Callback操作Redis,最后釋放連接,并返回結(jié)果
//這里使用的同步的方式執(zhí)行cmd指令
public <T> T executeSync(SyncCommandCallback<T> callback) {
//這里利用try的語(yǔ)法糖,執(zhí)行完,自動(dòng)給釋放連接
try (StatefulRedisConnection<String, String> connection = lettucePoolConfig.getRedisConnectionPool().borrowObject()) {
//開(kāi)啟自動(dòng)提交,如果false,命令會(huì)被緩沖,調(diào)用flushCommand()方法發(fā)出
connection.setAutoFlushCommands(true);
//設(shè)置為同步模式
RedisCommands<String, String> commands = connection.sync();
//執(zhí)行傳入的實(shí)現(xiàn)類(lèi)
return callback.doInConnection(commands);
} catch (Exception e) {
log.error(e.getMessage());
throw new RuntimeException(e);
}
}
//分裝一個(gè)set方法
public String set(final String key, final String val) {
return executeSync(commands -> commands.set(key, val));
}
//分裝一個(gè)get方法
public String get(final String key) {
return executeSync(commands -> commands.get(key));
}SyncCommandCallback
//抽象方法,為了簡(jiǎn)化代碼,便于傳入回調(diào)函數(shù)
T doInConnection(RedisCommands<String, String> commands);LettuceController
@Autowired
LettuceUtil lettuceUtil;
/**
* 使用Lettuce工具類(lèi),調(diào)用Redis的Set指令
* http://127.0.0.1:8080/lettuce/set?key=name&val=ipipman
*
* @param key
* @param val
* @return
*/
@GetMapping("/set")
public Object setItem(@RequestParam(name = "key", required = true) String key,
@RequestParam(name = "val", required = true) String val) {
return lettuceUtil.set(key, val);
}
/**
* 使用Lettuce工具類(lèi),調(diào)用Redis的Get指令
* http://127.0.0.1:8080/lettuce/get?key=name
*
* @param key
* @return
*/
@GetMapping("/get")
public Object getItem(@RequestParam(name = "key", required = true) String key) {
return lettuceUtil.get(key);
}到此這篇關(guān)于SpringBoot整合redis+lettuce的方法詳解的文章就介紹到這了,更多相關(guān)SpringBoot整合redis+lettuce內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 關(guān)于SpringBoot集成Lettuce連接Redis的方法和案例
- SpringBoot2.4.2下使用Redis配置Lettuce的示例
- springboot集成redis lettuce
- 關(guān)于SpringBoot整合redis使用Lettuce客戶端超時(shí)問(wèn)題
- 關(guān)于Springboot2.x集成lettuce連接redis集群報(bào)超時(shí)異常Command timed out after 6 second(s)
- springboot2整合redis使用lettuce連接池的方法(解決lettuce連接池?zé)o效問(wèn)題)
- SpringBoot 整合 Lettuce Redis的實(shí)現(xiàn)方法
- Springboot2.X集成redis集群(Lettuce)連接的方法
- SpringBoot集成Lettuce客戶端操作Redis的實(shí)現(xiàn)
相關(guān)文章
swagger配置正式環(huán)境中不可訪問(wèn)的問(wèn)題
這篇文章主要介紹了swagger配置正式環(huán)境中不可訪問(wèn)的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-06-06
spring cloud 之 客戶端負(fù)載均衡Ribbon深入理解
下面小編就為大家?guī)?lái)一篇spring cloud 之 客戶端負(fù)載均衡Ribbon深入理解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-06-06
struts2標(biāo)簽總結(jié)_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
這篇文章主要為大家詳細(xì)總結(jié)了struts2標(biāo)簽的使用方法,和學(xué)習(xí)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-09-09

