1.运行Java代码
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class PubSubTest {
public static void main(String[] args) {
String cmd = "subscribe news.share news.blog"+"\r\n";
try {
Socket socket = new Socket("localhost",6379);
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
out.write(cmd.getBytes()); //发送订阅命令
byte[] buffer = new byte[1024];
while (true) {
int readCount = in.read(buffer);
System.out.write(buffer, 0, readCount);
System.out.println("--------------------------------------");
}
} catch (Exception e) {
}
}
}
2.打开Redis一个客户端,输入如下命令
psubscribe news.*
127.0.0.1:6379> psubscribe news.*
3.在打开一个Redis客户端,开始发布订阅,
127.0.0.1:6379> publish news.share "hello"
4.之后会在java控制台输出“hello”和Redis第一个客户端也会输出“hello”