发布订阅(pub/sub)是一种消息通信模式,主要的目的是解耦消息发布者和消息订阅者之间的耦合,这点和设计模式中的观察者模式比较相似。pub /sub不仅仅解决发布者和订阅者直接代码级别耦合也解决两者在物理部署上的耦合。redis作为一个pub/sub server,在订阅者和发布者之间起到了消息路由的功能。订阅者可以通过subscribe和psubscribe命令向redis server订阅自己感兴趣的消息类型,redis将消息类型称为通道(channel)。当发布者通过publish命令向redis server发送特定类型的消息时。订阅该消息类型的全部client都会收到此消息。这里消息的传递是多对多的。一个client可以订阅多个 channel,也可以向多个channel发送消息。
java客户端代码如下:
public class App
{
public static void main( String[] args )
{
pub();
sub();
sub01();
}
public static void pub(){
new Thread(new Runnable() {
public void run() {
Jedis edis = new Jedis("localhost", 6379) ;
edis.auth("redis") ;
while( true ){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
edis.publish("channel01", "kuoo3942" + System.currentTimeMillis()) ;
edis.publish("channel03", "cdv" + System.currentTimeMillis()) ;
}
}
}).start();
}
public static void sub(){
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Jedis edis = new Jedis("localhost", 6379) ;
edis.auth("redis") ;
MyListener l = new App().new MyListener() ;
while( true ){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("得到订阅信息");
edis.subscribe(l, "channel01");
// edis.psubscribe(jsub, "channel*");
}
}
}).start();
}
public static void sub01(){
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
Jedis edis = new Jedis("localhost", 6379) ;
edis.auth("redis") ;
MyListener l = new App().new MyListener() ;
while( true ){
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
}
System.out.println("[模式]得到订阅信息");
// edis.subscribe(jsub, "channel01");
edis.psubscribe(l, "channel*");
}
}
}).start();
}
public class MyListener extends JedisPubSub{
@Override
public void onMessage(String channel, String message) {
// TODO Auto-generated method stub
//取得订阅消息时候的处理
System.out.println(channel + ":" + message + ":onMessage");
}
@Override
public void onPMessage(String pattern, String channel, String message) {
// TODO Auto-generated method stub
System.out.println("[模式]" + pattern + ":" + channel + ":" + message + ":onPMessage");
}
@Override
public void onSubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
//初始化订阅时候的处理
System.out.println(channel + ":" + subscribedChannels + ":onSubscribe");
}
@Override
public void onUnsubscribe(String channel, int subscribedChannels) {
// TODO Auto-generated method stub
//取消订阅消息的时候的处理
System.out.println(channel + ":" + subscribedChannels + ":onUnsubscribe");
}
@Override
public void onPUnsubscribe(String pattern, int subscribedChannels) {
// TODO Auto-generated method stub
System.out.println("[模式]" + pattern + ":" + subscribedChannels + ":onPUnsubscribe");
}
@Override
public void onPSubscribe(String pattern, int subscribedChannels) {
// TODO Auto-generated method stub
System.out.println("[模式]" + pattern + ":" + subscribedChannels + ":onPSubscribe");
}
}
}