From 4eab4ae3340e8c0222218ad463bcdd6009807586 Mon Sep 17 00:00:00 2001 From: p4exgo9f5 <3031186461@qq.com> Date: Tue, 29 Apr 2025 16:21:45 +0800 Subject: [PATCH] ADD file via upload --- CacheDataJob.java | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 CacheDataJob.java diff --git a/CacheDataJob.java b/CacheDataJob.java new file mode 100644 index 0000000..84aa902 --- /dev/null +++ b/CacheDataJob.java @@ -0,0 +1,54 @@ +package com.rabbiter.market.data_job; + +import com.rabbiter.market.common.redis.constants.RedisKeys; +import com.rabbiter.market.common.redis.service.RedisTemplateService; +import com.rabbiter.market.domain.goods_management.goods_category.GoodsCategory; +import com.rabbiter.market.service.goods_management.goods_category.IGoodsCategoryService; +import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +import java.util.List; + +/** + * 缓存数据定时任务类 + */ +@Component // 声明为Spring组件,由Spring容器管理 +public class CacheDataJob { + @Autowired // 自动注入Redis操作服务 + private RedisTemplateService redisTemplateService; + @Autowired // 自动注入商品分类服务 + private IGoodsCategoryService goodsCategoryService; + + /** + * 定时缓存商品分类数据到Redis + * 每天凌晨1点执行一次 + */ + @Scheduled(cron = "0 0 1 * * ?") // 使用cron表达式定义定时任务执行时间(每天凌晨1点) + public void cache_category(){ + // 打印执行日志 + System.out.println("被执行。。。。"); + + // 创建查询条件:只查询状态为正常的商品分类 + QueryWrapper wrapper = new QueryWrapper() + .eq("state", GoodsCategory.STATE_NORMAL); + + // 查询符合条件的商品分类列表 + List list = goodsCategoryService.list(wrapper); + + // 如果查询结果为空,则直接返回 + if (list==null ||list.size()<=0){ + return; + } + + // 获取商品分类在Redis中的缓存键 + String cacheKey = RedisKeys.GOODS_CATEGORY.join(); + + // 遍历查询结果,将每个商品分类存入Redis缓存 + for (GoodsCategory goodsCategory : list) { + // 使用商品分类ID作为字段名,将整个商品分类对象存入Redis的Hash结构中 + redisTemplateService.setCacheMapValue(cacheKey,goodsCategory.getId().toString(),goodsCategory); + } + } +} \ No newline at end of file