代码不熟造成的Redis报错

代码不熟造成的 Redis 报错

今天遇到了一个关于 Redis 的报错问题,是对公司代码不熟悉造成的。问题不是很严重,但是也要经过师兄的指点才能发现问题。

开门见山先说问题和解决办法


问题:
本地 Redis 服务开启的时候就能跑通,本地 Redis 服务关闭的时候就报错 Could not get a resource from the pool; ……RedisConnectionException: Unable to connect to localhost:6379] with root cause

原因:
公司自己封装了一个用于操作 Redis 的工具类,但是我不知道,我用的是 RedisTemplate。

RedisTemplate 是 Spring Data Redis 提供的一个用于与 Redis 数据库进行交互的工具类,所以在 yml 中要用 Spring 的方式配置 Redis 连接参数。而我的 yml 是用的公司自定义的注入方式,所以不能成功调通参数。

解决方法:
舍弃 RedisTemplate,用公司自己封装的工具类


用 RedisTemplate 的时候:

@Autowired
private RedisTemplate<String, String> redisTemplate;
@GetMapping("/save")
public String save(@RequestParam("Id") String Id,@RequestParam("string") String string){
// 创建ValueOperations对象,用于操作Redis中的值
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
String tempString = "request" + Id;
// 存储数据
valueOperations.set(tempString, string);
// 设置过期时间
String endTime = "2023-12-10 18:50:00";
// 解析日期时间字符串
//如果endTime的值是"2023-12-10 15:30:00",那么expirationTime将包含对应的LocalDateTime对象,表示2023年12月10日下午3点30分。
LocalDateTime expirationTime = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 获取当前时间
LocalDateTime currentTime = LocalDateTime.now();
// 计算当前时间和结束时间之间的秒数
long secondsUntilExpiration = ChronoUnit.SECONDS.between(currentTime, expirationTime);
// 设置过期时间
redisTemplate.expire(tempString, secondsUntilExpiration, TimeUnit.SECONDS);
// 获取存储的数据,并输出
String retrievedValue = valueOperations.get(tempString);
System.out.println("存储数据为:" + retrievedValue);
return string;
}

如果这样编写代码的话,yml 配置文件中就要这样写:

spring:
redis:
host: localhost
port: 6379
password: 1234
database: 5

对比一下我的 yml:

spring:
……

没有 redis 的配置,所以默认加载的是 localhost。


我本地调试的时候本地 Redis 是开着的,所以接口能跑通。
但是提交代码之后就不行了。
提交代码后的 Redis 读取不到配置,所以会报错。

创作不易!转载请注明作者及文章链接或作者博客链接——
- 作者:pidanxia
- 链接:https://pidanxia.ink
(链接可为:**文章链接**或者**作者博客链接**)
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇