spring Boot集成多数据源redis

配置数据源参数

#redis
spring.redis.mickey.host=***
spring.redis.mickey.port=6379
spring.redis.mickey.password=username:password

#更多数据源
#spring.redis.db1.host=***
#spring.redis.db1.port=6379
#spring.redis.db1.password=username:password



spring.redis.pool.max-active=400
spring.redis.pool.max-wait=20
spring.redis.pool.max-idle=8
spring.redis.pool.min-idle=0

RedisConfig创建配置文件

@EnableCaching
@Configuration
public class RedisConfig {
    @Value("${spring.redis.mickey.host}")
    private String host;
    @Value("${spring.redis.mickey.port}")
    private int port;
    @Value("${spring.redis.mickey.password}")
    private String password;


    @Value("${spring.redis.pool.max-active}")
    private Integer maxActive;
    @Value("${spring.redis.pool.max-idle}")
    private Integer maxIdle;
    @Value("${spring.redis.pool.max-wait}")
    private Long maxWait;
    @Value("${spring.redis.pool.min-idle}")
    private Integer minIdle;

    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {
        GenericObjectPoolConfig genericObjectPoolConfig = new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(maxIdle);
        genericObjectPoolConfig.setMaxWaitMillis(maxWait);
        genericObjectPoolConfig.setMaxTotal(maxActive);
        genericObjectPoolConfig.setMinIdle(minIdle);
        genericObjectPoolConfig.setTimeBetweenEvictionRunsMillis(30000);
        return genericObjectPoolConfig;
    }



        @Bean(name = "mickeyRedisTemplate")
    public RedisTemplate redisTemplate() {
        RedisStandaloneConfiguration poolConfig = new RedisStandaloneConfiguration();
        poolConfig.setDatabase(0);
        poolConfig.setHostName(host);
        poolConfig.setPassword(RedisPassword.of(password));
        poolConfig.setPort(port);
        LettucePoolingClientConfiguration lpc = LettucePoolingClientConfiguration.builder().poolConfig(genericObjectPoolConfig()).clientName("mickeyJedis").build();
        LettuceConnectionFactory factory = new LettuceConnectionFactory(poolConfig, lpc);
        factory.afterPropertiesSet();

        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(factory);
        /**替换默认序列化*/
        FastJson2JsonRedisSerializer fastJson2JsonRedisSerializer = new FastJson2JsonRedisSerializer(Object.class);
        template.setKeySerializer(template.getStringSerializer());
        template.setValueSerializer(fastJson2JsonRedisSerializer);
        template.setHashKeySerializer(template.getStringSerializer());
        template.setHashValueSerializer(fastJson2JsonRedisSerializer);
        template.afterPropertiesSet();
        template.setEnableTransactionSupport(true);

        return template;
    }
    
    //复制如上方法配置,引入新的连接参数,实现多数据源连接
}

配置公共方法MickeyRedisCacheUtil

@Component
@Log4j2
public class MickeyRedisCacheUtil {

    private static final String PREFIX = "mickey_";

    @Autowired
    @Qualifier("mickeyRedisTemplate")
    RedisTemplate redisTemplate;

    //=============================common============================

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(PREFIX + key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    public boolean expireMs(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(PREFIX + key, time, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(PREFIX + key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return redisTemplate.hasKey(PREFIX + key);
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 删除缓存
     *
     * @param key 可以传一个值 或多个
     */

    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    //============================String=============================

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        Long start = System.currentTimeMillis();
        try {
            return key == null ? null : redisTemplate.opsForValue().get(PREFIX + key);
        } catch (Exception e) {
            Long end = System.currentTimeMillis();
            log.error("cacheKey=" + key + " time=" + (end - start), e);
            throw e;
        }
    }

    public Object get(boolean prefix, String key) {
        String prefixStr = "";
        if (prefix) {
            prefixStr = PREFIX;
        }
        return key == null ? null : redisTemplate.opsForValue().get(prefixStr + key);
    }

    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */
    private boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(PREFIX + key, value);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }

    }

    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(PREFIX + key, value, time, TimeUnit.SECONDS);
            } else {
                set(PREFIX + key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    public boolean set(boolean usePrefix, String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set((usePrefix ? PREFIX : "") + key, value, time, TimeUnit.SECONDS);
            } else {
                set((usePrefix ? PREFIX : "") + key, value);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }


    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(PREFIX + key, delta);
    }

    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(PREFIX + key, -delta);
    }

    //================================Map=================================

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(PREFIX + key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */
    public Map hmget(String key) {
        return redisTemplate.opsForHash().entries(PREFIX + key);
    }



    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    private boolean hmset(String key, Map map) {
        try {
            redisTemplate.opsForHash().putAll(PREFIX + key, map);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map map, long time) {
        try {
            redisTemplate.opsForHash().putAll(PREFIX + key, map);
            if (time > 0) {
                expire(PREFIX + key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */
    private boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(PREFIX + key, item, value);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒)  注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(PREFIX + key, item, value);
            if (time > 0) {
                expire(PREFIX + key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(PREFIX + key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(PREFIX + key, item);
    }

    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */
    public double hincr(String key, String item, double by) {
        double result = redisTemplate.opsForHash().increment(PREFIX + key, item, by);
//        if (time > 0) {
//            expire(PREFIX + key, time);
//        }
        return result;
    }

    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by) {
        return redisTemplate.opsForHash().increment(PREFIX + key, item, -by);
    }

    //============================set=============================

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */
    public Set sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(PREFIX + key);
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(PREFIX + key, value);
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(PREFIX + key, values);
            if (time > 0){
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(PREFIX + key);
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }

    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(PREFIX + key, values);
            return count;
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }
    //===============================list=================================

    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束  0 到 -1代表所有值
     * @return
     */
    public List lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(PREFIX + key, start, end);
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(PREFIX + key);
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引  index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(PREFIX + key, index);
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(PREFIX + key, value);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(PREFIX + key, value);
            if (time > 0){
                expire(PREFIX + key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @return
     */
    public boolean lSet(String key, List value) {
        try {
            redisTemplate.opsForList().rightPushAll(PREFIX + key, value);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */
    public boolean lSet(String key, List value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(PREFIX + key, value);
            if (time > 0){
                expire(PREFIX + key, time);
            }
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(PREFIX + key, index, value);
            return true;
        } catch (Exception e) {
            log.error("", e);
            return false;
        }
    }

    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(PREFIX + key, count, value);
            return remove;
        } catch (Exception e) {
            log.error("", e);
            return 0;
        }
    }


    public Map> hmgetPipeLine(String prefix, List noteIds) {
        try {
            Map> reslut = Maps.newHashMap();
            List ls = redisTemplate.executePipelined(new SessionCallback() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                    operations.multi();
                    log.info("hmgetPipeLine: multi" );
                    for (Object noteId:noteIds) {
                        operations.opsForHash().entries(PREFIX + prefix + noteId);
                    }
                    return operations.exec();
                }
            });
            List ll = (List)ls.get(0);
            for(int i = 0; i < noteIds.size(); i++){
                reslut.put(prefix + noteIds.get(i), (Map) ll.get(i));
            }
            return reslut;
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }

    public Map getPipeLine(String prefix, List objectIds) {
        try {
            Map reslut = Maps.newHashMap();
            List ls = redisTemplate.executePipelined(new SessionCallback() {
                @Override
                public Object execute(RedisOperations operations) throws DataAccessException {
                    operations.multi();
                    log.info("getPipeLine: multi" );
                    for (Object id:objectIds) {
                        operations.opsForValue().get(PREFIX + prefix + id);
                    }
                    return operations.exec();
                }
            });
            List ll = (List)ls.get(0);
            for(int i = 0; i < objectIds.size(); i++){
                reslut.put(prefix + objectIds.get(i), ll.get(i));
            }
            return reslut;
        } catch (Exception e) {
            log.error("", e);
            return null;
        }
    }
}

redis的使用

    @GetMapping("/redis_test")
    public Result redisTest() {
        boolean res = mickeyRedisCacheUtil.set("test_key","vaule",10);
        String str = mickeyRedisCacheUtil.get("test_key").toString();
        return Result.success(str);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值