springboot集成redis配置多数据源

【前言】在开发需求中,很多情况一个数据源是不能够满足业务需求的,常常需要我们去配置多个数据源去综合使用完成业务需要的功能
其实多数据源本质就是多个redisTemplate

【代码】
1、依赖(这里以gradle项目为例)

dependencies {
    compile('org.springframework.boot:spring-boot-starter-data-redis')
    compile('redis.clients:jedis:2.9.0')
}

这里需要注意的是jedis的版本要在2.7以上,低版本会出现类缺省问题
2、application配置

# ------------redis多数据源配置-----------------
#共有配置
spring.redis.pool.max-active=50
spring.redis.pool.max-wait=10000
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0
spring.redis.timeout=200
#开发缓存redis
spring.redis.dev.host=10.168.99.149
spring.redis.dev.port=6379
spring.redis.dev.password=
spring.redis.dev.database=0
spring.redis.dev.testOnBorrow=false
#测试环境redis
#spring.redis.test.host=10.168.99.149
#spring.redis.test.port=6379
#spring.redis.test.password=
#spring.redis.test.database=0
#spring.redis.test.testOnBorrow=false
#线上环境redis
#spring.redis.prod.host=10.168.99.149
#spring.redis.prod.port=6379
#spring.redis.prod.password=
#spring.redis.prod.database=0
#spring.redis.prod.testOnBorrow=false

3、注入数据源

/**
 * @Author: LvFang
 * @Date: Created in 2018/7/25.
 * @Description:redis多数据源配置
 */
@Configuration
public class RedisReivceConfig {
    private static Logger logger = LoggerFactory.getLogger(ReceiverService.class);

    //---------------------------------------多数据源配置-----------------------------------------------------
    /**
     * redisDevTemplate 数据源
     */
    @Bean(name = "redisDevTemplate")
    public StringRedisTemplate redisTemplate(@Value("${spring.redis.dev.host}") String hostName,
                                             @Value("${spring.redis.dev.port}") int port,
//                                             @Value("${spring.redis.dev.password}") String password,
                                             @Value("${spring.redis.dev.testOnBorrow}") boolean testOnBorrow,
                                             @Value("${spring.redis.dev.database}") int index,
                                             @Value("${spring.redis.pool.max-idle}") int maxIdle,
                                             @Value("${spring.redis.pool.max-active}") int maxTotal,
                                             @Value("${spring.redis.pool.max-wait}") long maxWaitMillis) {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(
                connectionFactory(hostName, port, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));

        return temple;
    }

/**
     * redisTestTemplate 数据源
     */
    @Bean(name = "redisTestTemplate")
    public StringRedisTemplate redisTemplate(@Value("${spring.redis.test.host}") String hostName,
                                             @Value("${spring.redis.test.port}") int port,
//                                             @Value("${spring.redis.test.password}") String password,
                                             @Value("${spring.redis.test.testOnBorrow}") boolean testOnBorrow,
                                             @Value("${spring.redis.test.database}") int index,
                                             @Value("${spring.redis.pool.max-idle}") int maxIdle,
                                             @Value("${spring.redis.pool.max-active}") int maxTotal,
                                             @Value("${spring.redis.pool.max-wait}") long maxWaitMillis) {
        StringRedisTemplate temple = new StringRedisTemplate();
        temple.setConnectionFactory(
                connectionFactory(hostName, port, maxIdle, maxTotal, index, maxWaitMillis, testOnBorrow));
        return temple;
    }

    /**
     * 有密码
     */
    public RedisConnectionFactory connectionFactory(String hostName, int port, String password, int maxIdle,
                                                    int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(hostName);
        jedis.setPort(port);
        //如果密码不为空才去设置密码(如果没有密码,不设置或者设置空字符串即可)
        if (StringUtils.isNotEmpty(password)) {
            jedis.setPassword(password);
        }
        if (index != 0) {
            jedis.setDatabase(index);
        }
        jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow));
        // 初始化连接pool
        jedis.afterPropertiesSet();
        RedisConnectionFactory factory = jedis;
       return factory;
    }

    /**
     * 无密码
     */
    public RedisConnectionFactory connectionFactory(String hostName, int port, int maxIdle,
                                                    int maxTotal, int index, long maxWaitMillis, boolean testOnBorrow) {
        JedisConnectionFactory jedis = new JedisConnectionFactory();
        jedis.setHostName(hostName);
        jedis.setPort(port);
        if (index != 0) {
            jedis.setDatabase(index);
        }
        jedis.setPoolConfig(poolCofig(maxIdle, maxTotal, maxWaitMillis, testOnBorrow));
        // 初始化连接pool
        jedis.afterPropertiesSet();
        RedisConnectionFactory factory = jedis;
        return factory;
    }

    public 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;
    }
}

4、redisService服务类

@Service
public class RedisService {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Resource(name = "redisDevTemplate")
    private StringRedisTemplate redisTemplate;

    @Value("${global.env}")
    private String env;

    public int keys(String regEx) {
        regEx = env.concat("-").concat(regEx);
        try {
            return redisTemplate.keys(regEx).size();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return -1;
    }

    public Object getValue(String key) {
        key = env.concat("-").concat(key);
        try {
            BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);
            Object retValue = valueOperations.get();
            logger.info("get from redis {}:{}", key, retValue);
            return retValue;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }


    public void setValue(String key, Object value) {
        key = env.concat("-").concat(key);
        try {
            BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);
            valueOperations.set(String.valueOf(value), 1, TimeUnit.DAYS);
            logger.info("set to redis {}:{}", key, value);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    public void setValue(String key, Object value, int timeOut) {
        key = env.concat("-").concat(key);
        try {
            BoundValueOperations valueOperations = redisTemplate.boundValueOps(key);
            valueOperations.set(String.valueOf(value), timeOut, TimeUnit.SECONDS);
            logger.info("set to redis {}:{}", key, value);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

    /**
     * 自增1
     * @param key
     */
    public long increment(String key) {
        //给Redis中key加前缀:dev-ApiAccessCntqibumaiche2018-07-17
        key = env.concat("-").concat(key);
//    return redisTemplate.opsForValue().increment(env.concat("-").concat(key), 1);
        logger.info("increment redis {}", key);
        //对应Redis的value的值加1
        return redisTemplate.opsForValue().increment(key, 1);
    }

    /**
     * 初始化0
     * @param key
     */
    public void init(String key) {
        redisTemplate.opsForValue().set(env.concat("-").concat(key), String.valueOf(0));
    }

    public void delteKey(String key) {
        try {
            redisTemplate.delete(key);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }


    /**
     * 入队
     * @param key
     * @param value
     * @return
     */
    public Long inQueue(String key, String value) {
        return redisTemplate.opsForList().rightPush(key, value);
    }

    /**
     * 出队
     * @param key
     * @return
     */
    public String outQueue(String key) {
        return redisTemplate.opsForList().leftPop(key);
    }

    /**
     * 栈/队列长
     * @param key
     * @return
     */
    public Long length(String key) {
        return redisTemplate.opsForList().size(key);
    }

  /**
   * hash添加
   * @param key
   * @param field
   * @param value
   */
  public void hset(String key, String field, String value){
    try {
      HashOperations<String, String, String> vo = redisTemplate.opsForHash();
      vo.put(key,field,value);
    }catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
  }

  /**
   * hash获取
   * @param key
   * @param field
   * @return
   */
  public String hget(String key, String field){
    String value = null;
    try {
      HashOperations<String, String, String> vo = redisTemplate.opsForHash();
      if(vo.hasKey(key,field)){
        value = vo.get(key,field);
      }
    }catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return value;
  }

  /**
   * hash获取所有
   * @param key
   * @return
   */
  public Map<String,String> hgetall(String key){
    HashOperations<String, String, String> vo = redisTemplate.opsForHash();
    Map<String,String> map = new HashMap<>();
    for(String haskey:vo.keys(key)){
      String value = vo.get(key,haskey);
      map.put(haskey,value);
    }
    return map;
  }
}

以上可以注入多个redis数据源进行操作

    原文作者:先生_吕
    原文地址: https://www.jianshu.com/p/c21e11739fec
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞