spring-data-redis进行选库操作

前言

spring-data-redis对reids基本操作进行很好的封装,操作时候简单便捷,但是spring-data-redis在初始化选redis某个库后不能进行修改,如果想以数据库区分业务逻辑需要进行选库操作

配置

  • 为了简单配置,在springboot的基础上配置reids操作

在springboot配置的基础上引入spring-data-redis,不同版本的springboot引入的spring-boot-starter-data-redis可能不同,具体参看官方文档

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

在application.yml或者application.properties中配置基本的连接信息如下:

spring:
  redis:
    database: 0
    host: 127.0.0.1
    password:
    pool:
      max-active: 8
      max-wait: 5000
      max-idle: 8
      min-idle: 3
    timeout: 5000

之后自定义RedisTemplate继承spring-data-redis的StringRedisTemplate,定义REDIS_DB_INDEX为ThreadLocal类型,每个线程选库操作互不影响。


    public static ThreadLocal<Integer> REDIS_DB_INDEX = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    @Override
    protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
        try {
            Integer dbIndex = REDIS_DB_INDEX.get();
            //如果设置了dbIndex
            if (dbIndex != null) {
                if (connection instanceof JedisConnection) {
                    if (((JedisConnection) connection).getNativeConnection().getDB().intValue() != dbIndex) {
                        connection.select(dbIndex);
                    }
                } else {
                    connection.select(dbIndex);
                }
            } else {
                connection.select(0);
            }
        } finally {
            REDIS_DB_INDEX.remove();
        }
        return super.preProcessConnection(connection, existingConnection);
    }
}

注册自定义的RedisTemplate到Bean容器中

@Configuration
public class RedisConfig {


    @Bean
    public RedisSerializer fastJson2JsonRedisSerializer() {
        return new FastJson2JsonRedisSerializer<Object>(Object.class);
    }

    @Bean
    public RedisTemplate initRedisTemplate(RedisConnectionFactory redisConnectionFactory, RedisSerializer fastJson2JsonRedisSerializer) throws Exception {
        RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        redisTemplate.setValueSerializer(fastJson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}

上述代码使用FastJson座位redis默认序列化工具,配置FastJson序列化需要自定义序列化器

public class FastJson2JsonRedisSerializer<T> implements RedisSerializer<T> {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Class<T> clazz;

    public FastJson2JsonRedisSerializer(Class<T> clazz) {
        super();
        this.clazz = clazz;
    }

    @Override
    public byte[] serialize(T t) throws SerializationException {
        if (t == null) {
            return new byte[0];
        }
        return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length <= 0) {
            return null;
        }
        String str = new String(bytes, DEFAULT_CHARSET);

        return (T) JSON.parseObject(str, clazz);
    }

}

之后便可以进行选库操作:

    RedisTemplate.REDIS_DB_INDEX.set(10);
    redisTemplate.opsForValue().set("author","stevejobson");

当然最好自己写一份RedisServcie封装上述操作。

注意:

Redis进行选库操作并不能提高运行效率,不过如果业务量过大,可以将不同模块的不同业务的reids存储存放到不同库中,有效的区分数据

当然强烈建议在设计redis key的时候进行能的对业务进行区分,便于后期维护

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,569评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,275评论 6 342
  • 摘要: 原创出处 www.bysocket.com 「泥瓦匠BYSocket 」欢迎转载,保留摘要,谢谢! 『产品...
    子木聊出海阅读 1,653评论 5 50
  • 子曰:“唯仁者能好人,能惡人。” 孔子說:“只有仁人才能正確喜愛人,厭惡人。” 仁人少矣。
    石埭生阅读 290评论 0 1
  • 昨天有一则新闻,说的是在昨天清晨,杭州某高档小区某户起火,消防队员现场搜出4名伤者,但将其送往医院后,均抢救...
    葡萄树的好枝子阅读 318评论 0 3

友情链接更多精彩内容