发布/订阅 Pub/Sub
发布订阅 的特点是订阅者(listener)负责订阅频道(channel),发送者(publisher)负责向频道发送二进制字符串消息(binary string message)。每当有消息被发送至给定频道时,频道的所有订阅者都会收到消息。(订阅者可以订阅多个频道,发送者可以在任何频道发送消息)
发布订阅 依赖于即时消息的广播(即,如果没有听,则错过一条消息),没有对消息持久化。
在org.springframework.data.redis.connection和org.springframework.data.redis.listener软件包提供了对Redis的消息的核心功能
1、发布Pub:
发布消息,可以使用底层的 RedisConnection ,也可使用高级的 RedisTemplate。RedisConnection需要原始数据(字节数组),RedisTemplate可以让任意对象作为消息发布,如:
// send message through connection RedisConnection con = ... byte[] msg = ... byte[] channel = ... con.publish(msg, channel); // send message through RedisTemplate RedisTemplate template = ... template.convertAndSend("hello!", "world");
RedisTemplate 的 converAndSend 还是调用的 RedisConnection 的publish方法:
@Override public void convertAndSend(String channel, Object message) { Assert.hasText(channel, "a non-empty channel is required"); byte[] rawChannel = rawString(channel); byte[] rawMessage = rawValue(message); execute(connection -> { connection.publish(rawChannel, rawMessage); return null; }, true); }