springboot 整合redis standalone、sentinel、cluster自定义配置

 

这里用了@ConditionalOnProperty注解

例如:@ConditionalOnProperty(name = "redis.jedis.sentinelEnabled",havingValue = "true")

就是通过redis.jedis.sentinelEnabled的值和havingValue的值比较,当两个值相同返回true,配置类生效

application.yml
redis:
  jedis:
    host: 127.0.0.1
    port: 6379
    sentinels:
      - 192.168.200.135:26379
      - 192.168.200.135:26380
      - 192.168.200.135:26381
#    sentinelEnabled: true
#    standaloneEnabled: true
    clusterEnabled: true
    max-total: 20
    max-idle: 20
    max-wait-millis: 10000
    timeout: 10000
    master-name: mymaster
    clusters:
      - 192.168.200.135:7001
      - 192.168.200.135:7002
      - 192.168.200.135:7003
      - 192.168.200.135:7004
      - 192.168.200.135:7005
      - 192.168.200.135:7006
RedisProperties.class
import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

@ConfigurationProperties(prefix = "redis.jedis")
public class RedisProperties {
    private List<String> sentinels;
    private List<String> clusters;
    private String host;
    private int port;
    private int maxTotal;
    private int maxIdle;
    private int maxWaitMillis;
    private int timeout;
    private String masterName;
    private boolean sentinelEnabled;
    private boolean standaloneEnabled;
    private boolean clusterEnabled;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getMasterName() {
        return masterName;
    }

    public void setMasterName(String masterName) {
        this.masterName = masterName;
    }

    public int getMaxTotal() {
        return maxTotal;
    }

    public void setMaxTotal(int maxTotal) {
        this.maxTotal = maxTotal;
    }

    public int getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(int maxIdle) {
        this.maxIdle = maxIdle;
    }

    public int getMaxWaitMillis() {
        return maxWaitMillis;
    }

    public void setMaxWaitMillis(int maxWaitMillis) {
        this.maxWaitMillis = maxWaitMillis;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }

    public List<String> getSentinels() {
        return sentinels;
    }

    public void setSentinels(List<String> sentinels) {
        this.sentinels = sentinels;
    }

    public List<String> getClusters() {
        return clusters;
    }

    public void setClusters(List<String> clusters) {
        this.clusters = clusters;
    }
}
StandaloneRedisConfiguration.class
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@ConditionalOnProperty(name = "redis.jedis.standaloneEnabled", havingValue = "true")
public class StandaloneRedisConfiguration {
    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisProperties.getMaxTotal());
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        return config;
    }


    @Bean(name = "RedisConnectionFactory")
    public RedisConnectionFactory connectionFactory(RedisProperties properties) {
        //Jedis连接工厂 JedisConnectionFactory是RedisConnectionFactory子类
        log.info("Redis Standalone单节点配置...");
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(properties.getHost());
        redisStandaloneConfiguration.setPort(properties.getPort());
        //redisStandaloneConfiguration.setPassword(properties.getPassword());
        JedisConnectionFactory factory = new JedisConnectionFactory(redisStandaloneConfiguration);
        return factory;
    }



    @Bean(name = "RedisTemplate")
    public RedisTemplate redisTemplate() {


        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory(redisProperties));


        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        return template;
    }

    @Bean(name = "StringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(connectionFactory(redisProperties));
        return stringRedisTemplate;
    }
}
SentinelRedisConfiguration.class
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
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.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@ConditionalOnProperty(name = "redis.jedis.sentinelEnabled",havingValue = "true")
public class SentinelRedisConfiguration {
    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisProperties.getMaxTotal());
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        return config;
    }


    @Bean(name = "RedisConnectionFactory")
    public RedisConnectionFactory connectionFactory(RedisProperties properties) {
        //Jedis连接工厂 JedisConnectionFactory是RedisConnectionFactory子类
        RedisSentinelConfiguration sentinelConfig = getSentinelConfiguration(properties);
        log.info("Redis Sentinel 集群配置...");
        JedisConnectionFactory factory = new JedisConnectionFactory(sentinelConfig);
        return factory;
    }

    /**
     * 哨兵集群信息配置
     *
     * @param properties
     * @return
     */
    private RedisSentinelConfiguration getSentinelConfiguration(RedisProperties properties) {
        List<String> sentinels = properties.getSentinels();
        if (sentinels != null) {
            RedisSentinelConfiguration config = new RedisSentinelConfiguration();
            config.master(redisProperties.getMasterName());
            config.setSentinels(createSentinels(sentinels));
            //if (properties.getPassword() != null){
            //    config.setPassword(properties.getPassword());
            //}
            return config;
        }
        return null;
    }

    /**
     * 创建哨兵集群节点
     *
     * @param sentinels
     * @return
     */
    private static List<RedisNode> createSentinels(List<String> sentinels) {
        List<RedisNode> nodes = new ArrayList<>();
//        for (String node : StringUtils.commaDelimitedListToStringArray(sentinel.getNodes())) {
        for (String sentinel : sentinels) {
            String[] parts = StringUtils.split(sentinel, ":");
            Assert.state(parts.length == 2, "redis哨兵地址配置不合法!");
            nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
        }
        return nodes;
    }

    @Bean(name = "RedisTemplate")
    public RedisTemplate redisTemplate() {


        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory(redisProperties));


        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        return template;
    }

    @Bean(name = "StringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(connectionFactory(redisProperties));
        return stringRedisTemplate;
    }
}
ClusterRedisConfiguration.class
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;

@Slf4j
@Configuration
@EnableConfigurationProperties(RedisProperties.class)
@ConditionalOnProperty(name = "redis.jedis.clusterEnabled",havingValue = "true")
public class ClusterRedisConfiguration {
    @Autowired
    private RedisProperties redisProperties;

    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(redisProperties.getMaxTotal());
        config.setMaxIdle(redisProperties.getMaxIdle());
        config.setMaxWaitMillis(redisProperties.getMaxWaitMillis());
        return config;
    }


    @Bean(name = "RedisConnectionFactory")
    public RedisConnectionFactory connectionFactory(RedisProperties properties) {
        //Jedis连接工厂 JedisConnectionFactory是RedisConnectionFactory子类
        RedisClusterConfiguration clusterConfiguration = getClusterConfiguration(properties);
        log.info("Redis Cluster 集群配置...");
        JedisConnectionFactory factory = new JedisConnectionFactory(clusterConfiguration);
        return factory;
    }

    /**
     * 主从集群信息配置
     *
     * @param properties
     * @return
     */
    private RedisClusterConfiguration getClusterConfiguration(RedisProperties properties) {
        List<String> clusters = properties.getClusters();

        if (clusters != null) {
            RedisClusterConfiguration config = new RedisClusterConfiguration(clusters);
            //if (properties.getPassword() != null){
            //    config.setPassword(properties.getPassword());
            //}
            //if (cluster.getMaxRedirects() != null) {
            //    config.setMaxRedirects(cluster.getMaxRedirects());
            //}
            return config;
        }
        return null;
    }


    @Bean(name = "RedisTemplate")
    public RedisTemplate redisTemplate() {


        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory(redisProperties));


        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());

        // Hash的key也采用StringRedisSerializer的序列化方式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());

        return template;
    }

    @Bean(name = "StringRedisTemplate")
    public StringRedisTemplate StringRedisTemplate() {
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate(connectionFactory(redisProperties));
        return stringRedisTemplate;
    }
}

META-INF/spring.factories

org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.example.config.ClusterRedisConfiguration,\
com.example.config.StandaloneRedisConfiguration,\
com.example.config.SentinelRedisConfiguration

当然,你可以自己封装一个RedisService.class,例:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;


@Component
public class RedisService111 {
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    public RedisService111(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public void set(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }

    public String get(String key){
        return  stringRedisTemplate.opsForValue().get(key);
    }
}

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值