天天看點

redis釋出訂閱和自定義的指令組合

啟動訂閱和釋出用戶端

在訂閱用戶端

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();
		}
	}
           

2:Redis還支援自定義的指令組合,通過MULTI和EXEC,将幾個指令組合起來執行

redis 127.0.0.1:6379> SET counter 0
OK
redis 127.0.0.1:6379> MULTI
OK
redis 127.0.0.1:6379> INCR counter
QUEUED
redis 127.0.0.1:6379> INCR counter
QUEUED
redis 127.0.0.1:6379> INCR counter
QUEUED
redis 127.0.0.1:6379> EXEC
1) (integer) 1
2) (integer) 2
3) (integer) 3
redis 127.0.0.1:6379> GET counter
"3"