【发布时间】:2019-11-27 17:31:22
【问题描述】:
我正在开发一个 Spring Boot 应用程序,我必须将 OTP 存储在弹性缓存 (Redis) 中。
弹性缓存是存储 OTP 的正确选择吗?
使用 Redis 存储 OTP
为了在本地连接到 Redis,我使用了“sudo apt-get install Redis-server”。它已安装并成功运行。
我创建了一个 Redisconfig,我在其中向应用程序配置文件询问端口和主机名。在这里,我想我会使用这个主机名和端口来连接到 aws 弹性缓存,但现在我在本地运行。
public class RedisConfig {
@Value("${redis.hostname}")
private String redisHostName;
@Value("${redis.port}")
private int redisPort;
@Bean
protected JedisConnectionFactory jedisConnectionFactory() {
return new JedisConnectionFactory();
}
@Bean
public RedisTemplate<String,Integer> redisTemplate() {
final RedisTemplate<String, Integer> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(jedisConnectionFactory());
return redisTemplate;
}
现在我使用 RedisTemplate 和 valueOperation 来放置、读取 Redis 缓存中的数据
public class MyService {
private RedisTemplate<String, Integer> redisTemplate;
private ValueOperations<String, Integer> valueOperations;
public OtpService(RedisTemplate<String, Integer> redisTemplate) {
super();
this.redisTemplate = redisTemplate;
valueOperations = redisTemplate.opsForValue();
}
public int generateOTP(String key) throws Exception {
try {
Random random = new Random();
int otp = 1000 + random.nextInt(9000);
valueOperations.set(key, otp, 120, TimeUnit.SECONDS);
return otp;
} catch (Exception e) {
throw new Exception("Exception while setting otp" + e.getMessage()) ;
}
}
public int getOtp(String key) {
try {
return valueOperations.get(key);
} catch (Exception e) {
return 0;
}
}
}
现在这就是我所做的,并且在本地运行良好。
我的问题:
在 EC2 实例中部署应用程序时需要进行哪些更改。我们需要在代码中配置主机名和端口吗?
如果我们需要配置,有没有办法在本地测试我们部署的时候会发生什么?我们能以某种方式模拟那种环境吗?
我读过,要在本地访问 aws elastic cache (Redis),我们必须设置代理服务器,这不是一个好习惯,那么我们如何才能轻松地在本地构建应用程序并部署在云上?
为什么 ValueOperations 在设置、放置方法时没有“删除”方法?在过期时间之前使用完缓存,如何使缓存失效?
在本地访问 AWS 缓存:
当我尝试通过将帖子和主机名放入 JedisConnectionFactory 实例的创建中来访问 aws 弹性缓存 (Redis) 时
@Bean
protected JedisConnectionFactory jedisConnectionFactory() {
RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration(redisHostName, redisPort);
JedisConnectionFactory factory = new JedisConnectionFactory(configuration);
return factory;
}
设置键值时出错:
无法获得绝地连接;嵌套异常是 redis.clients.jedis.exceptions.JedisConnectionException:无法获取 池中的资源
我试图解释我做了什么以及我需要知道什么? 如果有人知道任何博客,详细提及的资源,请指导我那里。
【问题讨论】:
标签: java spring amazon-web-services amazon-elasticache