SpringBoot使用多数据源的redis集群

ps:网上大多博客都是讲述使用多个redis数据源但是不是集群  我在各位网友的代码基础上稍加修改  可以实现配置多个 redis集群数据源  代码可以直接复制改改即可用 

并且有两种方式  有使用JedisCluster连接和RedisTemplate

pom文件

        <!-- 添加redis支持 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

application.properties

#
spring.redis-ad.cluster.nodes=127.0.0.1:7001, 127.0.0.1:7002, 127.0.0.1:7003, 127.0.0.1:7004, 127.0.0.1:7005, 127.0.0.1:7006
#
spring.redis-bubble.cluster.nodes=127.0.0.1:7001, 127.0.0.1:7002, 127.0.0.1:7003
#
spring.redis-push.cluster.nodes=127.0.0.1:7004, 127.0.0.1:7005, 127.0.0.1:7006

首先贴上JedisCluster连接方式的配置类  这种代码比较少比较简单

package com.bootdo.config;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
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.Primary;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;

import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class JedisClusterConfig {


    @Value("${spring.redis-ad.cluster.nodes}")
    String redisAd;

    @Value("${spring.redis-bubble.cluster.nodes}")
    String redisBubble;

    @Value("${spring.redis-push.cluster.nodes}")
    String redisPush;
    /**
     * 注意:
     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @Bean(name = "redisAd")
    @Primary
    public JedisCluster getJedisCluster1() {
        String[] serverArray =redisAd.split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();
 
        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        return new JedisCluster(nodes,10000,1000,1,new GenericObjectPoolConfig());//需要密码连接的创建对象方式
    }
    /**
     * 注意:
     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @Bean(name = "redisBubble")
    public JedisCluster getJedisCluster2() {
        String[] serverArray =redisBubble.split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        return new JedisCluster(nodes,10000,1000,1,new GenericObjectPoolConfig());//需要密码连接的创建对象方式
    }

    /**
     * 注意:
     * 这里返回的JedisCluster是单例的,并且可以直接注入到其他类中去使用
     * @return
     */
    @Bean(name = "redisPush")
    public JedisCluster getJedisCluster3() {
        String[] serverArray =redisPush.split(",");//获取服务器数组(这里要相信自己的输入,所以没有考虑空指针问题)
        Set<HostAndPort> nodes = new HashSet<>();

        for (String ipPort : serverArray) {
            String[] ipPortPair = ipPort.split(":");
            nodes.add(new HostAndPort(ipPortPair[0].trim(), Integer.valueOf(ipPortPair[1].trim())));
        }
        return new JedisCluster(nodes,10000,1000,1,new GenericObjectPoolConfig());//需要密码连接的创建对象方式
    }






}

使用案例: 使用不同的bean名称即可使用不用的redis集群数据源

    @Autowired
    @Qualifier("redisAd")
    private JedisCluster redisUtil;

接下来贴上redistemplate的配置类

  @Primary代表默认的数据源

package com.bootdo.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
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.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.HashSet;
import java.util.Set;

import redis.clients.jedis.JedisPoolConfig;

/**
 * @program: itv-ad-app
 * @description:
 * @author: hw
 * @create: 2019-04-29 09:22
 **/
@Configuration
public class RedisDevConfiguration {
    @Value("${spring.redis-ad.cluster.nodes}")
    String clusterNodes;

    @Value("${spring.redis-bubble.cluster.nodes}")
    String redisBubble;

    @Value("${spring.redis-push.cluster.nodes}")
    String redisPush;
    /**
     * Redis集群的配置
     *
     * @return RedisClusterConfiguration
     * @throws
     */
    @Bean(name = "redisAd1")
    @Primary
    public RedisTemplate redisClusterConfiguration() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        //Set<RedisNode> clusterNodes
        String[] serverArray = clusterNodes.split(",");
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        for (String ipPort : serverArray) {
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
        }
        redisClusterConfiguration.setClusterNodes(nodes);
        //集群模式
        JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration,new JedisPoolConfig() );
        factory.setUsePool(true);
        //实例化redistemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }

    /**
     * Redis集群的配置
     *
     * @return RedisClusterConfiguration
     * @throws
     */
    @Bean(name = "redisBubble1")
    public RedisTemplate redisClusterConfiguration2() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        //Set<RedisNode> clusterNodes
        String[] serverArray = redisPush.split(",");
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        for (String ipPort : serverArray) {
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
        }
        redisClusterConfiguration.setClusterNodes(nodes);
        //集群模式
        JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration,new JedisPoolConfig() );
        factory.setUsePool(true);
        //实例化redistemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }


    /**
     * Redis集群的配置
     *
     * @return RedisClusterConfiguration
     * @throws
     */
    @Bean(name = "redisPush1")
    public RedisTemplate redisClusterConfiguration3() {
        RedisClusterConfiguration redisClusterConfiguration = new RedisClusterConfiguration();
        //Set<RedisNode> clusterNodes
        String[] serverArray = redisBubble.split(",");
        Set<RedisNode> nodes = new HashSet<RedisNode>();
        for (String ipPort : serverArray) {
            String[] ipAndPort = ipPort.split(":");
            nodes.add(new RedisNode(ipAndPort[0].trim(), Integer.valueOf(ipAndPort[1])));
        }
        redisClusterConfiguration.setClusterNodes(nodes);
        //集群模式
        JedisConnectionFactory factory = new JedisConnectionFactory(redisClusterConfiguration,new JedisPoolConfig() );
        factory.setUsePool(true);
        //实例化redistemplate
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        return redisTemplate;
    }





}

顺带贴上帮助类 能方便的使用redistemplate

package com.bootdo.util;

import com.fasterxml.jackson.core.JsonProcessingException;

import java.util.Map;
import java.util.Set;

/**
 * redis 的操作开放接口
 * 
 * @author hk
 * 
 *         
 */
public interface RedisService {

    /**
     * 如果key不在的话就给set一个默认1  如果在则获取
     *
     * @param key
     * @return
     */
    public long getorset(String key);


    public Long setIncrValue1(String key);
    /**
     * 通过key删除
     * 
     * @param keys
     */
    public  long del(String... keys);

    /**
     * 添加key value 并且设置存活时间(byte)
     * 
     * @param key
     * @param value
     * @param liveTime
     */
    public abstract void set(byte[] key, byte[] value, long liveTime);

    /**
     * 添加key value 并且设置存活时间
     * 
     * @param key
     * @param value
     * @param liveTime
     *            单位秒
     */
    public abstract void set(String key, String value, long liveTime);

    /**
     * 添加key value
     * 
     * @param key
     * @param value
     */
    public abstract void set(String key, String value);

    /**
     * 添加key value (字节)(序列化)
     * 
     * @param key
     * @param value
     */
    public abstract void set(byte[] key, byte[] value);
    public abstract void setMap(String key, Map<String, Object> map) throws JsonProcessingException;
    public abstract Map<String,Object> getMap(String key);

    /**
     * 获取redis value (String)
     * 
     * @param key
     * @return
     */
    public abstract String get(String key);

    /**
     * 通过正则匹配keys
     * 
     * @param pattern
     * @return
     */
    public abstract  Set keys(String pattern);

    /**
     * 检查key是否已经存在
     * 
     * @param key
     * @return
     */
    public abstract boolean exists(String key);

    /**
     * 清空redis 所有数据
     * 
     * @return
     */
    public abstract String flushDB();

    /**
     * 查看redis里有多少数据
     */
    public abstract long dbSize();

    /**
     * 有序集合 添加数据
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure);
    
    /**
     * 有序集合 根据分数(范围) 获取值
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1);
    
    /**
     * 检查是否连接成功
     * 
     * @return
     */
    public abstract String ping();
       
    
    /**
     * 获取自增的值
     * @param key
     * @return
     */
    public abstract long setIncrValue(String key);

}

 注意,实现类里面用到的redistemplate  你需要根据你 自身所需再创建不同的实现类注入不同bean名称的redistemp即可

package com.bootdo.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

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

import redis.clients.jedis.JedisCluster;

/**
 * 封装redis 缓存服务器服务接口
 *
 * @author hk
 * <p>
 * 2012-12-16 上午3:09:18
 */
@Service(value = "redisService")
@SuppressWarnings("unchecked")
public class RedisServiceImpl implements RedisService {
    @SuppressWarnings("rawtypes")
    private static String redisCode = "utf-8";

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

    @Autowired
   private JedisCluster jedisCluster;
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);

    /**
     * @param keys
     */

    public long del(final String... keys) {
        return ((long) redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                long result = 0;
                for (int i = 0; i < keys.length; i++) {
                    result = connection.del(keys[i].getBytes());
                }
                return result;
            }
        }));
    }

    /**
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(final byte[] key, final byte[] value, final long liveTime) {
        redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                connection.set(key, value);
                if (liveTime > 0) {
                    connection.expire(key, liveTime);
                }
                return 1L;
            }
        });
    }

    /**
     * @param key
     * @param value
     * @param liveTime
     */
    public void set(String key, String value, long liveTime) {
        this.set(key.getBytes(), value.getBytes(), liveTime);
    }

    /**
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        this.set(key, value, 0L);
    }

    /**
     * @param key
     * @param value
     */
    public void set(byte[] key, byte[] value) {
        this.set(key, value, 0L);
    }

    /**
     * @param key
     * @param map
     */
    public void setMap(String key, Map map) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        this.set(key, objectMapper.writeValueAsString(map), 0L);
    }

    /**
     * @param key
     */
    public Map<String, Object> getMap(String key) {
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            return objectMapper.readValue(this.get(key), Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }

    /**
     * @param key
     * @return
     */
    public String get(final String key) {
        return (String) redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                String s;
                try {
                    logger.info(key);
                    s = new String(connection.get(key.getBytes()), redisCode);
                } catch (Exception e) {
                   return "";
                }
                return s;
            }
        });
    }

    /**
     * @param pattern
     * @return
     */
    public Set keys(String pattern) {
        return redisTemplate.keys(pattern);

    }

    /**
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return (boolean) redisTemplate.execute(new RedisCallback() {
            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.exists(key.getBytes());
            }
        });
    }

    /**
     * @return
     */
    public String flushDB() {
        return (String) redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {
                connection.flushDb();
                return "ok";
            }
        });
    }

    /**
     * @return
     */
    public long dbSize() {
        return (long) redisTemplate.execute(new RedisCallback() {
            public Long doInRedis(RedisConnection connection) throws DataAccessException {
                return connection.dbSize();
            }
        });
    }

    /**
     * @return
     */
    public String ping() {
        return (String) redisTemplate.execute(new RedisCallback() {
            public String doInRedis(RedisConnection connection) throws DataAccessException {

                return connection.ping();
            }
        });
    }

    public void zAdd(String key, Object value, double score) {
        ZSetOperations<String, Object> zset = this.redisTemplate.opsForZSet();
        zset.add(key, value, score);
    }

    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = this.redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }

    private RedisServiceImpl() {

    }

    /**
     * 如果key不在的话就给set一个默认0  如果在则获取
     *
     * @param key
     * @return
     */
    public long getorset(String key) {
        if (exists(key)) {
            return Integer.parseInt(get(key));
        } else {
            set(key, "0");
            return 1;
        }

    }

    /**
     *
     * @param key
     * @return
     */
    public Long setIncrValue1(String key) {

        Long increment = redisTemplate.opsForValue().increment(key, 1);
        return increment;
    }

    /**
     * 获取自增的值
     *
     * @param key
     * @return
     */
    public long setIncrValue(String key) {
        // TODO Auto-generated method stub
//        if (exists(key)) {
//            //旧值
//            Integer i = Integer.parseInt(get(key));
//            Integer i1 = i + 1;
//            set(key, i1.toString());
//            return i1;
//        } else {//不存在则新设置
//            set(key, "1");
//            return 1;
//        }

        return redisTemplate.opsForValue().increment(key, 1);





		/*return (long) redisTemplate.execute(new RedisCallback<Long>() {
			@Override
			public Long doInRedis(RedisConnection connection) throws DataAccessException {
				RedisSerializer<String> serializer=redisTemplate.getStringSerializer();
				byte[] rowkey=serializer.serialize(key);
				byte[] rowval=connection.get(rowkey);
				try {
					String val=serializer.deserialize(rowval);
					return Long.parseLong(val);
				} catch (Exception e) {
					return 0L;
				}
			}
		});*/
    }



}

使用示例: 这里通过注入不同的实现类来达到使用不同的数据源的目的

    @Resource(name = "redisService")
    RedisService redisUtil1;

点赞或者评论是我最大的动力,有问题欢迎留言或者联系q:1559810637  

猜你喜欢

转载自blog.csdn.net/qq_41594146/article/details/89669735