springboot 集成redis集群、哨兵模式

1、maven依赖



   org.springframework.boot
   spring-boot-starter-data-redis


   redis.clients
   jedis
   2.9.0

2、redis.properties

#集群
redis.cmsdata.max-redirects=3
redis.cmsdata.password=psw
redis.cmsdata.cluster=127.0.0.1:8080,127.0.0.1:8081,127.0.0.1:8082,127.0.0.1:8083,127.0.0.1:8084

#哨兵模式
redis.rdsdata.password=password
redis.rdsdata.masterName=GIS
redis.rdsdata.sentinels=127.0.0.1:8080,127.0.0.1:8081,127.0.0.1:8082

3、Config配置

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.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.MapPropertySource;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

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

@Configuration
@PropertySource("classpath:redis.properties")
public class DefaultRedisConfig {

    @Value("${redis.cmsdata.cluster}")
    private String nodes;
    @Value("${redis.cmsdata.password}")
    private String pwd;
    @Value("${redis.cmsdata.max-redirects}")
    private int redirects;

    @Value("${redis.rdsdata.sentinels}")
    private String sentinels;
    @Value("${redis.rdsdata.password}")
    private String password;
    @Value("${redis.rdsdata.masterName}")
    private String master;


    /**
     * JedisPoolConfig 连接池 公用
     * @return
     */
    @Bean
    public JedisPoolConfig jedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大建立连接等待时间
        jedisPoolConfig.setMaxWaitMillis(3600);
        // 逐出连接的最小空闲时间 默认1800000毫秒(30分钟)
//        jedisPoolConfig.setMinEvictableIdleTimeMillis(1800000);
        // 每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
        jedisPoolConfig.setNumTestsPerEvictionRun(3);
        // 逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
        jedisPoolConfig.setTimeBetweenEvictionRunsMillis(-1);
        // 是否在从池中取出连接前进行检验,如果检验失败,则从池中去除连接并尝试取出另一个
        jedisPoolConfig.setTestOnBorrow(true);
        // 在空闲时检查有效性, 默认false
        jedisPoolConfig.setTestWhileIdle(false);
        return jedisPoolConfig;
    }


    // redis数据源1 集群模式
    public JedisConnectionFactory defaultRedisConnectionFactory(){
        return getJedisConnectionFactory(nodes, pwd, redirects);
    }

    private JedisConnectionFactory getJedisConnectionFactory(String nodes, String pwd, int redirects) {
        Map source = new HashMap<>();
        source.put("spring.redis.cluster.nodes", nodes);
        source.put("spring.redis.cluster.timeout", 5000);
        RedisClusterConfiguration conf = new RedisClusterConfiguration(new MapPropertySource("RedisClusterConfiguration", source));
        conf.setPassword(RedisPassword.of(pwd));
        conf.setMaxRedirects(redirects);
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(conf);
        // TODO: 下面这步很重要
        jedisConnectionFactory.afterPropertiesSet();
        return jedisConnectionFactory;
    }

    @Bean(name = "cmsRedisTemple")
    public RedisTemplate cmsRedisTemplate(){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(defaultRedisConnectionFactory());
        return redisTemplate;
    }

    //redis数据源2 哨兵模式
    @Bean
    public RedisSentinelConfiguration redisSentinelConfiguration(){
        RedisSentinelConfiguration configuration = new RedisSentinelConfiguration();
        String[] host = sentinels.split(",");
        for(String redisHost : host){
            String[] item = redisHost.split(":");
            String ip = item[0];
            String port = item[1];
            configuration.addSentinel(new RedisNode(ip, Integer.parseInt(port)));
        }
        configuration.setMaster(master);
        configuration.setPassword(password);
        return configuration;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(redisSentinelConfiguration(),jedisPoolConfig());
        return jedisConnectionFactory;
    }

    @Bean(name = "rdsRedisTemplate")
    public RedisTemplate rdsRedisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate redisTemplate = new RedisTemplate<>();
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(jedisConnectionFactory());
        // 开启事务
        redisTemplate.setEnableTransactionSupport(true);
        return redisTemplate;
    }
}

4、redis辅助类

import com.google.common.collect.Maps;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Map;


@Component
public class RedisService {

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

    @Autowired
    @Qualifier("rdsRedisTemplate")
    private RedisTemplate rdsRedisTemplate;

    //String 类型操作
    public void setString(String key, String value){
        this.redisTemplate.opsForValue().set(key,value);
    }

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

    public void delString(String key){
        this.redisTemplate.delete(key);
    }

    //Hash 类型操作
    public Map getHash(String key){
        Map resultMap= Maps.newHashMap();
        resultMap=this.rdsRedisTemplate.opsForHash().entries(key);
        return resultMap;
    }

    public void setHash(String key,Map myMap){
        this.rdsRedisTemplate.opsForHash().putAll(key,myMap);
    }


}

5、控制层

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import sf.myboot.service.RedisService;

import java.util.Map;

@Controller
@RequestMapping(value="redis")
public class RedisController {
    @Autowired
    RedisService redisService;


    @GetMapping(value="getString")
    @ResponseBody
    public String getTest(String code){
        String code=redisService.getString("GIS:"+code);
        return code;
    }

    @GetMapping(value="getHash")
    @ResponseBody
    public String getHash(){
        Map data=redisService.getHash("firstTest");
        return JSON.toJSONString(data);
    }

}

你可能感兴趣的:(redis)