Redis key 过期通知

1.开启过期通知配置 

默认 notify-keyspace-events "" 修改为:notify-keyspace-events Ex
只有当key被删除时候 才会通知 并不是在key过期后就马上删除的

2.增加监听类

public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {

  public RedisKeyExpirationListener(
      RedisMessageListenerContainer listenerContainer) {
    super(listenerContainer);
  }

  @Override
  public void onMessage(Message message, byte[] pattern) {
    String expireKey = message.toString();
    System.out.println("过期key:" + expireKey);
  }
}

@Configuration
public class RedisListenerConfig {

  @Autowired
  private RedisConnectionFactory redisConnectionFactory;

  @Bean
  public RedisMessageListenerContainer container() {
    RedisMessageListenerContainer container = new RedisMessageListenerContainer();
    container.setConnectionFactory(redisConnectionFactory);
    return container;
  }

  @Bean
  public RedisKeyExpirationListener keyExpirationListener() {
    return new RedisKeyExpirationListener(this.container());
  }
}

3.执行命令

set name zhangsan
expire name 2    //设置2秒过期

注:只能获取到失效的key,无法获取value 

//通知效果如图 RedisKeyExpirationListener.onmessage

Redis key 过期通知_第1张图片

你可能感兴趣的:(Redis,java,前端,开发语言)