springboot 动态切换 redis dbIndex

说明

参考 https://www.cnblogs.com/wiliamzhao/p/13298948.html
springboot版本:2.0.3.RELEASE

这里我们使用 LettuceConnectionFactory.setDatabase(dbIndex) 方法来切换redis db

pom配置

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

<!-- 序列化 java8的时间Instant、LocalDateTime、LocalDate -->
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-parameter-names</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jdk8</artifactId>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.1.0</version>
</dependency>

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>5.0.7.RELEASE</version>
</dependency>

yml配置

spring:
  redis:
    # Redis数据库索引(默认为0)
    database: 0
    # Redis服务器地址
    host: 127.0.0.1
    # Redis服务器连接端口
    port: 6380
    # Redis服务器连接密码(默认为空)
    password: 123456
    lettuce:
      pool:
        # 连接池最大连接数(使用负值表示没有限制)
        max-active: 200
        # 连接池最大阻塞等待时间(使用负值表示没有限制)
        max-wait: -1ms
        # 连接池中的最大空闲连接
        max-idle: 10
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接超时时间(毫秒)
    timeout: 1s

配置类 (RedisConfig)

注:其实是配置类初始化时为每一个db创建了一个RedisTemplate,需要的时候再去获取

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.connection.*;
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.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

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

@Configuration
public class RedisConfig {

    @Resource
    private RedisProperties redisProperties;

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

    @PostConstruct
    public void initRedisTemp() {
        for (int i = 0; i <= 15; i++) {
            redisTemplateMap.put(i, getRedisTemplate(i));
        }
    }

    public RedisTemplate setDataBase(int num) {
        return redisTemplateMap.getOrDefault(num, redisTemplateMap.get(0));
    }

    /**
     * 获取redisTemplate实例
     *
     * @param db
     * @return
     */
    private RedisTemplate<String, Object> getRedisTemplate(int db) {
        final RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        LettuceConnectionFactory factory = factory();
        factory.setDatabase(db);
        redisTemplate.setConnectionFactory(factory);
        return serializer(redisTemplate);
    }

    /**
     * redis单机配置
     *
     * @return
     */
    private RedisStandaloneConfiguration redisConfiguration() {
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(redisProperties.getHost());
        redisStandaloneConfiguration.setPort(redisProperties.getPort());
        //设置密码
        if (redisProperties.getPassword() != null) {
            redisStandaloneConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        }
        return redisStandaloneConfiguration;
    }

    /**
     * redis哨兵配置
     *
     * @return
     */
    private RedisSentinelConfiguration getSentinelConfiguration() {
        RedisProperties.Sentinel sentinel = redisProperties.getSentinel();
        if (sentinel != null) {
            RedisSentinelConfiguration config = new RedisSentinelConfiguration();
            config.setMaster(sentinel.getMaster());
            if (!StringUtils.isEmpty(redisProperties.getPassword())) {
                config.setPassword(RedisPassword.of(redisProperties.getPassword()));
            }
            config.setSentinels(createSentinels(sentinel));
            return config;
        }
        return null;
    }

    /**
     * 获取哨兵节点
     *
     * @param sentinel
     * @return
     */
    private List<RedisNode> createSentinels(RedisProperties.Sentinel sentinel) {
        List<RedisNode> nodes = new ArrayList<>();
        for (String node : sentinel.getNodes()) {
            String[] parts = StringUtils.split(node, ":");
            Assert.state(parts.length == 2, "redis哨兵地址配置不合法!");
            nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
        }
        return nodes;
    }

    /**
     * redis集群配置
     *
     * @return
     */
    private RedisClusterConfiguration getRedisClusterConfiguration() {
        RedisProperties.Cluster cluster = redisProperties.getCluster();
        if (cluster != null) {
            RedisClusterConfiguration config = new RedisClusterConfiguration();
            config.setClusterNodes(createCluster(cluster));
            if (!StringUtils.isEmpty(redisProperties.getPassword())) {
                config.setPassword(RedisPassword.of(redisProperties.getPassword()));
            }
            config.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
            return config;
        }
        return null;
    }

    /**
     * 获取集群节点
     *
     * @param cluster
     * @return
     */
    private List<RedisNode> createCluster(RedisProperties.Cluster cluster) {
        List<RedisNode> nodes = new ArrayList<>();
        for (String node : cluster.getNodes()) {
            String[] parts = StringUtils.split(node, ":");
            Assert.state(parts.length == 2, "redis哨兵地址配置不合法!");
            nodes.add(new RedisNode(parts[0], Integer.valueOf(parts[1])));
        }
        return nodes;
    }


    /**
     * 连接池配置
     *
     * @return
     */
    private GenericObjectPoolConfig redisPool() {
        GenericObjectPoolConfig genericObjectPoolConfig =
                new GenericObjectPoolConfig();
        genericObjectPoolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        genericObjectPoolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        genericObjectPoolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        genericObjectPoolConfig.setTestOnBorrow(true);
        genericObjectPoolConfig.setTestWhileIdle(true);
        genericObjectPoolConfig.setTestOnReturn(false);
        genericObjectPoolConfig.setMaxWaitMillis(5000);
        return genericObjectPoolConfig;
    }

    /**
     * redis客户端配置
     *
     * @return
     */
    private LettuceClientConfiguration clientConfiguration() {
        LettucePoolingClientConfiguration.LettucePoolingClientConfigurationBuilder builder = LettucePoolingClientConfiguration.builder();
        builder.commandTimeout(redisProperties.getLettuce().getShutdownTimeout());
        builder.shutdownTimeout(redisProperties.getLettuce().getShutdownTimeout());
        builder.poolConfig(redisPool());
        LettuceClientConfiguration lettuceClientConfiguration = builder.build();
        return lettuceClientConfiguration;
    }

    /**
     * redis获取连接工厂
     *
     * @return
     */
    @Scope(scopeName = "prototype")
    private LettuceConnectionFactory factory() {
        //根据配置和客户端配置创建连接
        LettuceConnectionFactory lettuceConnectionFactory = null;
        if (redisProperties.getSentinel() == null && redisProperties.getCluster() == null) {  //单机模式
            lettuceConnectionFactory = new LettuceConnectionFactory(redisConfiguration(), clientConfiguration());
            lettuceConnectionFactory.afterPropertiesSet();
        } else if (redisProperties.getCluster() == null) {                                      //哨兵模式
            lettuceConnectionFactory = new LettuceConnectionFactory(getSentinelConfiguration(), clientConfiguration());
            lettuceConnectionFactory.afterPropertiesSet();
        } else {                                                                                 //集群模式
            lettuceConnectionFactory = new LettuceConnectionFactory(getRedisClusterConfiguration(), clientConfiguration());
            lettuceConnectionFactory.afterPropertiesSet();
        }
        return lettuceConnectionFactory;
    }

    /**
     * 序列化
     *
     * @param redisTemplate
     * @return
     */
    private RedisTemplate<String, Object> serializer(RedisTemplate redisTemplate) {
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper om = new ObjectMapper()
                // 序列化 java8的时间Instant、LocalDateTime、LocalDate,(存储实体类的时间也可以序列化)
                .registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(om);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采用String的序列化方式
        redisTemplate.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        redisTemplate.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

工具类 (RedisUtil)

注:采用了int… db这种不定参的方式,有的方法本身就带有不定参数,所以重载了这类方法

import com.genius.switchredisdatabase.config.RedisConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 */
@Component
public class RedisUtil {

    private static Logger logger = LoggerFactory.getLogger(RedisUtil.class);

    @Resource
    private RedisConfig redisConfig;

    /**
     * 根据db获取对应的redisTemplate实例
     *
     * @param db
     * @return redisTemplate实例
     */
    public RedisTemplate<String, Object> getRedisTemplateByDb(final int... db) {
        int dbIndex = db.length > 0 ? db[0] : 0;
        return redisConfig.setDataBase(dbIndex);
    }

    // =============================key============================
    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key, long time, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(毫秒)
     * @return
     */
    public boolean pexpire(String key, long time, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 指定key永久有效
     * @param key 键
     * @return
     */
    public boolean persist(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.persist(key);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long ttl(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(毫秒) 返回0代表为永久有效
     */
    public long pttl(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.getExpire(key, TimeUnit.MILLISECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean exists(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.hasKey(key);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 判断key的类型
     * @param key 键
     * @return key类型的字符串
     */
    public String typeStr(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.type(key).code();
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 判断key的类型
     * @param key 键
     * @return key类型
     */
    public DataType type(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.type(key);
        } catch (Exception e) {
            logger.error(e.getMessage());
            return DataType.NONE;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String... key) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(0);
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete(CollectionUtils.arrayToList(key));
            }
        }
    }

    /**
     * 删除指定库缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(int db, String... key) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        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, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }
    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

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

    /**
     * 追加
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean append(String key, String value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForValue().append(key, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return
     */
    public long incr(String key, long delta, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }
    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return
     */
    public long decr(String key, long delta, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }




    // ================================Map=================================
    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

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

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

    /**
     * 删除指定库hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(int db, String key, Object... item) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hexists(String key, String item, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.opsForHash().hasKey(key, item);
    }

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

    /**
     * hash递减
     * @param key 键
     * @param item 项
     * @param by 要减少记(小于0)
     * @return
     */
    public double hdecr(String key, String item, double by, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        return redisTemplate.opsForHash().increment(key, item, -by);
    }



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

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> smembers(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sismember(String key, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sadd(String key, Object... values) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(0);
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 将数据放入指定库set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sadd(int db, String key, Object... values) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForSet().add(key, values);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

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

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sadd(int db, String key, long time, Object... values) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0)
                expire(key, time, db);
            return count;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return
     */
    public long ssize(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long srem(String key, Object... values) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(0);
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 移除指定库值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long srem(int db, String key, Object... values) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            Long c = redisTemplate.opsForSet().remove(key, values);
            return c;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }



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

    /**
     * 获取list缓存的所有内容
     * @param key 键
     * @return
     */
    public List<Object> lrange(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForList().range(key, 0, -1);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束 0 到 -1代表所有值
     * @return
     */
    public List<Object> lrange(String key, long start, long end, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return
     */
    public long llen(String key, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

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

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean rpush(String key, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param seconds 时间(秒)
     * @return
     */
    public boolean rpush(String key, Object value, long seconds, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (seconds > 0)
                expire(key, seconds, db);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return
     */
    public boolean rpushAll(String key, List value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 将list放入缓存
     *
     * @param key 键
     * @param value 值
     * @param seconds 时间(秒)
     * @return
     */
    public boolean rpushAll(String key, List value, long seconds, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (seconds > 0)
                expire(key, seconds, db);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return
     */
    public boolean lset(String key, long index, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lrem(String key, long count, Object value, int... db) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplateByDb(db);
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw e;
        }
    }
}

测试接口

import com.genius.switchredisdatabase.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/switch")
public class SwitchDatabaseResource {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 使用默认db的set方法
     * @param key
     * @param map
     */
    @PostMapping("/set/{key}")
    public void setHash(@PathVariable("key") String key, @RequestBody Map map) {
        redisUtil.set(key, map);
    }

    /**
     * 使用默认db的get方法
     * @param key
     */
    @GetMapping("/get/{key}")
    public Object setHashWithDbIndex(@PathVariable("key") String key) {
        return redisUtil.get(key);
    }

    /**
     * 使用指定dbIndex
     * @param key
     * @param dbIndex
     * @param map
     */
    @PostMapping("/withDbIndex/{key}")
    public void setWithDbIndex(@PathVariable("key") String key, @RequestParam("dbIndex") int dbIndex, @RequestBody Map map) {
        redisUtil.set(key, map, dbIndex);
    }

    /**
     * 从指定dbIndex获取
     * @param key
     * @param dbIndex
     */
    @GetMapping("/withDbIndex/{key}")
    public Object getWithDbIndex(@PathVariable("key") String key, @RequestParam("dbIndex") int dbIndex) {
        return redisUtil.get(key, dbIndex);
    }


    /**
     * 不指定db,不适用默认的redisTemplate
     * @param key
     * @param dbIndex
     */
    @PostMapping("/setWithDbIndex/{key}")
    public void addSetWithDbIndex(@PathVariable("key") String key, @RequestParam("dbIndex") int dbIndex) {
        redisUtil.sadd(dbIndex, key, "test1");
    }

    @DeleteMapping("/setWithDbIndex/{key}")
    public void delSetWithDbIndex(@PathVariable("key") String key, @RequestParam("dbIndex") int dbIndex) {
        redisUtil.srem(dbIndex, key, "test1");
    }

    @PostMapping("/setOperate/{key}")
    public void addSet(@PathVariable("key") String key) {
        redisUtil.sadd(key, "test2");
    }

    @DeleteMapping("/setOperate/{key}")
    public void delSet(@PathVariable("key") String key) {
        redisUtil.srem(key, "test2");
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值