网站首页 > 开源技术 正文
在工作中,我们用到分布式缓存的时候,第一选择就是Redis,今天介绍一下SpringBoot如何集成Redis的,分别使用Jedis和Spring-data-redis两种方式。
一、使用Jedis方式集成#
1、增加依赖
Copy Line-numbers language-xml<!-- spring-boot-starter-web不是必须的,这里是为了测试-->
<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不是必须的,这里是为了测试-->
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.73</version>
</dependency>
2、配置项
Copy Line-numbers language-noneredis.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、配置连接池
Copy Line-numbers language-java/**
* @author 公-众-号:程序员阿牛
* 由于Jedis实例本身不非线程安全的,因此我们用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、测试
Copy Line-numbers language-java/**
* @author 公-众-号:程序员阿牛
*/
@RestController
public class JedisController {
@Autowired
private JedisPool jedisPool;
@RequestMapping("getUser")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("张三丰");
userInfo.setAddress("武当山");
jedisPool.getResource().set("userInfo", JSON.toJSONString(userInfo));
UserInfo userInfo1 = JSON.parseObject(jedisPool.getResource().get("userInfo"),UserInfo.class);
return userInfo1.toString();
}
}
运行结果如下:
我们可以自己包装一个RedisClient,来简化我们的操作
使用spring-data-redis#
1、引入依赖
Copy Line-numbers language-xml <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置项
在application.properties中增加配置
Copy Line-numbers language-nonespring.redis.host=localhost
spring.redis.port=6379
3、使用
Copy Line-numbers language-java/**
* @author 公-众-号:程序员阿牛
*/
@RestController
public class RedisController {
@Autowired
private RedisTemplate redisTemplate;
@RequestMapping("getUser2")
public String getUserFromRedis(){
UserInfo userInfo = new UserInfo();
userInfo.setUserId("A0001");
userInfo.setUserName("张三丰");
userInfo.setAddress("武当山");
redisTemplate.opsForValue().set("userInfo", userInfo);
UserInfo userInfo1 = (UserInfo) redisTemplate.opsForValue().get("userInfo");
return userInfo1.toString();
}
}
是的,你只需要引入依赖、加入配置就可以使用Redis了,不要高兴得太早,这里面会有一些坑
4、可能会遇到的坑
使用工具查看我们刚才set的内容,发现key前面多了一串字符,value也是不可见的
原因
使用springdataredis,默认情况下是使用org.springframework.data.redis.serializer.JdkSerializationRedisSerializer这个类来做序列化
具体我们看一下RedisTemplate 代码如何实现的
Copy Line-numbers language-java/**
*在初始化的时候,默认的序列化类是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());
}
...省略无关代码
}
如何解决
很简单,自己定义RedisTemplate并指定序列化类即可
Copy Line-numbers language-java/**
* @author 公-众-号:程序员阿牛
*/
@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;
}
}
查看运行结果:
哨兵和集群#
只需要改一下配置项即可
Copy Line-numbers language-none# 哨兵
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
总结:#
以上两种方式都可以,但是还是建议你使用Spring-data-redis,因为Spring经过多年的发展,尤其是Springboot的日渐成熟,已经为我们简化了很多操作。
猜你喜欢
- 2024-10-27 Golang 入门系列(七)整合Redis详解,实战
- 2024-10-27 几个小技巧,让你的Redis程序快如闪电
- 2024-10-27 掌握这些 Redis 技巧,百亿数据量不在话下
- 2024-10-27 「高频 Redis 面试题」Redis 事务是否具备原子性?
- 2024-10-27 架构篇-一分钟掌握可扩展架构(可扩展是什么意思)
- 2024-10-27 图解Redis-命令系统设计(redis命令大全)
- 2024-10-27 Redis 数据持久化与发布订阅(redis持久化aof)
- 2024-10-27 依赖倒置原则详解(对依赖倒置的表述错误的是)
- 2024-10-27 五种分布式锁(分布式锁最佳实践)
- 2024-10-27 Alibaba/IOC-golang 正式开源——打造服务于go开发者的IOC框架
你 发表评论:
欢迎- 03-19基于layui+springcloud的企业级微服务框架
- 03-19开箱即用的前端开发模板,扩展Layui原生UI样式,集成第三方组件
- 03-19SpringMVC +Spring +Mybatis + Layui通用后台管理系统OneManageV2.1
- 03-19SpringBoot+LayUI后台管理系统开发脚手架
- 03-19layui下拉菜单form.render局部刷新方法亲测有效
- 03-19Layui 遇到的坑(记录贴)(layui chm)
- 03-19基于ASP.NET MVC + Layui的通用后台开发框架
- 03-19LayUi自定义模块的定义与使用(layui自定义表格)
- 最近发表
-
- 基于layui+springcloud的企业级微服务框架
- 开箱即用的前端开发模板,扩展Layui原生UI样式,集成第三方组件
- SpringMVC +Spring +Mybatis + Layui通用后台管理系统OneManageV2.1
- SpringBoot+LayUI后台管理系统开发脚手架
- layui下拉菜单form.render局部刷新方法亲测有效
- Layui 遇到的坑(记录贴)(layui chm)
- 基于ASP.NET MVC + Layui的通用后台开发框架
- LayUi自定义模块的定义与使用(layui自定义表格)
- Layui 2.9.11正式发布(layui2.6)
- Layui 2.9.13正式发布(layui2.6)
- 标签列表
-
- jdk (81)
- putty (66)
- rufus (78)
- 内网穿透 (89)
- okhttp (70)
- powertoys (74)
- windowsterminal (81)
- netcat (65)
- ghostscript (65)
- veracrypt (65)
- asp.netcore (70)
- wrk (67)
- aspose.words (80)
- itk (80)
- ajaxfileupload.js (66)
- sqlhelper (67)
- express.js (67)
- phpmailer (67)
- xjar (70)
- redisclient (78)
- wakeonlan (66)
- tinygo (85)
- startbbs (72)
- webftp (82)
- vsvim (79)
本文暂时没有评论,来添加一个吧(●'◡'●)