redis使用基础

redis springboot常用命令

1
2
3
4
5
6
7
8
9
10
11
@Autowired
StringRedisTemplate redisTemplate;
//----------------------------------------------------------------------
//给key设置value
redisTemplate.opsForValue().set("key","value"); //SET key "value"
//取key的value
redisTemplate.opsForValue().get("key");//GET key
//设置key在new Date()过期
redisTemplate.expireAt("key",new Date()); //EXPIREAT key timestamp
redisTemplate.getExpire("testttl"); //返回过期时间

reids设置过期key监听事件

  1. 在redis命令行执行config set notify-keyspace-events Ex

  2. 在java代码添加监听事件

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    import org.springframework.data.redis.connection.Message;
    import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
    import org.springframework.data.redis.listener.RedisMessageListenerContainer;
    import org.springframework.stereotype.Component;

    @Component
    public class RedisKeyExpirationListener extends KeyExpirationEventMessageListener {
    public RedisKeyExpirationListener(RedisMessageListenerContainer listenerContainer) {
    super(listenerContainer);
    }
    @Override
    public void onMessage(Message message, byte[] pattern) {
    // 处理接收到的消息
    String channel = new String(message.getChannel());
    String body = new String(message.getBody());
    System.out.println("接收到来自通道 " + channel + " 的消息:" + body);
    }
    }
  3. 等待过期,就会打印如下内容

    1
    2
    3
    接收到来自通道 __keyevent@1__:expired 的消息:GATE:DEVICE:HEART:1725361717475983361
    接收到来自通道 __keyevent@1__:expired 的消息:GATE:DEVICE:HEART:1728969231125295105
    接收到来自通道 __keyevent@1__:expired 的消息:GATE:DEVICE:HEART:1726505401086349313

注意

reids重新设值会覆盖expireAt过期时间的设置

参考

记一次Redis_Key值无效监听失效的失败历程