springboot 集成redis系列二

如何集成多个redis 数据源并且轻松的管理使用

第一步,同样是需要引入redis 依赖

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

第二步,添加多个redis数据源配置,我使用的是application.yml,此处仅用两个来举例说明

spring:
 redis:
    timeout: 0 # 连接超时时间(毫秒)
    jedis:
      pool:
        max-active: 8
        max-idle: 9
        max-wait: -1
        min-idle: 0
    filter:
      host: 10.90.11.60 # Redis服务器地址
      port: 6379  # Redis服务器连接端口
      password: # Redis服务器连接密码(默认为空)
      testOnBorrow: true
      database: 14 # Redis数据库索引(默认为0)
    filternew:
      host: 10.80.25.142 # Redis服务器地址
      port: 6379  # Redis服务器连接端口
      password:  # Redis服务器连接密码(默认为空)
      testOnBorrow: true
      database: 0 # Redis数据库索引(默认为0)

添加redis config 配置文件

package com.ifeng.icrawlms.config.redis;

import org.springframework.cache.interceptor.KeyGenerator;
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.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisClientConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

import java.lang.reflect.Method;

/**
 * spring-boot-data-packing 设置Redis多实例的基类
 */
@Configuration
public class RedisConfig {

    /**
     * 配置Key的生成方式
     *
     * @return
     */
    @Bean
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(o.getClass().getName())
                        .append(method.getName());
                for (Object object : objects) {
                    stringBuilder.append(object.toString());
                }
                return stringBuilder.toString();
            }
        };
    }

    public static RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle,int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {

        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        //设置redis服务器的host或者ip地址
        redisStandaloneConfiguration.setHostName(hostName);
        redisStandaloneConfiguration.setPort(port);
        redisStandaloneConfiguration.setPassword(RedisPassword.of(password));
        redisStandaloneConfiguration.setDatabase(index);
        //获得默认的连接池构造
        //这里需要注意的是,edisConnectionFactoryJ对于Standalone模式的没有(RedisStandaloneConfiguration,JedisPoolConfig)的构造函数,对此
        //我们用JedisClientConfiguration接口的builder方法实例化一个构造器,还得类型转换
        JedisClientConfiguration.JedisPoolingClientConfigurationBuilder jpcf = (JedisClientConfiguration.JedisPoolingClientConfigurationBuilder) JedisClientConfiguration.builder();
        //修改我们的连接池配置
        jpcf.poolConfig(poolCofig(maxIdle,maxTotal,maxWaitMillis,testOnBorrow));
        //通过构造器来构造jedis客户端配置
        JedisClientConfiguration jedisClientConfiguration = jpcf.build();

        return new JedisConnectionFactory(redisStandaloneConfiguration, jedisClientConfiguration);
    }

    public static  JedisPoolConfig poolCofig(int maxIdle, int maxTotal, long maxWaitMillis, boolean testOnBorrow) {
        JedisPoolConfig poolCofig = new JedisPoolConfig();
        poolCofig.setMaxIdle(maxIdle);
        poolCofig.setMaxTotal(maxTotal);
        poolCofig.setMaxWaitMillis(maxWaitMillis);
        poolCofig.setTestOnBorrow(testOnBorrow);
        return poolCofig;
    }

}

第四步, 注入第一个redis 配置的 Template : redisFilterTemplate

package com.ifeng.icrawlms.config.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

@Configuration
public class RedisFilterConfiguration extends RedisConfig{

    @Value("${spring.redis.filter.host}")
    private String host;
    @Value("${spring.redis.filter.port}")
    private int port;
    @Value("${spring.redis.filter.password}")
    private String password;
    @Value("${spring.redis.filter.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
    @Value("${spring.redis.filter.database}")
    private int index;


    @Bean(name = "redisFilterTemplate")
    public StringRedisTemplate redisTemplate() {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory( connectionFactory(host, port, password,maxIdle,maxTotal,index,maxWaitMillis,testOnBorrow));
        return temple;
    }



}

第五步, 注入第二个redis 配置的 Template : redisFilterNewTemplate

package com.ifeng.icrawlms.config.redis;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * @author Mr.C
 * @Description  
 * @create 2018/4/20 14:45
 * Copyright: Copyright (c) 2018
 * Company:CWWT
 */
@Configuration
public class RedisFilterNewConfiguration extends RedisConfig{

    @Value("${spring.redis.filternew.host}")
    private String host;
    @Value("${spring.redis.filternew.port}")
    private int port;
    @Value("${spring.redis.filternew.password}")
    private String password;
    @Value("${spring.redis.filternew.testOnBorrow}")
    private boolean testOnBorrow;
    @Value("${spring.redis.jedis.pool.max-active}")
    private int maxTotal;
    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;
    @Value("${spring.redis.jedis.pool.max-wait}")
    private long maxWaitMillis;
    @Value("${spring.redis.jedis.pool.min-idle}")
    private int minIdle;
    @Value("${spring.redis.filternew.database}")
    private int index;


    @Bean(name = "redisFilterNewTemplate")
    public StringRedisTemplate redisTemplate() {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(connectionFactory(host, port, password,maxIdle,maxTotal,index,maxWaitMillis,testOnBorrow));
        return temple;
    }

}

第六步,添加一个redis 的抽象类,实现一些redis的方法

package com.ifeng.icrawlms.redis;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

public abstract class AbRedisConfiguration  {

    protected StringRedisTemplate temple;

    public StringRedisTemplate getTemple() {
        return temple;
    }

    /**
     *  String 设置key中的字符串
     * @param key
     * @param value
     */
    public void setData(String key, String value) {
        getTemple().opsForValue().set(key, value);
    }

    /**
     *  String 设置key中的字符串
     * @param key
     * @param value
     */
    public void setData(String key, String value,Long expirtTime,TimeUnit timeUnit) {
        getTemple().opsForValue().set(key, value);
        getTemple().expire(key,expirtTime,timeUnit);
    }

    /**
     * String 获取key中的字符串
     * @param key
     * @return
     */
    public String getData(String key) {
        return getTemple().opsForValue().get(key);
    }

    /**
     * @Author: chengwei1
     * @Description:  删除key
     * @param key
     * @return: java.lang.Boolean
     * @Date: 2019/6/14 14:46
     */
    public Boolean removeData(String key){ return getTemple().delete(key);}

    /**
     * 设置key的过期时间
     * @param key
     * @param timeout
     * @param unit
     */
    public void expireKey(String key,Long timeout,TimeUnit unit){
        getTemple().expire(key,timeout,unit);
    }

    /***************************************************************************************************/

    /**
     * hash  获取hashKey 中的内容
     * @param hashKey
     * @return
     */
    public Map<Object, Object> getHashAllMap(String hashKey){
        return  getTemple().opsForHash().entries(hashKey);
    }

    /**
     * hash  获取hashKey 中某个key的内容
     * @param hashKey
     * @param key
     * @return
     */
    public Object getHashKeyData(String hashKey,String key){
        return  getTemple().opsForHash().get(hashKey,key);
    }

    /**
     * hash 添加一个hash结构数据
     * @param key
     * @param map
     */
    public void addHashData(String key, Map<String,String> map){
        getTemple().opsForHash().putAll(key,map);
    }

    /**
     * hash 添加一个hash结构数据 加一个过期时间
     * @param key
     * @param map
     * @param timeout
     * @param unit
     */
    public void addHashData(String key, Map<String,String> map,Long timeout,TimeUnit unit){
        addHashData(key,map);
        getTemple().expire(key,timeout,unit);

    }

    /**
     * @Author: chengwei1
     * @Description:
     * @param redisKey
     * @param key
     * @param value
     * @return: void
     * @Date: 2019/6/17 18:32
     */
    public void addHashData(String redisKey,String key,String value){
        getTemple().opsForHash().put(redisKey,key,value);
    }

    /**
     * hash 更新hashKey 中的内容
     * @param key
     * @param map
     */
    public void updateHashData(String key, Map<String,String> map){
        Set<Map.Entry<String, String>> set = map.entrySet();
        for(Map.Entry entry:set){
            getTemple().opsForHash().put(key,entry.getKey(),entry.getValue());
        }
    }

    /**
     *
     * @param key
     */
    public Boolean delHashKey(String key){
        return getTemple().delete(key);
    }


    /***************************************************************************************************/


    /**
     * list  设置listkey中的集合与失效时间
     * @param key
     * @param collection
     * @param time
     * @param timeunit
     */
    public void setListData(String key, Collection collection, Long time, TimeUnit timeunit){
        getTemple().opsForList().rightPushAll(key,collection);
        getTemple().expire(key,time,timeunit);
    }

    /**
     * list  获取listkey中的字符串集合
     * @param key
     * @return
     */
    public List<String> getAllListData(String key){
        List<String> list = getTemple().opsForList().range(key, 0, -1);
        return list;
    }

    /***************************************************************************************************/


    /**
     * zset 获取zsetkey从start和end范围内的数据
     * @param key
     * @param start
     * @param end
     * @return
     */
    public String zrangPage(String key,Integer start,Integer end){
        String josnStr = getTemple().opsForZSet().range(key, start, end).toString();
        return josnStr;
    }

    /**
     * zset 计算zsetkey中的数据的总数
     * @param key
     * @return
     */
    public Long zrangCount(String key){
        return getTemple().opsForZSet().zCard(key);
    }


    /***************************************************************************************************/
    /**
     * set 计算set key中的数据的总数
     * @param key
     * @return
     */
    public Long setCount(String key){
        return getTemple().opsForSet().size(key);
    }

    /**
     * set 给setkey添加一个数据
     * @param key
     * @param hotName
     */
    public void addSet(String key,String hotName){
        getTemple().opsForSet().add(key,hotName);
    }

    public Long delSetValue(String key,Object obj){
       return getTemple().opsForSet().remove(key,obj);
    }

    /**
     * set 查询所有数据
     * @param key
     * @return
     */
    public Set<String> getAllSetByKey(String key){
       return   getTemple().opsForSet().members(key);
    }

    /**
     * set 判断某个数据是否setkey的一个成员
     * @param key
     * @param hotName
     * @return
     */
    public boolean isSetMember(String key,String hotName){
        return getTemple().opsForSet().isMember(key,hotName);
    }


    /***************************************************************************************************/


    /**
     * redis 判断是否存在key
     * @param key
     * @return
     */
    public Boolean hasKey(String key){
       return  getTemple().hasKey(key);
    }

/**
     * @Author:
     * @Description: 自由切换redis的db
     * @param db
     * @return: 
     * @Date: 2019/12/11 14:32 
     */
    public void  selectDb(Integer db){
        temple=getTemple();
        JedisConnectionFactory jedisConnectionFactory= (JedisConnectionFactory) temple.getConnectionFactory();
        jedisConnectionFactory.getStandaloneConfiguration().setDatabase(db);
        temple.setConnectionFactory(jedisConnectionFactory);
    }
}

第七

步,添加两个类 获取各自的 template

package com.ifeng.icrawlms.redis;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisFilterTemple extends AbRedisConfiguration {

    @Resource(name = "redisFilterTemplate")
    private StringRedisTemplate temple;


    @Override
    public StringRedisTemplate getTemple() {
        return temple;
    }
}
package com.ifeng.icrawlms.redis;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RedisFilterNewTemple extends AbRedisConfiguration {

    @Resource(name = "redisFilterNewTemplate")
    private StringRedisTemplate temple;

    @Override
    public StringRedisTemplate getTemple() {
        return temple;
    }
}

第八步,至此 准备工作就做完了 ,下面开始看怎么调用,其他redis 的调用都类似

@Autowired
 private RedisFilterNewTemple redisFilterNewTemplate;

// 添加一个hash数据 
public void test(){
	 redisFilterNewTemplate.addHashData("redisKey","mapKey","mapValue");

    // 切换redis 的db 方式 
    redisFilterNewTemplate.selectDb(8);
	System.out.println(redisFilterNewTemplate.getData("key"));
	redisFilterNewTemplate.selectDb(0);
	System.out.println(redisFilterNewTemplate.getData("key"));
	redisFilterNewTemplate.selectDb(12);
	System.out.println(redisFilterNewTemplate.getData("key"));


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值