Springboot使用Quartz定时任务删除redis中的物品
一. 导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-quartz</artifactId>
</dependency>
二. 模型数据
package io.coderyeah.ymcc.dto;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
/**
* @author lqs
* @date 2022/11/6 10:10
*/
@Data
public class GoodsDTO {
// 主键
private Long id;
// 商品数量
private Integer num;
// 商品名称
private String name;
// 用户
private Long userId;
// 当前时间
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Long time = new Date().getTime();
}
三. 自定义redis模板配置
package io.coderyeah.ymcc.config;
import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.Resource;
//缓存的配置
@Configuration
public class RedisConfig {
@Resource
private RedisConnectionFactory factory;
//使用JSON进行序列化
@Bean
public RedisTemplate<Object, Object> redisTemplate() {
RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
//JSON格式序列化
GenericFastJsonRedisSerializer serializer = new GenericFastJsonRedisSerializer();
//key的序列化
redisTemplate.setKeySerializer(new StringRedisSerializer());
//value的序列化
redisTemplate.setValueSerializer(serializer);
//hash结构key的序列化
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
//hash结构value的序列化
redisTemplate.setHashValueSerializer(serializer);
return redisTemplate;
}
}
yml配置
sue:
spring:
quartz:
cron: "*/10 * * * * ?" # [秒] [分] [小时] [日] [月] [周] [年] 每隔5秒执行一次
四. Quartz配置
-
定时任务代码功能
package io.coderyeah.ymcc.quartz; import com.alibaba.fastjson2.JSON; import io.coderyeah.ymcc.dto.GoodsDTO; import lombok.extern.slf4j.Slf4j; import org.quartz.JobExecutionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.scheduling.quartz.QuartzJobBean; import java.util.List; import java.util.Set; /** * @author lqs * @date 2022/11/6 11:05 */ @Slf4j public class QuartzCartJob extends QuartzJobBean { @Autowired private RedisTemplate<Object, Object> redisTemplate; @Override protected void executeInternal(JobExecutionContext context) { // 每隔10秒执行一次 // 获取redis中所有的商品 Set<Object> keys = redisTemplate.keys(("cache:goods:*"));// 获取所有key assert keys != null; keys.forEach(key -> { // 遍历每一个key 获取当前key的所有值 List<Object> values = redisTemplate.opsForHash().values(key); List<GoodsDTO> goodsDTOS = JSON.parseArray(JSON.toJSONString(values), GoodsDTO.class); // 遍历货品 goodsDTOS.forEach(goodsDTO -> { // 判断存储时间是否大于一分钟 if (System.currentTimeMillis() - goodsDTO.getTime() > 1000 * 60) { // 删除此物品 redisTemplate.opsForHash().delete(key, goodsDTO.getId().toString()); log.info("定时删除成功"); } }); }); System.out.println(keys); String userName = (String) context.getJobDetail().getJobDataMap().get("userName"); System.out.println("userName:" + userName); } }
-
配置执行
package io.coderyeah.ymcc.quartz; import org.quartz.*; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * @author lqs * @date 2022/11/6 11:07 */ @Configuration public class QuartzConfig { @Value("${sue.spring.quartz.cron}") private String cron; /** * 创建定时任务 */ @Bean public JobDetail quartzCartJobDetail() { JobDetail jobDetail = JobBuilder.newJob(QuartzCartJob.class) .withIdentity("quartzCartJobDetail", "QUARTZ_CART") .usingJobData("userName", "coderyeah") .storeDurably() .build(); return jobDetail; } /** * 创建触发器 */ @Bean public Trigger quartzCartJobTrigger() { //每隔5秒执行一次 CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule(cron); //创建触发器 Trigger trigger = TriggerBuilder.newTrigger() .forJob(quartzCartJobDetail()) .withIdentity("quartzCartJobTrigger", "QUARTZ_CART_JOB_TRIGGER") .withSchedule(cronScheduleBuilder) .build(); return trigger; } }