redisパブリッシュサブスクリプションとカスタムコマンドの組合せ
1878 ワード
サブスクリプションとパブリッシュクライアントの起動
クライアントの購読
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実装サブスクリプションコードを添付:
2:Redisはカスタムコマンドの組み合わせもサポートしており、MULTIとEXECを通じて、いくつかのコマンドを組み合わせて実行しています.
クライアントの購読
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
";
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"