redis-切库

Redis库切换实践
本文介绍了一种通过重新配置RedisTemplate来实现动态切换Redis数据库的方法。该方法通过创建新的JedisConnectionFactory并设置不同的数据库索引来达到目的,适用于需要访问多个Redis数据库的场景。

   碰上获取redis不同库的信息,首先想到配置多个redisTemplate连接,可能人笨了点花费几个小时也没有成功,然后只能想到最土的方法封装一个redis的连接类,每次调用redis之前切库,直接上代码:

redis配置类

package com.steward.redis;
import com.fasterxml.jackson.annotation.JsonAutoDetect;  
import com.fasterxml.jackson.annotation.PropertyAccessor;  
import com.fasterxml.jackson.databind.ObjectMapper;
import redis.clients.jedis.JedisPoolConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;  
import org.springframework.cache.annotation.CachingConfigurerSupport;  
import org.springframework.cache.annotation.EnableCaching;  
import org.springframework.cache.interceptor.KeyGenerator;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.data.redis.cache.RedisCacheManager;  
import org.springframework.data.redis.connection.RedisConnectionFactory;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.core.StringRedisTemplate;  
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;    
import java.lang.reflect.Method;   
@Configuration  
@EnableCaching  
public class RedisConfig extends CachingConfigurerSupport{  


    @Bean  
    public KeyGenerator wiselyKeyGenerator(){  
        return new KeyGenerator() {  
            @Override  
            public Object generate(Object target, Method method, Object... params) {  
                StringBuilder sb = new StringBuilder();  
                sb.append(target.getClass().getName());  
                sb.append(method.getName());  
                for (Object obj : params) {  
                    sb.append(obj.toString());  
                }  
                return sb.toString();  
            }  
        };  
  
    }    
    @Bean  
    public CacheManager cacheManager(  
            @SuppressWarnings("rawtypes") RedisTemplate redisTemplate) {  
        return new RedisCacheManager(redisTemplate);  
    }


    
    @Bean  
    public RedisTemplate<String, String> redisTemplate(  
            RedisConnectionFactory factory) {  
        StringRedisTemplate template = new StringRedisTemplate(factory);  
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class);  
        ObjectMapper om = new ObjectMapper();  
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);  
        om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);  
        jackson2JsonRedisSerializer.setObjectMapper(om);  
        template.setValueSerializer(jackson2JsonRedisSerializer);  
        template.afterPropertiesSet();  
        return template;  
    }  

}  

测试类

package com.steward.controller.redis;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


@RestController
public class RedisController {
private static Logger logger=Logger.getLogger(RedisController.class); 
@Autowired
    private RedisTemplate<String, String> redisTemplate;  
@PostMapping("/users/redisTst/{random}")
public @ResponseBody String redisTst() {
redisTemplate=initRedis(12,redisTemplate);
String redis12=redisTemplate.opsForValue().get("00001");
logger.info("redis12 : "+redis12);
redisTemplate=initRedis(5,redisTemplate);
String redis5= redisTemplate.opsForValue().get("39E40B10-5EE9-431B-A015-5ECDA7AFE173");
logger.info("redis5 : "+redis5);
redisTemplate=initRedis(12,redisTemplate);
String redis12_2=redisTemplate.opsForValue().get("00001");
logger.info("redis12_2 : "+redis12_2);
return "success";

}
//自己改进后的封装
/**
* redis 数据库切换

*/    
   public static RedisTemplate<String, String> initRedis(Integer indexDb, RedisTemplate<String, String> redisTemplate){
       JedisConnectionFactory redisConnectionFactory = new JedisConnectionFactory(); 
       redisConnectionFactory.setHostName("192.168.0.71");  
       redisConnectionFactory.setPort(6379); 
       redisConnectionFactory.setDatabase(indexDb);
       redisConnectionFactory.setPassword("klcgj");
       redisConnectionFactory.afterPropertiesSet(); 
      
       redisTemplate.setConnectionFactory(redisConnectionFactory); 
       return redisTemplate;
   }

}

结果:


redis 库切换成功,也能获取数据


Redis换数据可以通过 `SELECT` 命令实现,该命令允许选择一个指定的数据编号以进行后续操作。Redis 默认提供 16 个数据(编号从 0 到 15),每个数据之间相互独立,不会共享键值空间[^4]。 ### 使用 `redis-cli` 换数据 通过 `redis-cli` 工具连接 Redis 后,直接使用 `SELECT` 命令后接数据编号换当前数据。例如,换到编号为 1 的数据: ```bash 127.0.0.1:6379> select 1 OK ``` 换成功后,所有后续操作都将在该数据中进行。如果需要返回默认的 0号数据,可以执行: ```bash 127.0.0.1:6379[1]> select 0 OK ``` ### 在程序中换数据 在程序中操作 Redis 时,可以使用 Redis 客户端提供的方法换数据。例如,使用 Jedis(Java 客户端)时,通过 `jedis.select(dbIndex)` 方法实现操作: ```java Jedis jedis = new Jedis(); jedis.select(10); // 换到编号为 10 的数据 jedis.set("K1", "value"); ``` 这种方式适用于需要在不同模块中使用不同数据的场景,确保数据隔离且管理便捷[^1]。 ### 使用 Spring Boot Redis 数据 在 Spring Boot 应用中,可以通过配置 Redis 连接工厂并手动指定数据编号实现。例如,通过 `RedisTemplate` 获取连接后,调用 `select` 方法换数据: ```java RedisConnection connection = redisConnectionFactory.getConnection(); connection.select(2); // 换到编号为 2 的数据 ``` 这种方式适用于项目中多个模块需要使用同一个 Redis 实例的不同数据的情况,确保数据隔离的同时简化部署管理[^2]。 ### 注意事项 尽管 Redis 提供了多个数据支持,但这些数据之间没有权限控制机制,因此不适合用于多用户隔离的场景。如果需要更复杂的隔离机制,建议使用多个 Redis 实例或结合 Redis 命名空间功能实现键的隔离[^3]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值