啟動訂閱和發布用戶端
在訂閱用戶端
redis 127.0.0.1:6379> PSUBSCRIBE share
Reading messages... (press Ctrl-C to quit)
1) "psubscribe"
2) "share"
3) (integer) 1
表示客訂閱share通道
其中1表示該用戶端中連的接訂閱通道數為1
在發布用戶端,為該通道發布一個訊息
redis 127.0.0.1:6379> publish share "share"
(integer) 1
其中1表示有1個串連接收到這個訊息
訂閱用戶端顯示:
1) "pmessage"//訊息類型
2) "share"//我訂閱的通道名
3) "share"//我接收的通道名
4) "share"//訊息內容
ps:另附java實現訂閱代碼:
- public static void main(String[] args) {
- String cmd = "subscribe share\r\n";
- SocketChannel client = null;
- try {
- SocketAddress address = new InetSocketAddress("localhost", 6379);
- client = SocketChannel.open(address);
- client.configureBlocking(false);// 設定為非同步
- ByteBuffer buffer = ByteBuffer.allocate(100);
- buffer.put(cmd.getBytes());
- buffer.clear();
- client.write(buffer);
- System.out.println("發送資料: " + new String(buffer.array()));
-
- while (true) {
- buffer.flip();
- int i = client.read(buffer);
- if (i > 0) {
- byte[] b = buffer.array();
- System.out.println("接收資料: " + new String(b));
- break;
- }
- }
- } catch (Exception e) {
- try {
- client.close();
- } catch (IOException e1) {
- e1.printStackTrace();
- }
- e.printStackTrace();
- }
- }