“使用 Redis 查询的一般程序实现和击穿、雪崩、穿透”的版本间的差异
跳到导航
跳到搜索
Jihongchang(讨论 | 贡献) 小 (Jihongchang移动页面Redis 查询实现的一般程序实现至使用 Redis 查询的一般程序实现) |
Jihongchang(讨论 | 贡献) |
||
第1行: | 第1行: | ||
− | https://www.bilibili.com/video/BV1fb4y147qw/ | + | https://www.bilibili.com/video/BV1fb4y147qw/<syntaxhighlight lang="java"> |
+ | package io.github.jihch.service; | ||
+ | |||
+ | import io.github.jihch.bean.ExpressInfo; | ||
+ | import io.github.jihch.exception.ClientException; | ||
+ | import io.github.jihch.mapper.ExpressMapper; | ||
+ | import org.springframework.beans.factory.annotation.Autowired; | ||
+ | import org.springframework.data.redis.core.RedisTemplate; | ||
+ | |||
+ | import java.awt.datatransfer.Clipboard; | ||
+ | import java.time.Duration; | ||
+ | |||
+ | public class ExpressInfoService implements IExpressInfoService { | ||
+ | |||
+ | @Autowired | ||
+ | RedisTemplate redisTemplate; | ||
+ | |||
+ | @Autowired | ||
+ | ExpressMapper expressMapper; | ||
+ | |||
+ | /** | ||
+ | * 通过发货单查询物流信息 | ||
+ | * @param id | ||
+ | * @return | ||
+ | */ | ||
+ | @Override | ||
+ | public ExpressInfo findByDeliveryOrderId(Long id) { | ||
+ | String key = "xushu-express:express-info:"; | ||
+ | |||
+ | //从 Redis 查询物流信息 | ||
+ | Object obj = redisTemplate.opsForValue().get(key + id); | ||
+ | |||
+ | if (obj != null) { | ||
+ | return (ExpressInfo) obj; | ||
+ | |||
+ | } else { | ||
+ | ExpressInfo expressInfo = expressMapper.selectByDeliveryOrderId(id); | ||
+ | if (expressInfo != null) { | ||
+ | redisTemplate.opsForValue().set(key+id, expressInfo, Duration.ofHours(2)); | ||
+ | return expressInfo; | ||
+ | } else { | ||
+ | throw new ClientException("发货单:{} 的物流信息不存在", id); | ||
+ | } | ||
+ | }//end else | ||
+ | |||
+ | } | ||
+ | } | ||
+ | |||
+ | </syntaxhighlight> |
2023年2月13日 (一) 07:35的版本
https://www.bilibili.com/video/BV1fb4y147qw/
package io.github.jihch.service;
import io.github.jihch.bean.ExpressInfo;
import io.github.jihch.exception.ClientException;
import io.github.jihch.mapper.ExpressMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import java.awt.datatransfer.Clipboard;
import java.time.Duration;
public class ExpressInfoService implements IExpressInfoService {
@Autowired
RedisTemplate redisTemplate;
@Autowired
ExpressMapper expressMapper;
/**
* 通过发货单查询物流信息
* @param id
* @return
*/
@Override
public ExpressInfo findByDeliveryOrderId(Long id) {
String key = "xushu-express:express-info:";
//从 Redis 查询物流信息
Object obj = redisTemplate.opsForValue().get(key + id);
if (obj != null) {
return (ExpressInfo) obj;
} else {
ExpressInfo expressInfo = expressMapper.selectByDeliveryOrderId(id);
if (expressInfo != null) {
redisTemplate.opsForValue().set(key+id, expressInfo, Duration.ofHours(2));
return expressInfo;
} else {
throw new ClientException("发货单:{} 的物流信息不存在", id);
}
}//end else
}
}