redis-master | redis-slave1 | redis-slave2 | redis-sentinel1 | redis-sentinel2 | redis-sentinel3 | |
---|---|---|---|---|---|---|
配置文件 | redis-9090.conf | redis-9091.conf | redis-9092.conf | sentinel-26377.conf | sentinel-26378.conf | sentinel-26379.conf |
ip | ||||||
port | 9090 | 9091 | 9092 | 26377 | 26378 | 26379 |
role | master | slave | slave | sentinel | sentinel | sentinel |
一、设置sentinel远程访问
image.png【问题】由于是自己搭建的redis的哨兵模式,所以在连接前需要看下远程访问redis的哨兵是否成功
解决方法
设置sentinel-26377.conf
的protected-mode no
;默认是该字段值是yes
二、SpringBoot连接redis哨兵模式
启动springboot项目提示:Unable to connect to 127.0.0.1:9092
问题[1]:sentinel-XXX.conf的配置为
sentinel monitor mymaster 127.0.0.1 16379 2
问题[2]:redis-XXX.conf的配置为bind 127.0.0.1
修改问题[1]中为redis集群master节点的真实地址;
修改问题[2]中为bind 0.0.0.0
三、redis-template代码
- application.properties
# redis-single
# spring.redis.host=110.24.71.71
# spring.redis.port=9090
# spring.redis.password=123456
## redis-sentinel
spring.redis.password=123456
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=110.24.71.71:26377,110.24.71.71:26378,110.24.71.71:26379
- pom.xml
<!-- 加载 spring boot redis 包 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
- 序列化
@Configuration
@EnableCaching
public class CacheConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(stringRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
【注】redisTemplate实际上是对其他框架的的封装,springboot2.x以上底层实现由jedis变为了lettuce。而且lettuce会根据配置自动选择是否用单机或者哨兵模式。
image.png image.png四、参考
【1】Redis 哨兵模式 设置密码
【2】sentinel搭建redis集群经验总结
【3】SpringBoot2.x使用Lettuce连接redis哨兵报错:RedisConnectionException: Unable to connect to 127.0.0.1:16379]:https://blog.csdn.net/repAgell/article/details/106600960
【4】解决使用jedis连接是报DENIED Redis is running in protected mode错误:https://www.cnblogs.com/lonecloud/p/9084761.html
网友评论