redis配置多个数据库之新旧项目之间的取舍
首先博主先引用一篇文章,讲述的是用配置类实现多个数据库配置 https://blog.csdn.net/vicoqi/article/details/105968022 大家可以娶看看,这种方法适用于项目刚开始新建的时候一次性配置好.
但是有时候计划赶不上变化,原本没有考虑多个数据库的项目,突然来了新的需求,为了区分别的数据,只能强行使用其他数据库,同时又不能干扰其他已经使用的地方.
@Resource
private StringRedisTemplate stringRedisTemplate;
private StringRedisTemplate redisDataStorage;
@PostConstruct
private void redisDataStorage() {
JedisConnectionFactory connectionFactory = (JedisConnectionFactory) stringRedisTemplate.getConnectionFactory();
JedisConnectionFactory factory = new JedisConnectionFactory();
factory.setDatabase(10);
factory.setHostName(connectionFactory.getHostName());
factory.setUseSsl(connectionFactory.isUseSsl());
factory.setPassword(connectionFactory.getPassword());
factory.setPort(connectionFactory.getPort());
factory.afterPropertiesSet();
redisDataStorage = new StringRedisTemplate(factory);
}
这是博主的做法,在需要新数据库的类 新声明一个 redisDataStorage,然后通过一个方法
redisDataStorage将原本的stringRedisTemplate各属性赋值给redisDataStorage,同时要加上@PostConstruct这个注解,
这个注解的大概意思如下:
Java中该注解的说明:@PostConstruct该注解被用来修饰一个非静态的void()方法。被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。
通常我们会是在Spring框架中使用到@PostConstruct注解 该注解的方法在整个Bean初始化中的执行顺序
Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)
具体的用法,朋友就自行去百度吧.
`@Override
public void dataStorageRefresh(ControlPointVo controlPointVo) {
HashMap<String, String> map = new HashMap<>();
map.put("xx", object);
redisDataStorage.opsForHash().putAll("xx", map);
}`
这样就能在该方法中调用redis10号库了,并且不会干扰其他地方使用的.
另外:springboot2.0+的用LettuceConnectionFactory 这个工厂 就别用JedisConnectionFactory这个了
以为就是博主记录的一些小东西.不嫌弃的话点个赞.感谢,有不对的地方也请各位指出,同处一个互联网环境,互助互利