手撸从数据库中加载 Redis 配置
程序员文章站
2022-03-31 10:26:49
...
从数据库中加载 Redis 配置,初始化 RedisTemplate 并写入数据。
RedisReporter
public class RedisReporter implements ILocationResultReporter {
RedisTemplate<String, LocationResult> template;
private final RedisConfigEntity redisConfig;
public RedisReporter(RedisConfigEntity redisConfig) {
this.redisConfig = redisConfig;
template = new RedisTemplate<>();
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();
RedisSerializer<LocationResult> objectRedisSerializer = new Jackson2JsonRedisSerializer<>(LocationResult.class);
template.setKeySerializer(stringRedisSerializer);
template.setValueSerializer(objectRedisSerializer);
template.setStringSerializer(stringRedisSerializer);
template.setHashKeySerializer(stringRedisSerializer);
template.setHashValueSerializer(stringRedisSerializer);
RedisConnectionFactory factory = getRedisConnectionFactory(redisConfig);
template.setConnectionFactory(factory);
// 这步非常重要, 不写会提示 template 未初始化
template.afterPropertiesSet();
}
@NotNull
private RedisConnectionFactory getRedisConnectionFactory(RedisConfigEntity redisConfig) {
RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
redisStandaloneConfiguration.setHostName(redisConfig.getHost());
redisStandaloneConfiguration.setPassword(redisConfig.getPassword());
redisStandaloneConfiguration.setPort(redisConfig.getPort());
redisStandaloneConfiguration.setDatabase(redisConfig.getDbName());
return new JedisConnectionFactory(redisStandaloneConfiguration);
}
@Override
public void reportLocationResult(LocationResult locationResult) {
template.opsForList().leftPush(redisConfig.getKey(), locationResult);
}
RedisConfigEntity
从数据库中获取配置
@Entity(name = "RedisConfig")
@Data
public class RedisConfigEntity extends OutputConfig {
private String host;
private Integer port;
private Integer dbName;
private String key;
}
注意:
template.afterPropertiesSet();
java.lang.IllegalArgumentException: template not initialized; call afterPropertiesSet() before using it
上一篇: 云计算或将取代移动计算?
下一篇: 云计算引发商业领域变革
推荐阅读