定时删除(过期)

定时删除(过期)

  1. 动态参数定时器,可自定义cron,实现定时执行job。(使用体验:差)
    可通过定时器每隔一段时间从数据库表查“过期时间”字段,跟当前时间对比,如果相同就删除
    在这里插入图片描述

  2. threadlocal(使用体验:极差)
    容易使用不当导致内存泄漏。

  3. @schedule(使用体验:一般)

    @schedule注解注释的方法无法携带参数,限制太多
    4.redis过期通知(强烈推荐!)

给key加上过期时间,通过监听过期键去实现service功能,类似于中间件

1、创建配置类RedisListenerConfig

// An highlighted block
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;

@Configuration
public class RedisListenerConfig {

    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        return container;
    }
}

2、创建监听类RedisKeyExpirationListener

// An highlighted block
import cn.hutool.core.util.StrUtil;
import com.leayun.cn.constant.RedisPrefixConstant;
import com.leayun.cn.service.FlightService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

@Component
public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

     @Autowired
     RedisTemplate redisTemplate;
     @Autowired
     FlightService flightService;

    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
        super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {

        // 由于通知收到的是redis key,value已经过期,无法收到,所以需要在key上标记业务数据。
        // 获取到失效的 key,进行取消订单业务处理
           RedisSerializer<String> serializer = redisTemplate.getValueSerializer();
                // 获取到失效的 key
                String orderNo = message.toString();
                //hutool的StrUtil类的startWith方法,判断前缀是否和你redis存的key相同
                if (StrUtil.startWith(orderNo,RedisPrefixConstant.FLIGHT_EXPIRATION_DATE)) {
                //由于我的key是固定字段:id,中间有:分开,所以需要根据:切割字段
                    String[] data = orderNo.split(":");
                    //获取切割后的第二个字段id,实现删除功能
                    flightService.deleteById(Long.valueOf(data[1]));
                    System.out.println("delete success!!!");
                }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值