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数据源进行操作

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 221,548评论 6 515
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,497评论 3 399
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 167,990评论 0 360
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,618评论 1 296
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,618评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,246评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,819评论 3 421
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,725评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,268评论 1 320
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,356评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,488评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 36,181评论 5 350
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,862评论 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,331评论 0 24
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,445评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,897评论 3 376
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,500评论 2 359

推荐阅读更多精彩内容