直接上图

redis 动态修改快照 redis动态切换数据库_spring


复制注意包路径可直接使用

pom导包

<!-- redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>

通过key计算出db

redis 动态修改快照 redis动态切换数据库_spring_02


db总数 和存储位置

redis 动态修改快照 redis动态切换数据库_spring boot_03


有些东西冗余可以自行删减

redis方法又进行了一些封装

AbstractRedisConfig类

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: TODO
 */
@Slf4j
public abstract class AbstractRedisConfig {
    public int defaultDb = 0;

    public int totalDbs = 1;

    public Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>();

    private StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();

    abstract String getHost();
    abstract int getPort();
    abstract String getPassword();
    abstract int getMaxActive();
    abstract int getMaxIdle();
    abstract int getMinIdle();
    abstract int getMaxWait();
    abstract List<Integer> getDbs();

    @PostConstruct
    public void initRedisTemp() throws Exception {
        log.info("############################################################");
        log.info("###### START 初始化 Redis{} "+this.getClass().getSimpleName()+"连接池 START ######", this.getHost());
        if(StringUtils.isEmpty(getHost())||getHost().equalsIgnoreCase("null")){
            log.info("无配置,不需要初始化!");
            return;
        }
        defaultDb = this.getDbs().get(0);
        if(this.getDbs().size()==2&&this.getDbs().get(1)!=null){
            totalDbs = this.getDbs().get(1);
            log.info("init totalDbs : {}",totalDbs);
            for (int i = 0;i < totalDbs; i++) {
                log.info("###### 正在加载Redis-db-" + i+ " ######");
                redisTemplateMap.put(i, getRedisTemplate(i));
            }
        }else{
            log.info("init defaultDb : {}",defaultDb);
            redisTemplateMap.put(defaultDb, getRedisTemplate(defaultDb));
        }
        log.info("###### END 初始化 Redis 连接池 END ######");

        log.info("###### START 初始化 Redis-queue{} "+this.getClass().getSimpleName()+"连接池 START ######", this.getHost());
        //初始化队列
        LettuceConnectionFactory factory = null;
        if(totalDbs==1){
            log.info("###### 正在加载Redis-queue-db-" + defaultDb + " ######");
            factory = getDbFactory(defaultDb);
        }else{
            log.info("###### 正在加载Redis-queue-db-" + (totalDbs-1) + " ######");
            factory = getDbFactory(totalDbs-1);
        }

        stringRedisTemplate.setConnectionFactory(factory);
        stringRedisTemplate.afterPropertiesSet();
        log.info("###### END 初始化 Redis-queue 连接池 END ######");
    }

    private RedisTemplate<String, Object> getRedisTemplate(int dbNo) {
        return getRedisTemplate(getDbFactory(dbNo));
    }

    private LettuceConnectionFactory getDbFactory(int dbNo){
        LettuceConnectionFactory factory = new LettuceConnectionFactory(getRedisConfig(dbNo), getClientConfig());
        factory.afterPropertiesSet();//必须初始化实例
        return factory;
    }

    private RedisStandaloneConfiguration getRedisConfig(int dbNo) {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
        config.setHostName(this.getHost());
        config.setPort(this.getPort());
        config.setPassword(this.getPassword());
        config.setDatabase(dbNo);
        return config;
    }

    private LettuceClientConfiguration getClientConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(this.getMaxActive());
        poolConfig.setMaxIdle(this.getMaxIdle());
        poolConfig.setMinIdle(this.getMinIdle());
        poolConfig.setMaxWaitMillis(this.getMaxWait());
        return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
    }

    private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        setSerializer(redisTemplate);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }

    public RedisTemplate<String, Object> getRedisTemplateByDb(int db){
        return redisTemplateMap.get(db);
    }

    public StringRedisTemplate getStringRedisTemplate(){
        return stringRedisTemplate;
    }

    public StringRedisTemplate getDefaultStringRedisTemplate(){
        if(StringUtils.isEmpty(getHost())||getHost().equalsIgnoreCase("null")){
            log.info("无配置,不需要初始化!");
            return null;
        }
        LettuceConnectionFactory factory = null;
        if(totalDbs==1){
            factory = getDbFactory(defaultDb);
        }else{
            factory = getDbFactory(totalDbs-1);
        }
        StringRedisTemplate stringRedisTemplate = new StringRedisTemplate();
        stringRedisTemplate.setConnectionFactory(factory);
        stringRedisTemplate.afterPropertiesSet();
        return stringRedisTemplate;
    }

    private void setSerializer(RedisTemplate<String, Object> template) {
        Jackson2JsonRedisSerializer j2jrs = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper();
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        om.registerModule(new JavaTimeModule());
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        j2jrs.setObjectMapper(om);

        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(j2jrs);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(j2jrs);
        template.afterPropertiesSet();
    }
}

RedisConfig 类

import lombok.extern.slf4j.Slf4j;
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;

import java.util.List;


/**
 * Redis配置类
 *
 * @author qy
 */
@Slf4j
@Configuration
public class RedisConfig  extends AbstractRedisConfig{
    @Value("${spring.redis.host:null}")
    private String host;
    @Value("${spring.redis.port:-1}")
    private int port;
    @Value("${spring.redis.password:null}")
    private String password;
    @Value("${spring.redis.lettuce.pool.max-active:-1}")
    private int maxActive;
    @Value("${spring.redis.lettuce.pool.max-idle:-1}")
    private int maxIdle;
    @Value("${spring.redis.lettuce.pool.min-idle:-1}")
    private int minIdle;
    @Value("${spring.redis.lettuce.pool.max-wait:-1}")
    private int maxWait;

    @Value("${spring.redis.dbs:${spring.redis.database:-1}}")
    private List<Integer> dbs;

    @Bean
    public StringRedisTemplate stringRedisTemplate() {
        return this.getDefaultStringRedisTemplate();
    }

    String getHost(){
        return this.host;
    }

    int getPort(){
        return this.port;
    }
    String getPassword(){
        return this.password;
    }
    int getMaxActive(){
        return this.maxActive;
    }
    int getMaxIdle(){
        return this.maxIdle;
    }
    int getMinIdle(){
        return this.minIdle;
    }
    int getMaxWait(){
        return this.maxWait;
    }
    List<Integer> getDbs(){
        return this.dbs;
    }
}

AbstractRedisUtil类

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import zone.gaohu.utils.config.AbstractRedisConfig;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Description: Redis工具类
 */
public abstract class AbstractRedisUtil {
    /**
     * 补全KEY前缀
     */
    public abstract String fillingKey(String key);

    /**
     * 获取redis初始化信息
     */
    public abstract int getDbs();

    /**
     * 设置redis数据源
     *
     * @return
     */
    abstract AbstractRedisConfig getRedisConfig();

    /**
     * 获取redis队列
     */
    public StringRedisTemplate getStringRedisTemplate() {
        return this.getRedisConfig().getStringRedisTemplate();
    }

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

    /**
     * 指定缓存失效时间
     *
     * @param key  键
     * @param time 时间(秒)
     * @return
     */
    private boolean expire(String key, long time) {
        if (time > 0) {

            this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).expire(key, time, TimeUnit.SECONDS);

        }
        return true;
    }


    /**
     * 根据key 获取过期时间
     *
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).getExpire(key, TimeUnit.SECONDS);
    }


    /**
     * 判断key是否存在
     *
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).hasKey(key);
    }

    /**
     * 根据前缀模糊删除
     *
     * @param prefix Key前缀
     */
    public void delKeysByPrefix(String prefix) {
        prefix = this.fillingKey(prefix);

        if (null != prefix && prefix.trim().length() > 0) {
            for (Integer key : this.getRedisConfig().redisTemplateMap.keySet()) {
                Set<String> keys = this.getRedisConfig().getRedisTemplateByDb(key).keys(prefix.concat("*"));

                if (!CollectionUtils.isEmpty(keys)) {
                    this.getRedisConfig().getRedisTemplateByDb(key).delete(keys);
                }
            }
        }
    }

    /**
     * 删除缓存(多db情况需要单独实现批量删除-该方法慎重使用)
     *
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {

        if (key != null && key.length > 0) {

            if (key.length == 1) {
                String keyStr = this.fillingKey(key[0]);

                this.getRedisConfig().getRedisTemplateByDb(this.getIndex(keyStr)).delete(keyStr);
            } else {

//                redisTemplate.delete(CollectionUtils.arrayToList(key));
                for (String keyStr : key) {
                    keyStr = this.fillingKey(keyStr);

                    this.getRedisConfig().getRedisTemplateByDb(this.getIndex(keyStr)).delete(keyStr);
                }
            }

        }

    }

    private static final ArrayList<String> STRING_ARRAY_LIST = new ArrayList<>();
    private static final HashMap<Integer, ArrayList<String>> INTEGER_ARRAY_LIST_HASH_MAP = new HashMap();

    public static ArrayList<String> arrayListString() {
        return (ArrayList<String>) STRING_ARRAY_LIST.clone();
    }

    public static HashMap<Integer, ArrayList<String>> hashMapIntegerArrayList() {
        return (HashMap<Integer, ArrayList<String>>) INTEGER_ARRAY_LIST_HASH_MAP.clone();
    }

    public void delList(List<String> key) {
        HashMap<Integer, ArrayList<String>> hashMap;
        if (key != null && key.size() > 0) {
            hashMap = hashMapIntegerArrayList();
            //构建 需要删除的Redis HashMapDBKey
            for (String keyStr : key) {
                keyStr = this.fillingKey(keyStr);
                Integer dbPosition = this.getIndex(keyStr);
                ArrayList<String> dbArray;
                if (hashMap.containsKey(dbPosition)) {
                    dbArray = hashMap.get(dbPosition);
                } else {
                    dbArray = arrayListString();
                }
                dbArray.add(keyStr);
                hashMap.put(dbPosition, dbArray);
            }

            //删除Redis
            for (Integer redisDb : hashMap.keySet()) {
                ArrayList<String> delRedisKeyList = hashMap.get(redisDb);
                this.getRedisConfig().getRedisTemplateByDb(redisDb).delete(delRedisKeyList);
            }
        }
    }

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

    /**
     * 普通缓存获取
     *
     * @param key 键
     * @return 值
     */

    public Object get(String key) {
        if (null == key) {
            return null;
        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().get(key);
    }


    /**
     * 普通缓存放入
     *
     * @param key   键
     * @param value 值
     * @return true成功 false失败
     */

    public boolean set(String key, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().set(key, value);

        return true;
    }


    /**
     * 普通缓存放入并设置时间
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */

    public boolean set(String key, Object value, long time) {

        if (time > 0) {
            key = this.fillingKey(key);
            RedisTemplate<String, Object> redisTemplate = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key));
            redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
        } else {

            set(key, value);

        }

        return true;
    }

    /**
     * 递增
     *
     * @param key   键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递增因子必须大于0");

        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, delta);
    }


    /**
     * 递减
     *
     * @param key   键
     * @param delta 要减少几(小于0)
     * @return
     */

    public long decr(String key, long delta) {

        if (delta < 0) {

            throw new RuntimeException("递减因子必须大于0");

        }

        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, -delta);
    }


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

    /**
     * HashGet
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().get(key, item);
    }

    public Object hkeys(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().keys(key);
    }


    /**
     * 获取hashKey对应的所有键值
     *
     * @param key 键
     * @return 对应的多个键值
     */

    public Map<Object, Object> hmget(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().entries(key);
    }


    /**
     * HashSet
     *
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */

    public boolean hmset(String key, Map<String, Object> map) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);

        return true;
    }


    /**
     * HashSet 并设置时间
     *
     * @param key  键
     * @param map  对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */

    public boolean hmset(String key, Map<String, Object> map, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);

        if (time > 0) {

            expire(key, time);

        }
        return true;
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @return true 成功 false失败
     */

    public boolean hset(String key, String item, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);

        return true;
    }


    /**
     * 向一张hash表中放入数据,如果不存在将创建
     *
     * @param key   键
     * @param item  项
     * @param value 值
     * @param time  时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */

    public boolean hset(String key, String item, Object value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);

        if (time > 0) {

            expire(key, time);

        }

        return true;
    }


    /**
     * 删除hash表中的值
     *
     * @param key  键 不能为null
     * @param item 项 可以使多个 不能为null
     */

    public void hdel(String key, Object... item) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().delete(key, item);
    }


    /**
     * 判断hash表中是否有该项的值
     *
     * @param key  键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */

    public boolean hHasKey(String key, String item) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().hasKey(key, item);
    }


    /**
     * hash递增 如果不存在,就会创建一个 并把新增后的值返回
     *
     * @param key  键
     * @param item 项
     * @param by   要增加几(大于0)
     * @return
     */

    public double hincr(String key, String item, double by) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, by);
    }


    /**
     * hash递减
     *
     * @param key  键
     * @param item 项
     * @param by   要减少记(小于0)
     * @return
     */

    public double hdecr(String key, String item, double by) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, -by);
    }


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

    /**
     * 根据key获取Set中的所有值
     *
     * @param key 键
     * @return
     */

    public Set<Object> sGet(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().members(key);
    }


    /**
     * 根据value从一个set中查询,是否存在
     *
     * @param key   键
     * @param value 值
     * @return true 存在 false不存在
     */

    public boolean sHasKey(String key, Object value) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().isMember(key, value);
    }


    /**
     * 将数据放入set缓存
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 成功个数
     */

    public long sSet(String key, Object... values) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);
    }


    /**
     * 将set数据放入缓存
     *
     * @param key    键
     * @param time   时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */

    public long sSetAndTime(String key, long time, Object... values) {
        key = this.fillingKey(key);

        Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);

        if (time > 0) {
            expire(key, time);
        }

        return count;
    }


    /**
     * 获取set缓存的长度
     *
     * @param key 键
     * @return
     */
    public long sGetSetSize(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().size(key);
    }


    /**
     * 移除值为value的
     *
     * @param key    键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        key = this.fillingKey(key);

        Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().remove(key, values);

        return count;
    }

    // ===============================list=================================


    /**
     * 获取list缓存的内容
     *
     * @param key   键
     * @param start 开始
     * @param end   结束 0 到 -1代表所有值
     * @return
     */

    public List<Object> lGet(String key, long start, long end) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().range(key, start, end);
    }


    /**
     * 获取list缓存的长度
     *
     * @param key 键
     * @return
     */

    public long lGetListSize(String key) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().size(key);
    }


    /**
     * 通过索引 获取list中的值
     *
     * @param key   键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return
     */

    public Object lGetIndex(String key, long index) {
        key = this.fillingKey(key);

        return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().index(key, index);
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */

    public boolean lSet(String key, Object value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);

        if (time > 0) {
            expire(key, time);
        }

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean lSet(String key, List<Object> value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);

        return true;
    }


    /**
     * 将list放入缓存
     *
     * @param key   键
     * @param value 值
     * @param time  时间(秒)
     * @return
     */

    public boolean lSet(String key, List<Object> value, long time) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);

        if (time > 0) {
            expire(key, time);
        }

        return true;
    }


    /**
     * 根据索引修改list中的某条数据
     *
     * @param key   键
     * @param index 索引
     * @param value 值
     * @return
     */

    public boolean lUpdateIndex(String key, long index, Object value) {
        key = this.fillingKey(key);

        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().set(key, index, value);

        return true;
    }


    /**
     * 移除N个值为value
     *
     * @param key   键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        key = this.fillingKey(key);

        Long remove = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().remove(key, count, value);

        return remove;
    }

    public RedisTemplate<String, Object> getRedisTemplateByDb(int db) {
        return this.getRedisConfig().getRedisTemplateByDb(db);
    }


    public Object getDB15RedisHGet(String redisKey, String item) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForHash().get(redisKey, item);
    }

    public Object getDB15RedisGet(String redisKey) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForValue().get(redisKey);
    }

    public boolean getDB15RedisHasKey(String redisKey, String item) {
        redisKey = this.fillingKey(redisKey);

        return this.getRedisConfig().getRedisTemplateByDb(15).opsForSet().isMember(redisKey, item);
    }

    /**
     * 创建锁
     * @param key         锁的Key
     * @param value       值(随便写毫无意义)
     * @param releaseTime 锁过期时间 防止死锁
     * @return
     */
    public boolean lock(String key, int value, long releaseTime) {
        key = this.fillingKey(key);

        // 尝试获取锁
        RedisTemplate<String, Object> redisTemplate = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key));
        Boolean boo = redisTemplate.opsForValue().setIfAbsent(key, value, releaseTime, TimeUnit.SECONDS);
        // 判断结果
        return boo != null && boo;
    }

    /**
     ** 根据key删除锁
     ** @param key
     */
    public void uLock(String key) {
        key = this.fillingKey(key);
        // 删除key即可释放锁
        this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).delete(key);
    }


    public static void main(String[] args) {
        String[] keys = {
                ""
        };
        for (String key : keys) {
            long value = key.hashCode();
            int idx = ((int) (value ^ (value >>> 32)) % 250);
            System.out.printf("\n[%s] - idx:%s", key, idx);
        }
    }

    private int getIndex(String key) {
        return MathUtil.getIndex(key, this.getRedisConfig().defaultDb, this.getRedisConfig().totalDbs);
    }

}
import lombok.extern.slf4j.Slf4j;

/**
 * @Description: TODO
 */
@Slf4j
public class MathUtil {
    public static int getIndex(String key,int defaultDb,int totalDbs){
        log.debug("MathUtil.getIndex key:{} hashcode:{}",key,key.hashCode());
//        int defaultDb = RedisConfig.defaultDb;
//        int totalDbs = RedisConfig.totalDbs;
        if(totalDbs==1){
            log.info("only one db : {} ",defaultDb);
            return defaultDb;
        }
        int mod = 250;
        if(totalDbs > 1 && totalDbs < 256){
            if(totalDbs==16){
                mod = 15;
            }else{
                mod = totalDbs - 1;
            }
        }
        long value = Long.valueOf(key.hashCode());
        int hash=(int)(value ^ (value >>> 32));
        int index=hash % mod;
        log.debug("MathUtil.getIndex key:{} index:{}",key,index);
        return index;
    }
}

RedisUtils类

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import zone.gaohu.utils.config.AbstractRedisConfig;
import zone.gaohu.utils.config.RedisConfig;

/**
 * @author TT
 */
@Slf4j
@Component("redisUtils")
public class RedisUtils extends AbstractRedisUtil{

    @Autowired
    private RedisConfig redisConfig;

    @Override
    public String fillingKey(String key) {
        return key;
    }

    @Override
    public int getDbs() {
        return redisConfig.totalDbs;
    }

    @Override
    AbstractRedisConfig getRedisConfig() {
        return this.redisConfig;
    }

    public static void main(String[] args) {
        String[] keys = {
                "",
        };
        for (String key : keys) {
            long value = key.hashCode();
            int idx = ((int) (value ^ (value >>> 32)) % 250);
            System.out.printf("\n[%s] - idx:%s", key, idx);
        }
    }
}