想在一个JAVA Class 向同一个Redis实例的不同 dbindex 写入数据,非常类似于StackOverflowe上的[How can select dbIndex when I use RedisTemplate in Spring-Data-Redis?。在这篇文章中描述了如何使用Spring boot访问Redis,在创建JedisConnectionFactory的时候指定dbindex:

JedisConnectionFactory factory = new JedisConnectionFactory(); ... factory.setDatabase(databaseId);//set dbindex

因此,大概思路是配置2个RedisTemplate,其中一个RedisTemplate负责访问dbindex=1的数据库;另一个RedisTemplate负责访问dbindex=3的数据库。

根据这篇文章,因此通过 @Bean(name=) 生成多个RedisTemplate。但是由于生成RedisTemplate需要传入JedisConnectionFactory实例,而我们是在JedisConnectionFactory中指定了访问Redis的哪个数据库(dbindex)。因此,就在创建JedisConnectionFactory实例的时候,使用 @Scope(scopeName = "prototype") 注解,这样的话Jedis连接工厂就不再是单例模式了。因此,就有两个JedisConnectionFactory实例,每个实例通过jedisConnectionFactory.setDatabase()设置不同的dbindex。这种方式可能非常愚蠢,会引起严重的性能问题。

下面,来看看具体是怎么配置的:

@Scope(scopeName = "prototype") public JedisConnectionFactory jedisConnectionFactory() { JedisPoolConfig config = getRedisConfig(); JedisConnectionFactory factory = new JedisConnectionFactory(config); factory.setUsePool(true); factory.setHostName(host); factory.setPort(port); return factory; }

每调用一次jedisConnectionFactory() 返回一个新的JedisConnectionFactory实例。

然后定义2个RedisTemplate Bean,jedisConnectionFactory.setDatabase() 方法分别设置不同的dbindex

import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; import org.springframework.data.redis.connection.jedis.JedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.StringRedisSerializer; import redis.clients.jedis.JedisPoolConfig; import java.util.Map; /** * Created by Administrator on 2018/4/9. */ @Configuration public class LoginMacRedisConfig { private static final Logger logger = LoggerFactory.getLogger(LoginMacRedisConfig.class); @Value("1") private int logmacDatabaseId; @Value("3") private int mobmaskDatabaseId; @Bean public JedisPoolConfig getRedisConfig() { JedisPoolConfig config = new JedisPoolConfig(); config.setMaxIdle(8); config.setMinIdle(0); return config; } @Scope(scopeName = "prototype") public JedisConnectionFactory jedisConnectionFactory() { JedisPoolConfig config = getRedisConfig(); JedisConnectionFactory factory = new JedisConnectionFactory(config); factory.setUsePool(true); factory.setHostName(host); factory.setPort(port); return factory; } @Bean(name = "login_mac") public RedisTemplate> logmacRedisTemplate() { final RedisTemplate> template = new RedisTemplate<>(); JedisConnectionFactory jedisConnectionFactory = jedisConnectionFactory(); jedisConnectionFactory.setDatabase(logmacDatabaseId); template.setConnectionFactory(jedisConnectionFactory); logger.info("host:{}, port:{}, database:{}", jedisConnectionFactory.getHostName(),jedisConnectionFactory.getPort(), jedisConnectionFactory.getDatabase()); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setHashValueSerializer(stringRedisSerializer); return template; } @Bean(name = "mobile_mask") public RedisTemplate> mobileMaskRedisTemplate() { final RedisTemplate> template = new RedisTemplate<>(); JedisConnectionFactory jedisConnectionFactory = jedisConnectionFactory(); jedisConnectionFactory.setDatabase(mobmaskDatabaseId); template.setConnectionFactory(jedisConnectionFactory); logger.info("host:{}, port:{}, database:{}", jedisConnectionFactory.getHostName(),jedisConnectionFactory.getPort(), jedisConnectionFactory.getDatabase()); StringRedisSerializer stringRedisSerializer = new StringRedisSerializer(); template.setKeySerializer(stringRedisSerializer); template.setHashKeySerializer(stringRedisSerializer); template.setHashValueSerializer(stringRedisSerializer); return template; } }

最后,再写一个Service类,就可以同时注入这两个RedisTemplate,操作同一个Redis服务器上的不同的dbindex了。

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * Created by Administrator on 2018/4/10. */ @Service public class RedisTestService { @Autowired @Qualifier("login_mac") private RedisTemplate> template1; @Autowired @Qualifier("mobile_mask") private RedisTemplate> template2; public void write2Redis() { HashOperations hashOperations = template1.opsForHash(); Map values = new HashMap<>(); values.put("dbindex", "1"); hashOperations.putAll("123", values); template2.opsForHash().put("123", "dbindex", "3"); } }

Application.java 启动类

@SpringBootApplication public class Application implements CommandLineRunner{ @Autowired private RedisTestService redisTestService; public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Override public void run(String... strings) throws Exception { redisTestService.write2Redis(); } }

在redisTestService对象中:有两个RedisTemplate实例:

两个RedisTemplate实例分别封装了两个JedisConnectionFactory:

调试结果下: 2018-04-10 20:18:34.754 INFO 13512 --- [ main] c.y.t.c.redis.LoginMacRedisConfig : host:192.168.107.253, port:6379, database:1

2018-04-10 20:19:06.972 INFO 13512 --- [ main] c.y.t.c.redis.LoginMacRedisConfig : host:192.168.107.253, port:6379, database:3

最终查看写入Redis结果,可以看出:dbindex 1 和 dbindex 3 都分别成功写入了数据。

redis 192.168.107.253:6379> SELECT 1 OK redis 192.168.107.253:6379[1]> KEYS * 1) "123" redis 192.168.107.253:6379[1]> HGET 123 dbindex "1" redis 192.168.107.253:6379[1]> SELECT 3 OK redis 192.168.107.253:6379[3]> KEYS * 1) "123" redis 192.168.107.253:6379[3]> HGET 123 dbindex "3"

其实要在同一个应用中访问不同的dbindex,一种方式是使用JedisPool,JedisPool创建Jedis,然后调用select方法选择dbindex。具体实现可参考这篇文章。但这样的话,就不能使用RedisTemplate的各种方便的接口读写Redis了。

@Bean public JedisPool redisPoolFactory() { JedisPool jedisPool = new JedisPool(jedisPoolConfig(), host, port); Jedis jedis = jedisPool.getResource(); jedis.select(3); return jedisPool; }

其实是可以像说的:通过RedisConnectionCommand的 select 方法来选择dbindex的,但是还是同样的问题,用不了RedisTemplate。

RedisConnection redisConnection = redisTemplate.getConnectionFactory().getConnection(); DefaultStringRedisConnection stringRedisConnection = new DefaultStringRedisConnection(redisConnection); stringRedisConnection.select(2); stringRedisConnection.set("test", "test");

另外这里也有一篇Spring Boot Redis多实例配置,也可以参考一下。Spring Boot 兼Redis新手,只能这样了。

多个redistemplate_Spring boot 使用多个RedisTemplate相关推荐

  1. 深入理解 Redis Template及4种序列化方式__spring boot整合redis实现RedisTemplate三分钟快速入门

    概述 使用Spring 提供的 Spring Data Redis 操作redis 必然要使用Spring提供的模板类 RedisTemplate, 今天我们好好的看看这个模板类 . RedisTem ...

  2. 【Spring】Spring Boot 和 Redis 自定义 RedisTemplate

    文章目录 1.概述 2.源码 3. 测试一下 3.1 存对象 3.2 存json 3.3 无序列化 4.自定义 4.1 普通的 4.2 Lettuce 1.概述 2.源码 从源码可以看到默认sprin ...

  3. Spring Boot集成Redis缓存之RedisTemplate的方式

    前言 Spring Boot 集成Redis,将自动配置 RedisTemplate,在需要使用的类中注入RedisTemplate的bean即可使用 @Autowired private Redis ...

  4. SpringBoot集成Cache缓存(Redis缓存,RedisTemplate方式)

    1.说明 SpringBoot集成Redis缓存, 首先创建一个Spring Boot工程, 使用Maven向导方式创建:SpringBoot集成Maven工程 然后引入redis的spring bo ...

  5. 太好了 | 这篇写的太好了!Spring Boot + Redis 实现接口幂等性

    Hi ! 我是小小,今天是本周的第四篇,第四篇主要内容是 Spring Boot + Redis 实现接口幂等性 介绍 幂等性的概念是,任意多次执行所产生的影响都与一次执行产生的影响相同,按照这个含义 ...

  6. 分布式缓存的选择及问题

    现如今,缓存系统的应用非常广泛,能够用来提高并发数.数据吞吐量,提高快速响应能力.那么当数据量达到一定程度,单机环境可能就显得有些力不从心了,就需要一个分布式缓存系统.分布式缓存能够处理大量的动态数据 ...

  7. alibaba Fastjson的JOSN解析库 -

    JSON,全称:JavaScript Object Notation,作为一个常见的轻量级的数据交换格式,应该在一个程序员的开发生涯中是常接触的.简洁和清晰的层次结构使得 JSON 成为理想的数据交换 ...

  8. Java zset 应用_Java简单使用redis-zset实现排行榜

    简单使用redis-zset实现排行榜 此方法实现一个根据某字段的查询次数进行排行,查询的次数越多排行越前(从大到小排序),适用于初学者 1.添加依赖 org.springframework.boot ...

  9. springboot幂等性_SpringBoot+Redis实现接口幂等性,就看这篇了

    介绍 幂等性的概念是,任意多次执行所产生的影响都与一次执行产生的影响相同,按照这个含义,最终的解释是对数据库的影响只能是一次性的,不能重复处理.手段如下 数据库建立唯一索引 token机制 悲观锁或者 ...

最新文章

  1. C++实现动态顺序表
  2. 密码技术--国密SM3哈希算法及Go语言应用
  3. 处理器在实施任务切换时的操作——《x86汇编语言:从实模式到保护模式》读书笔记39
  4. OpenCV支持向量机SVM和SDG算法的实例(附完整代码)
  5. ping 问题网络翻滚问题小结
  6. 使用RabbitMQ进行消息传递
  7. 60-100-024-使用-MySQL 表锁
  8. tesseract 使用说明
  9. 【WCF】无法加载协定为“ServiceReference1.xxxxxx”的终结点配置部分,因为找到了该协定的多个终结点配置。请按名称指示首选的终结点配置部分.
  10. c语言错误spawning,C语言一直出现Error spawning cl.exe的解决办法
  11. 15个最好的Bootstrap设计工具推荐
  12. Java千百问_05面向对象(013)_泛型如何使用
  13. 物联网安全专题 | 浅谈物联网设备安全分析方法 — 硬件篇
  14. jflash烧录教程_Jlink flash 烧录HEX 程序
  15. 富士康将和台积电联手 竞购东芝半导体业务
  16. HIT软件构造第六章一二节知识点总结
  17. 下列属于usb转串口的芯片是_USB转串口芯片——FT232R
  18. 设置浏览器的下载模式
  19. 高新技术企业认证的好处
  20. Ubuntu16.04--poco和boost库编译和安装

热门文章

  1. 【Scrapy】Unsupported major.minor version 52.0 [duplicate]
  2. [CC]CC插件初探
  3. 国家哀悼日将网站全部变成灰色的代码
  4. GenePix Pro 3.0
  5. 桌面虚拟化之用户评估指南 (翻译)
  6. oracle修改表字段约束条件,Oracle创建表、修改表、删除表、约束条件语法
  7. 信息学奥赛一本通 1051:分段函数 | OpenJudge NOI 1.4 13
  8. 信息学奥赛一本通(2030:【例4.16】找素数)
  9. XOR and Favorite Number(CF-617E)
  10. 组合数学 —— 组合数取模 —— 逆元与递推打表