springboot连接redis哨兵集群
springboot整合redis哨兵集群
1.pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.0.3.RELEASE</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.5.0</version>
</dependency>2.application.yml
spring:
redis:
#host: 172.16.0.109 #哨兵模式下不用配置
#port: 6380 #哨兵模式下不用配置
sentinel:
master: mymaster
nodes: 172.16.0.109:8001,172.16.0.109:8002,172.16.0.109:8003
jedis:
pool:
max-active: 8
max-wait: -1
max-idle: 500
min-idle: 0
lettuce:
shutdown-timeout: 0 3.java相关类配置
(1). 哨兵配置:
@Configuration
public class RedisSentinelConfig {
@Value("${spring.redis.sentinel.nodes}")
private Set<String> nodes;
@Value("${spring.redis.sentinel.master}")
private String master;
@Bean
public RedisConnectionFactory lettuceConnectionFactory() {
RedisSentinelConfiguration redisSentinelConfiguration = new RedisSentinelConfiguration(master, nodes);
return new LettuceConnectionFactory(redisSentinelConfiguration);
}
}
(2). redis实例配置:
@Configuration
public class RedisTempLateConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<String, Object>();
//设置连接
redisTemplate.setConnectionFactory(factory);
//设置key序列化器
redisTemplate.setKeySerializer(new StringRedisSerializer(Charset.forName("UTF-8")));
//设置value序列化器
redisTemplate.setValueSerializer(new Jackson2JsonRedisSerializer<Object>(Object.class));
return redisTemplate;
}
}4.测试
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestRedis {
private static Logger logger = LoggerFactory.getLogger(TestRedis.class);
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Test
public void testSet(){
try {
logger.info("开始-------------------------------");
this.redisTemplate.opsForValue().set("ddd", "testdddd");
logger.info("#############################################"+this.redisTemplate.opsForValue().get("ddd"));
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
文章标题:springboot连接redis哨兵集群
发布时间:2019-12-12, 17:23:05
最后更新:2019-12-12, 17:23:05