jhipster 6 设置redis

背景

最近升级了JHipster,Jhipster 6使用Spring Boot 2.1作为其后端API

Spring Boot 2.0以后可以使用了spring cache来配置redis

它本质上不是一个具体的缓存实现方案(例如 EHCache 或者 OSCache),而是一个对缓存使用的抽象,通过在既有代码中添加少量它定义的各种 annotation,即能够达到缓存方法的返回对象的效果。

此处不多介绍如何使用Spring Cache,主要是介绍jHipster 6在设置redis的时候遇到的坑

描述

在application-dev.yml中,设置redis的地方只有如下代码:

1
2
3
4
jhipster:
cache: # Cache configuration
redis: # Redis configuration
expiration: 3600 # By default objects stay 1 hour (in seconds) in the cache

这样的配置,默认会连接localhost的redis,而我们希望连接的是测试服务器的redis,不知道怎么配置。

解决思路

发现CacheConfiguration有如下代码:

1
2
3
4
5
6
7
8
9
@Bean
public javax.cache.configuration.Configuration<Object, Object> jcacheConfiguration(JHipsterProperties jHipsterProperties) {
MutableConfiguration<Object, Object> jcacheConfig = new MutableConfiguration<>();
Config config = new Config();
config.useSingleServer().setAddress(jHipsterProperties.getCache().getRedis().getServer());
jcacheConfig.setStatisticsEnabled(true);
jcacheConfig.setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.SECONDS, jHipsterProperties.getCache().getRedis().getExpiration())));
return RedissonConfiguration.fromInstance(Redisson.create(config), jcacheConfig);
}

里面比较关键的是
config.useSingleServer().setAddress(jHipsterProperties.getCache().getRedis().getServer());

有此发现,我们只需要在yml中增加server配置

1
2
3
4
5
jhipster:
cache: # Cache configuration
redis: # Redis configuration
expiration: 50000 # By default objects stay 1 hour (in seconds) in the cache
server: redis://your host:port # Server address

在CacheConfiguration中设置password即可

1
2
.setAddress(jHipsterProperties.getCache().getRedis().getServer()).setDatabase(1)
.setPassword("your password");`