springboot1.5.2整合RedisTemplate集群(Redis4.0.10)

8 篇文章 0 订阅
3 篇文章 0 订阅

一、版本

springboot1.5.2

Redis4.0.10

 

二、集群状况

模式:Cluster 集群

密码:有

 

三、依赖包

 <!--整合redis集群-->
        <!--默认继承lettuce,切换成jedis需要排除依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
spring-boot-starter-data-redis版本是1.5.2

spring-data-redis版本是1.8.1(由spring-boot-starter-data-redis引入)

jedis版本是2.9.0

四、配置

#redis cluster
spring.redis.cluster.nodes=10.10.2.89:6379,10.10.2.89:6380,10.10.2.90:6379,10.10.2.90:6380,10.10.2.91:6379,10.10.2.91:6380
spring.redis.cluster.password =testpwd
spring.redis.cluster.timeout=2000
spring.redis.cluster.max-redirects=8

五、定义RedisTemplate


import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
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.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
@EnableCaching
public class RedisConfig {

    //------------------redis集群配置--------------------------//

    //redis集群节点列表
    @Value("${spring.redis.cluster.nodes}")
    private String clusterNodes;

    //redis集群连接超时时间
    @Value("${spring.redis.cluster.timeout}")
    private Long timeout;

    //redis集群最大连接次数
    @Value("${spring.redis.cluster.max-redirects}")
    private int redirects;

    //redis集群连接密码
    @Value("${spring.redis.cluster.password}")
    private String redisClusterPwd;

    //--------------------------------------------//

    @Bean(name = "myRedisTemplate")
    public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
        //序列化方式  使用Jackson2JsonRedisSerialize替换默认序列化(默认采用的是JDK序列化,虽然可以用,但是在redis内存的是乱码,不能可视化)
        /**
         * 1,用StringRedisSerializer进行序列化的值,在Java和Redis中保存的内容是一样的
         * 2,用Jackson2JsonRedisSerializer进行序列化的值,在Redis中保存的内容,比Java中多了一对双引号。
         * 3,用JdkSerializationRedisSerializer进行序列化的值,对于Key-Value的Value来说,是在Redis中是不可读的。对于Hash的Value来说,比Java的内容多了一些字符。
         */
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);

        //最终操作工具
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());//key是原始值
        template.setValueSerializer(jackson2JsonRedisSerializer);//value多了双引号
        template.setHashKeySerializer(new StringRedisSerializer());//key是原始值
        template.setHashValueSerializer(jackson2JsonRedisSerializer);//value多了双引号
        /**必须执行这个函数,初始化RedisTemplate*/
        template.afterPropertiesSet();

        return template;
    }


    @Bean(name="factory")
    public RedisConnectionFactory factory(RedisClusterConfiguration clusterConfig){
        JedisConnectionFactory redisConnectionFactory=new JedisConnectionFactory(clusterConfig);
        String redisPassword = redisClusterPwd;
        redisConnectionFactory.setPassword(redisPassword);
        redisConnectionFactory.setPoolConfig(createJedisPoolConfig());
        redisConnectionFactory.setTimeout(timeout.intValue());
        redisConnectionFactory.setUsePool(true);
        return redisConnectionFactory;
    }

    @Bean(name="clusterConfig")
    public RedisClusterConfiguration clusterConfig(){
        RedisClusterConfiguration config = new RedisClusterConfiguration();
        String[] nodes = clusterNodes.split(",");
        for(String node : nodes){
            String[] host =  node.split(":");
            RedisNode redis = new RedisNode(host[0], Integer.parseInt(host[1]));
            config.addClusterNode(redis);
        }
        config.setMaxRedirects(redirects);

        return config;
    }

    public JedisPoolConfig createJedisPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        //连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
        config.setBlockWhenExhausted(false);

        //设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
        config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");

        //是否启用pool的jmx管理功能, 默认true
        config.setJmxEnabled(true);

        //MBean ObjectName = new ObjectName("org.apache.commons.pool2:type=GenericObjectPool,name=" + "pool" + i); 默 认为"pool", JMX不熟,具体不知道是干啥的...默认就好.
        config.setJmxNamePrefix("pool");

        //是否启用后进先出, 默认true
        config.setLifo(true);

        //最大空闲连接数, 默认8个
        config.setMaxIdle(2000);

        //最大连接数, 默认8个
        config.setMaxTotal(5000);

        //获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
        config.setMaxWaitMillis(10000);

        //逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
        config.setMinEvictableIdleTimeMillis(1800000);

        //最小空闲连接数, 默认0
        config.setMinIdle(0);

        //每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        config.setNumTestsPerEvictionRun(3);

        //对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
        config.setSoftMinEvictableIdleTimeMillis(1800000);

        //在获取连接的时候检查有效性, 默认false
        config.setTestOnBorrow(false);

        //在空闲时检查有效性, 默认false
        config.setTestWhileIdle(false);

        //逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        config.setTimeBetweenEvictionRunsMillis(-1);

        return config;
    }


}

六、引用注入

@Autowired
@Qualifier("myRedisTemplate")
private RedisTemplate redisTemplate;

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值