SpringBoot 整合 Lettuce Redis的實(shí)現(xiàn)方法
SpringBoot 是為了簡(jiǎn)化 Spring 應(yīng)用的創(chuàng)建、運(yùn)行、調(diào)試、部署等一系列問(wèn)題而誕生的產(chǎn)物,自動(dòng)裝配的特性讓我們可以更好的關(guān)注業(yè)務(wù)本身而不是外部的XML配置,我們只需遵循規(guī)范,引入相關(guān)的依賴就可以輕易的搭建出一個(gè) WEB 工程
Spring Boot 除了支持常見(jiàn)的ORM框架外,更是對(duì)常用的中間件提供了非常好封裝,隨著Spring Boot2.x的到來(lái),支持的組件越來(lái)越豐富,也越來(lái)越成熟,其中對(duì)Redis的支持不僅僅是豐富了它的API,更是替換掉底層Jedis的依賴,取而代之換成了Lettuce(生菜)
Redis介紹
Redis是一個(gè)開源的使用ANSI C語(yǔ)言編寫、支持網(wǎng)絡(luò)、可基于內(nèi)存亦可持久化的日志型、Key-Value數(shù)據(jù)庫(kù),并提供多種語(yǔ)言的API。相比Memcached它支持存儲(chǔ)的類型相對(duì)更多(字符、哈希、集合、有序集合、列表、GEO),同時(shí)Redis是線程安全的。2010年3月15日起,Redis的開發(fā)工作由VMware主持,2013年5月開始,Redis的開發(fā)由Pivotal贊助。
Lettuce
Lettuce 和 Jedis 的都是連接Redis Server的客戶端程序。Jedis在實(shí)現(xiàn)上是直連redis server,多線程環(huán)境下非線程安全,除非使用連接池,為每個(gè)Jedis實(shí)例增加物理連接。Lettuce基于Netty的連接實(shí)例(StatefulRedisConnection),可以在多個(gè)線程間并發(fā)訪問(wèn),且線程安全,滿足多線程環(huán)境下的并發(fā)訪問(wèn),同時(shí)它是可伸縮的設(shè)計(jì),一個(gè)連接實(shí)例不夠的情況也可以按需增加連接實(shí)例。
導(dǎo)入依賴
在 pom.xml 中spring-boot-starter-data-redis的依賴,Spring Boot2.x 后底層不在是Jedis如果做版本升級(jí)的朋友需要注意下
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>
屬性配置
在 application.properties 文件中配置如下內(nèi)容,由于Spring Boot2.x 的改動(dòng),連接池相關(guān)配置需要通過(guò)spring.redis.lettuce.pool或者 spring.redis.jedis.pool 進(jìn)行配置了
spring.redis.host=localhost spring.redis.password=battcn # 連接超時(shí)時(shí)間(毫秒) spring.redis.timeout=10000 # Redis默認(rèn)情況下有16個(gè)分片,這里配置具體使用的分片,默認(rèn)是0 spring.redis.database=0 # 連接池最大連接數(shù)(使用負(fù)值表示沒(méi)有限制) 默認(rèn) 8 spring.redis.lettuce.pool.max-active=8 # 連接池最大阻塞等待時(shí)間(使用負(fù)值表示沒(méi)有限制) 默認(rèn) -1 spring.redis.lettuce.pool.max-wait=-1 # 連接池中的最大空閑連接 默認(rèn) 8 spring.redis.lettuce.pool.max-idle=8 # 連接池中的最小空閑連接 默認(rèn) 0 spring.redis.lettuce.pool.min-idle=0
具體編碼
Spring Boot對(duì)Redis的支持已經(jīng)非常完善了,良好的序列化以及豐富的API足夠應(yīng)對(duì)日常開發(fā)
實(shí)體類
創(chuàng)建一個(gè)User類
package com.battcn.entity;
import java.io.Serializable;
/**
* @author Levin
* @since 2018/5/10 0007
*/
public class User implements Serializable {
private static final long serialVersionUID = 8655851615465363473L;
private Long id;
private String username;
private String password;
// TODO 省略get set
}
自定義Template
默認(rèn)情況下的模板只能支持RedisTemplate<String, String>,也就是只能存入字符串,這在開發(fā)中是不友好的,所以自定義模板是很有必要的,當(dāng)自定義了模板又想使用String存儲(chǔ)這時(shí)候就可以使用StringRedisTemplate的方式,它們并不沖突…
package com.battcn.config;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.io.Serializable;
/**
* TODO 修改database
*
* @author Levin
* @since 2018/5/10 0022
*/
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisCacheAutoConfiguration {
@Bean
public RedisTemplate<String, Serializable> redisCacheTemplate(LettuceConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Serializable> template = new RedisTemplate<>();
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(redisConnectionFactory);
return template;
}
}
測(cè)試
完成準(zhǔn)備事項(xiàng)后,編寫一個(gè)junit測(cè)試類來(lái)檢驗(yàn)代碼的正確性,有很多人質(zhì)疑過(guò)Redis線程安全性,故下面也提供了響應(yīng)的測(cè)試案例,如有疑問(wèn)歡迎指正
package com.battcn;
import com.battcn.entity.User;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import java.io.Serializable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;
/**
* @author Levin
* @since 2018/5/10 0010
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Chapter8ApplicationTest {
private static final Logger log = LoggerFactory.getLogger(Chapter8ApplicationTest.class);
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private RedisTemplate<String, Serializable> redisCacheTemplate;
@Test
public void get() {
// TODO 測(cè)試線程安全
ExecutorService executorService = Executors.newFixedThreadPool(1000);
IntStream.range(0, 1000).forEach(i ->
executorService.execute(() -> stringRedisTemplate.opsForValue().increment("kk", 1))
);
stringRedisTemplate.opsForValue().set("k1", "v1");
final String k1 = stringRedisTemplate.opsForValue().get("k1");
log.info("[字符緩存結(jié)果] - [{}]", k1);
// TODO 以下只演示整合,具體Redis命令可以參考官方文檔,Spring Data Redis 只是改了個(gè)名字而已,Redis支持的命令它都支持
String key = "battcn:user:1";
redisCacheTemplate.opsForValue().set(key, new User(1L, "u1", "pa"));
// TODO 對(duì)應(yīng) String(字符串)
final User user = (User) redisCacheTemplate.opsForValue().get(key);
log.info("[對(duì)象緩存結(jié)果] - [{}]", user);
}
}
其它類型
下列的就是Redis其它類型所對(duì)應(yīng)的操作方式
- opsForValue: 對(duì)應(yīng) String(字符串)
- opsForZSet: 對(duì)應(yīng) ZSet(有序集合)
- opsForHash: 對(duì)應(yīng) Hash(哈希)
- opsForList: 對(duì)應(yīng) List(列表)
- opsForSet: 對(duì)應(yīng) Set(集合)
- opsForGeo: 對(duì)應(yīng) GEO(地理位置)
總結(jié)
spring-data-redis文檔: https://docs.spring.io/spring-data/redis/docs/2.0.1.RELEASE/reference/html/#new-in-2.0.0
Redis 文檔: https://redis.io/documentation
Redis 中文文檔: http://www.redis.cn/commands.html
目前很多大佬都寫過(guò)關(guān)于 SpringBoot 的教程了,如有雷同,請(qǐng)多多包涵,本教程基于最新的 spring-boot-starter-parent:2.0.1.RELEASE編寫,包括新版本的特性都會(huì)一起介紹
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- SpringBoot整合redis+lettuce的方法詳解
- 關(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)題)
- Springboot2.X集成redis集群(Lettuce)連接的方法
- SpringBoot集成Lettuce客戶端操作Redis的實(shí)現(xiàn)
相關(guān)文章
springcloud微服務(wù)基于redis集群的單點(diǎn)登錄實(shí)現(xiàn)解析
這篇文章主要介紹了springcloud微服務(wù)基于redis集群的單點(diǎn)登錄實(shí)現(xiàn)解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09
RxJava中map和flatMap的用法區(qū)別源碼解析
這篇文章主要為大家介紹了RxJava中map和flatMap的用法區(qū)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09
Spring Boot自定義favicon實(shí)現(xiàn)方法實(shí)例解析
這篇文章主要介紹了Spring Boot自定義favicon實(shí)現(xiàn)方法實(shí)例解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
spring boot + mybatis如何實(shí)現(xiàn)數(shù)據(jù)庫(kù)的讀寫分離
這篇文章主要給大家介紹了關(guān)于spring boot + mybatis如何實(shí)現(xiàn)數(shù)據(jù)庫(kù)的讀寫分離的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-09-09
spring boot 下對(duì)JSON返回值去除null和空字段操作
這篇文章主要介紹了spring boot 下對(duì)JSON返回值去除null和空字段操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-10-10
Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán)示例源碼
這篇文章主要介紹了Spring gateway配置Spring Security實(shí)現(xiàn)統(tǒng)一權(quán)限驗(yàn)證與授權(quán),本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2023-07-07

