詳解Spring集成Redis的兩種方式
在工作中,我們用到分布式緩存的時(shí)候,第一選擇就是Redis,今天介紹一下SpringBoot如何集成Redis的,分別使用Jedis和Spring-data-redis兩種方式。
一、使用Jedis方式集成
1、增加依賴
<!-- spring-boot-starter-web不是必須的,這里是為了測(cè)試--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency> <dependency> <!-- fastjson不是必須的,這里是為了測(cè)試--> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.73</version> </dependency>
2、配置項(xiàng)
redis.host=localhost redis.maxTotal=5 redis.maxIdle=5 redis.testOnBorrow=true #以下方式也可以,SpringBoot同樣能將其解析注入到JedisPoolConfig中 #redis.max-total=3 #redis.max-idle=3 #redis.test-on-borrow=true
3、配置連接池
/**
* @author 公-眾-號(hào):程序員阿牛
* 由于Jedis實(shí)例本身不非線程安全的,因此我們用JedisPool
*/
@Configuration
public class CommonConfig {
@Bean
@ConfigurationProperties("redis")
public JedisPoolConfig jedisPoolConfig() {
return new JedisPoolConfig();
}
@Bean(destroyMethod = "close")
public JedisPool jedisPool(@Value("${redis.host}") String host) {
return new JedisPool(jedisPoolConfig(), host);
}
}
4、測(cè)試
/**
* @author 公-眾-號(hào):程序員阿牛
*/
@RestController
public class JedisController {
@Autowired
private JedisPool jedisPool;
@RequestMapping("getUser")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("張三豐");
userInfo.setAddress("武當(dāng)山");
jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo));
UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class);
return userInfo1.toString();
}
}
運(yùn)行結(jié)果如下:

我們可以自己包裝一個(gè)RedisClient,來簡(jiǎn)化我們的操作
使用spring-data-redis
1、引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、配置項(xiàng)
在application.properties中增加配置
spring.redis.host=localhost spring.redis.port=6379
3、使用
/**
* @author 公-眾-號(hào):程序員阿牛
*/
@RestController
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("getUser2")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("張三豐");
userInfo.setAddress("武當(dāng)山");
redisTemplate.opsForValue().set("userInfo", userInfo);
UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo");
return userInfo1.toString();
}
}
是的,你只需要引入依賴、加入配置就可以使用Redis了,不要高興的太早,這里面會(huì)有一些坑
4、可能會(huì)遇到的坑

使用工具查看我們剛才set的內(nèi)容,發(fā)現(xiàn)key前面多了一串字符,value也是不可見的
原因
使用springdataredis,默認(rèn)情況下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer這個(gè)類來做序列化
具體我們看一下RedisTemplate 代碼如何實(shí)現(xiàn)的
/**
*在初始化的時(shí)候,默認(rèn)的序列化類是JdkSerializationRedisSerializer
*/
public void afterPropertiesSet() {
super.afterPropertiesSet();
boolean defaultUsed = false;
if (this.defaultSerializer == null) {
this.defaultSerializer = new JdkSerializationRedisSerializer(this.classLoader != null ? this.classLoader : this.getClass().getClassLoader());
}
...省略無關(guān)代碼
}
如何解決
很簡(jiǎn)單,自己定義RedisTemplate并指定序列化類即可
/**
* @author 公-眾-號(hào):程序員阿牛
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setValueSerializer(jackson2JsonRedisSerializer());
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
}/**
* @author 公-眾-號(hào):程序員阿牛
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
template.setValueSerializer(jackson2JsonRedisSerializer());
//使用StringRedisSerializer來序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(jackson2JsonRedisSerializer());
template.afterPropertiesSet();
return template;
}
@Bean
public RedisSerializer<Object> jackson2JsonRedisSerializer() {
//使用Jackson2JsonRedisSerializer來序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
return serializer;
}
}
查看運(yùn)行結(jié)果:

哨兵和集群
只需要改一下配置項(xiàng)即可
# 哨兵 spring.redis.sentinel.master=mymaster spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381 #集群 spring.redis.cluster.max-redirects=100 spring.redis.cluster.nodes=127.0.0.1:6379,127.0.0.1:6380,127.0.0.1:6381,127.0.0.1:6382,127.0.0.1:6383,127.0.0.1:6384
總結(jié):
以上兩種方式都可以,但是還是建議你使用Spring-data-redis,因?yàn)镾pring經(jīng)過多年的發(fā)展,尤其是Springboot的日漸成熟,已經(jīng)為我們簡(jiǎn)化了很多操作。
到此這篇關(guān)于詳解Spring集成Redis的兩種方式的文章就介紹到這了,更多相關(guān)Spring集成Redis 內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
springboot項(xiàng)目中controller層與前端的參數(shù)傳遞方式
這篇文章主要介紹了springboot項(xiàng)目中controller層與前端的參數(shù)傳遞方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10
深入學(xué)習(xí)java8?中的CompletableFuture
本文主要介紹了java8中的CompletableFuture,CompletableFuture實(shí)現(xiàn)了CompletionStage接口和Future接口,前者是對(duì)后者的一個(gè)擴(kuò)展,增加了異步回調(diào)、流式處理、多個(gè)Future組合處理的能力,使Java在處理多任務(wù)的協(xié)同工作時(shí)更加順暢便利,下文需要的朋友可以參考一下2022-05-05
源碼分析Spring?中?@Qualifier?注解基本用法
這篇文章主要介紹了源碼分析Spring?中?@Qualifier?注解基本用法,在源碼分析的過程中,也?GET?到?Spring?許多新的玩法,感興趣的小伙伴趕緊去試試吧2023-08-08
詳解Spring Security如何在權(quán)限中使用通配符
小伙伴們知道,在Shiro中,默認(rèn)是支持權(quán)限通配符的?,F(xiàn)在給用戶授權(quán)的時(shí)候,可以一個(gè)權(quán)限一個(gè)權(quán)限的配置,也可以直接用通配符。本文將介紹Spring Security如何在權(quán)限中使用通配符,需要的可以參考一下2022-06-06
spring boot下 500 404 錯(cuò)誤頁面處理的方法
本篇文章主要介紹了spring boot下 500 404 錯(cuò)誤頁面處理的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-04-04
java實(shí)現(xiàn)寫入并保存txt文件的代碼詳解
在本篇文章里小編給大家整理了關(guān)于java實(shí)現(xiàn)寫入并保存txt文件的代碼實(shí)例內(nèi)容,需要的朋友們可以參考學(xué)習(xí)下。2020-02-02
JSP服務(wù)器端和前端出現(xiàn)亂碼問題解決方案
這篇文章主要介紹了JSP服務(wù)器端和前端出現(xiàn)亂碼問題解決方案,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02

