Redis發布訂閱

來源:互聯網
上載者:User

啟動訂閱和發布用戶端

在訂閱用戶端

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實現訂閱代碼:

  1. public static void main(String[] args) {  
  2.         String cmd = "subscribe share\r\n";  
  3.         SocketChannel client = null;  
  4.         try {  
  5.             SocketAddress address = new InetSocketAddress("localhost", 6379);  
  6.             client = SocketChannel.open(address);  
  7.             client.configureBlocking(false);// 設定為非同步   
  8.             ByteBuffer buffer = ByteBuffer.allocate(100);  
  9.             buffer.put(cmd.getBytes());  
  10.             buffer.clear();  
  11.             client.write(buffer);  
  12.             System.out.println("發送資料: " + new String(buffer.array()));  
  13.   
  14.             while (true) {  
  15.                 buffer.flip();  
  16.                 int i = client.read(buffer);  
  17.                 if (i > 0) {  
  18.                     byte[] b = buffer.array();  
  19.                     System.out.println("接收資料: " + new String(b));  
  20.                     break;  
  21.                 }  
  22.             }  
  23.         } catch (Exception e) {  
  24.             try {  
  25.                 client.close();  
  26.             } catch (IOException e1) {  
  27.                 e1.printStackTrace();  
  28.             }  
  29.             e.printStackTrace();  
  30.         }  
  31.     }  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.