定期删除(过期)

定时删除(过期)

  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!!!");
                }
    }
}
posted @ 2021-06-30 16:09  咱那飘逸的长发  阅读(54)  评论(0)    收藏  举报