spring注解方式配置redis哨兵

配置文件:
#redis哨兵配置文件
sentinel.host1=192.168.xx.xx
sentinel.host2=192.168.xx.xx
sentinel.port1=xxxx
sentinel.port2=xxxx
redis.password=xxxx
redis.database=0


redis.pool.maxTotal=500
#最大能够保持idel状态的对象数  
redis.pool.maxIdle=200
#当池内没有返回对象时,最大等待时间  
redis.pool.maxWait=1000
#当调用borrow Object方法时,是否进行有效性检查
redis.pool.testOnBorrow=true
#当调用return Object方法时,是否进行有效性检查  
redis.pool.testOnReturn=true

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Sets;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.Set;

@Configuration
@PropertySource(value = "classpath:/redis_ms.properties",encoding = "UTF-8")
public class RedisConfig {

    private Logger logger = LoggerFactory.getLogger(RedisConfig.class);

    @Autowired
    private Environment environment;

    @Value("${redis.pool.maxTotal}")
    private Integer maxTotal;
    @Value("${redis.pool.maxIdle}")
    private Integer maxIdle;
    @Value("${redis.pool.testOnBorrow}")
    private Boolean testOnBorrow;
    @Value("${redis.pool.testOnReturn}")
    private Boolean testOnReturn;
    @Value("${redis.pool.maxWait}")
    private Long maxWait;
    @Value("${redis.password}")
    private String password;
    @Value("${redis.database}")
    private Integer database;

    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        logger.info("初始化redisPoolConfig.................");
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxTotal);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        jedisPoolConfig.setTestOnReturn(testOnReturn);
        jedisPoolConfig.setMaxWaitMillis(maxWait);
        return jedisPoolConfig;
    }


    @Bean
    public RedisSentinelConfiguration redisSentinelConfiguration(){
        logger.info("初始化redisSentinelConfiguration.................");
        RedisSentinelConfiguration configuration = new RedisSentinelConfiguration();
        Set<RedisNode> redisNodeSet = Sets.newHashSet();

        for (int i = 1; i < Integer.MAX_VALUE; i++) {
            String host = environment.getProperty("sentinel.host" + i);
            if(StringUtils.isEmpty(host)){
                break;
            }
            Integer port = environment.getProperty("sentinel.port" + i, Integer.class);
            redisNodeSet.add(new RedisNode(host,port));
        }
        logger.info("一共有"+redisNodeSet.size()+"个哨兵");
        configuration.setSentinels(redisNodeSet);
        configuration.setMaster("mymaster");

        return  configuration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig poolConfig,RedisSentinelConfiguration sentinelConfig){
        logger.info("初始化redisConnectionFactory.................");
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig);
        jedisConnectionFactory.setPassword(password);
        jedisConnectionFactory.setDatabase(database);
        jedisConnectionFactory.setPoolConfig(poolConfig);
        return jedisConnectionFactory;
    }

    @Bean
    public RedisTemplate<String,Object> redisTemplate(JedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String,Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        //自定义序列化方式
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();


        return redisTemplate;
    }

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要在Spring中集成配置Redis哨兵模式,需要进行以下步骤: 1. 在pom.xml文件中添加Redis依赖: ```xml <dependency> <groupId>org.springframework.data</groupId> <artifactId>spring-data-redis</artifactId> <version>2.4.6</version> </dependency> ``` 2. 在application.properties中配置Redis哨兵模式的相关参数: ``` spring.redis.sentinel.master=your-master-name spring.redis.sentinel.nodes=redis://host1:port1,redis://host2:port2,redis://host3:port3 spring.redis.password=your-password ``` 其中,`your-master-name`是Redis主节点的名称,`host1:port1,host2:port2,host3:port3`是Redis哨兵节点的地址,`your-password`是Redis连接密码。 3. 创建Redis连接工厂: ```java @Bean public RedisConnectionFactory redisConnectionFactory() { RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration() .master("your-master-name") .sentinel("host1", port1) .sentinel("host2", port2) .sentinel("host3", port3); sentinelConfig.setPassword(RedisPassword.of("your-password")); return new LettuceConnectionFactory(sentinelConfig); } ``` 其中,`your-master-name`是Redis主节点的名称,`host1,host2,host3`是Redis哨兵节点的地址,`port1,port2,port3`是Redis哨兵节点的端口号,`your-password`是Redis连接密码。 4. 创建RedisTemplate: ```java @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory()); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } ``` 在RedisTemplate中,需要设置连接工厂、key序列化器和value序列化器。 5. 在需要使用Redis的地方注入RedisTemplate: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; ``` 现在,你已经成功地在Spring中集成配置Redis哨兵模式。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值