在工作中,咱们用到分布式缓存的时候,第一抉择就是Redis,明天介绍一下SpringBoot如何集成Redis的,别离应用Jedis和Spring-data-redis两种形式。
一、应用Jedis形式集成
1、减少依赖
<!-- 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、配置项
redis.host=localhostredis.maxTotal=5redis.maxIdle=5redis.testOnBorrow=true#以下形式也能够,SpringBoot同样能将其解析注入到JedisPoolConfig中#redis.max-total=3#redis.max-idle=3#redis.test-on-borrow=true
3、配置连接池
/** * @author 公-众-号:程序员阿牛 * 因为Jedis实例自身不非线程平安的,因而咱们用JedisPool */@Configurationpublic 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、测试
/** * @author 公-众-号:程序员阿牛 */@RestControllerpublic 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、引入依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
2、配置项
在application.properties中减少配置
spring.redis.host=localhostspring.redis.port=6379
3、应用
/** * @author 公-众-号:程序员阿牛 */@RestControllerpublic 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 代码如何实现的
/***在初始化的时候,默认的序列化类是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并指定序列化类即可
/** * @author 公-众-号:程序员阿牛 */@Configurationpublic 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; }}
查看运行后果:
哨兵和集群
只须要改一下配置项即可
# 哨兵spring.redis.sentinel.master=mymasterspring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26380,127.0.0.1:26381#集群spring.redis.cluster.max-redirects=100spring.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的日渐成熟,曾经为咱们简化了很多操作。