SpringBoot註解的方式使用redis集羣模式

 

​ 使用SpringBoot都不喜歡寫xml配置文件,下面我就分享一下使用配置類的方式將redis切換到集羣模式


1、添加依賴

​ spring-boot-starter-parent已經將redis的依賴定義好了,我們不需要定義版本號:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
</dependency>

2、編寫集羣配置屬性類

package com.fcbox.sflowapp.config;

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Redis集羣屬性
 * @author 002158
 */
@Getter
@Setter
@ConfigurationProperties(prefix = "redis.cluster")
public class ClusterRedisProperties {
    /**
     * 最大連接數
     */
    private int maxTotal;
    /**
     * 最大空閒數
     */
    private int maxIdle;
    /**
     * 初始化連接數
     */
    private int minIdle;

    /**
     * 建立連接時最大等待時間,單位毫秒
     */
    private long maxWait;

    /**
     * 客戶端超時時間,單位毫秒
     */
    private int timeout;

    /**
     * 指明是否在從池中取出連接前進行檢驗,如果檢驗失敗,則從池中去除連接並嘗試取出另一個
     */
    private boolean testOnBorrow;

    /**
     * 在return給pool時,是否提前進行validate操作
     */
    private boolean testOnReturn;

    /**
     * 如果爲true,表示有一個idle object evitor線程對idle object進行掃描,如果validate失敗,此object會被從pool中drop掉;
     */
    private boolean testWhileIdle;

    /**
     * 配合testWhileIdle使用,表示idle object evitor兩次掃描之間要sleep的毫秒數
     */
    private long timeBetweenEvictionRunsMillis;

    /**
     * 集羣信息
     */
    private String nodes;

    private int maxRedirects;

    private String password;
}

3、編寫配置類

package com.fcbox.sflowapp.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.MapPropertySource;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashMap;
import java.util.Map;

/**
 * Redis集羣配置類
 * @author 002158
 */
@Configuration
@EnableConfigurationProperties(ClusterRedisProperties.class)
public class RedisConfig {
    private static final String REDIS_CLUSTER_NODES_CONFIG_PROPERTY = "spring.redis.cluster.nodes";
    private static final String REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY = "spring.redis.cluster.max-redirects";
    private static final String REDIS_CLUSTER_PROPERTIES = "redis.properties";

    @Autowired
    private ClusterRedisProperties clusterRedisProperties;

    /**
     * 配置jedis連接池
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(clusterRedisProperties.getMaxTotal());
        jedisPoolConfig.setMaxIdle(clusterRedisProperties.getMaxIdle());
        jedisPoolConfig.setMinIdle(clusterRedisProperties.getMinIdle());
        jedisPoolConfig.setMaxWaitMillis(clusterRedisProperties.getMaxWait());
        jedisPoolConfig.setTestOnBorrow(clusterRedisProperties.isTestOnBorrow());
        jedisPoolConfig.setTestOnReturn(clusterRedisProperties.isTestOnReturn());
        jedisPoolConfig.setTestWhileIdle(clusterRedisProperties.isTestWhileIdle());
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(clusterRedisProperties.getTimeBetweenEvictionRunsMillis());
        return jedisPoolConfig;
    }

    /**
     * redis集羣配置
     * @return
     */
    @Bean
    public RedisClusterConfiguration redisClusterConfiguration(){
        Map<String,Object> clusterPropertie = new HashMap<>();
        clusterPropertie.put(REDIS_CLUSTER_NODES_CONFIG_PROPERTY, clusterRedisProperties.getNodes());
        clusterPropertie.put(REDIS_CLUSTER_MAX_REDIRECTS_CONFIG_PROPERTY, clusterRedisProperties.getMaxRedirects());
        MapPropertySource mapPropertySource = new MapPropertySource(REDIS_CLUSTER_PROPERTIES, clusterPropertie);

        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration(mapPropertySource);
        return redisClusterConfiguration;
    }

    /**
     * 配置jedis連接工廠
     * @param redisClusterConfiguration
     * @param jedisPoolConfig
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory(RedisClusterConfiguration redisClusterConfiguration, JedisPoolConfig jedisPoolConfig){
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisClusterConfiguration,jedisPoolConfig );
        jedisConnectionFactory.setTimeout(clusterRedisProperties.getTimeout());
        jedisConnectionFactory.setPassword(clusterRedisProperties.getPassword());
        return jedisConnectionFactory;
    }

    /**
     * 配置RedisTemplate
     * @param factory
     * @return
     */
    @Bean
    public RedisTemplate redisTemplate(JedisConnectionFactory factory){
        RedisTemplate redisTemplate = new RedisTemplate();
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        redisTemplate.setHashValueSerializer(stringRedisSerializer);
        return redisTemplate;
    }
}

4、在disconf上傳redis.propertie配置文件

redis.cluster.max-total=16
redis.cluster.max-idle=3
redis.cluster.min-idle=1
redis.cluster.max-wait=1000
redis.cluster.timeout=1000
redis.cluster.test-on-borrow=true
redis.cluster.test-on-return=false
redis.cluster.test-while-idle=true
redis.cluster.time-between-eviction-runs-millis=160000
redis.cluster.max-redirects=3
#redis.cluster.nodes=127.0.0.1:6379
#redis.cluster.password=
# sit2
redis.cluster.nodes=10.204.58.11:8080,10.204.58.12:8080,10.204.58.13:8080,10.204.58.14:8080,10.204.58.15:8080,10.204.58.16:8080
redis.cluster.password=K6CJDjjnE9d0OxRjYNKZ
這樣就完成了集羣模式的切換了,下面測試一下:

編寫一個Controller

@RequestMapping(value = "test")
@RestController
public class TestController {
  @Autowired
  private RedisTemplate redisTemplate;
  @RequestMapping("/push")
  public Object testRedisPush(String password){
    redisTemplate.opsForValue().set("password", password);
    return "OK";
  }
  @RequestMapping("/pop")
  public Object testRedisPop(String password){
    return redisTemplate.opsForValue().get("password");
  }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章