Springboot使用Quartz定时任务删除redis中的物品


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配置

  1. 定时任务代码功能

    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);
        }
    }
    
  2. 配置执行

    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;
        }
    }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值