JAVA全系列 教程
3762个小节阅读:7092.2k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
我们需要将正在秒杀的商品从数据库同步保存到redis中,在redis中秒杀商品是以Hash类型保存,Hash的键是商品id,值是商品对象。
用户只能查询正在秒杀的商品( 开始时间 < 当前时间 < 结束时间,且库存 > 0 )
,所以我们在redis中只保存正在秒杀的商品。由于每分钟都有商品开始秒杀,也有商品结束秒杀。所以需要定时查询数据库中正在秒杀的商品,同步到redis中。我们使用SpringTask技术,每分钟同步一次数据:
修改秒杀服务的启动类,开启定时任务:
xxxxxxxxxx
@SpringBootApplication
@MapperScan("com.itbaizhan.shopping_seckill_service.mapper")
@EnableScheduling // 开启定时任务
public class ShoppingSeckillServiceApplication {
public static void main(String[] args) {
SpringApplication.run(ShoppingSeckillServiceApplication.class, args);
}
}
创建秒杀接口实现类,重写同步方法
xxxxxxxxxx
/**
* 每分钟查询一次数据库,更新redis中的秒杀商品数据
* 条件为startTime < 当前时间 < endTime,库存大于0
*/
@Scheduled(cron = "0/5 * * * * *")
public void refreshRedis(){
System.out.println("同步mysql秒杀商品到redis...");
// 1.查询数据库中正在秒杀的商品
QueryWrapper<SeckillGoods> queryWrapper = new QueryWrapper();
Date date = new Date();
String now = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
queryWrapper.le("startTime",now) // 当前时间晚于开始时间
.ge("endTime",now) // 当前时间早于开始时间
.gt("stockCount",0); // 库存大于0
List<SeckillGoods> seckillGoodsList = seckillGoodsMapper.selectList(queryWrapper);
// 2.删除之前的秒杀商品
redisTemplate.delete("seckillGoods");
// 3.保存现在正在秒杀的商品
for (SeckillGoods seckillGoods : seckillGoodsList) {
redisTemplate.boundHashOps("seckillGoods").put(seckillGoods.getGoodsId(),seckillGoods);
}
}