在 redis.conf 中,到场一条设置
notify-keyspace-events Ex
运行代码如下
package com.rjzheng.delay5;import redis.clients.jedis.JedisPool;import redis.clients.jedis.JedisPubSub;public class RedisTest { private static final String ADDR = "127.0.0.1"; private static final int PORT = 6379; private static JedisPool jedis = new JedisPool(ADDR, PORT); private static RedisSub sub = new RedisSub(); public static void init() { new Thread(new Runnable() { public void run() { jedis.getResource().subscribe(sub, "__keyevent@0__:expired"); } }).start(); } public static void main(String[] args) throws InterruptedException { init(); for (int i = 0; i < 10; i++) { String orderId = "OID000000" + i; jedis.getResource().setex(orderId, 3, orderId); System.out.println(System.currentTimeMillis() + "ms:" + orderId + "订单天生"); } } static class RedisSub extends JedisPubSub { @Override public void onMessage(String channel, String message) { System.out.println(System.currentTimeMillis() + "ms:" + message + "订单取消"); } }}输出如下
可以显着看到 3 秒事后,订单取消了
ps:redis 的 pub/sub 机制存在一个硬伤,官网内容如下
原:Because Redis Pub/Sub is fire and forget currently there is no way to use this feature if your application demands reliable notification of events, that is, if your Pub/Sub client disconnects, and reconnects later, all the events delivered during the time the client was disconnected are lost.
翻: Redis 的发布/订阅现在是即发即弃(fire and forget)模式的,因此无法实现变乱的可靠关照。也就是说,假如发布/订阅的客户端断链之后又重连,则在客户端断链期间的全部变乱都丢失了。因此,方案二不是太保举。固然,假如你对可靠性要求不高,可以使用。
长处