消息订阅者
@Controller
public class RedisSubscribe extends JedisPubSub{
@Override
public void onMessage(String channel, String message) {
SimpleDateFormat df = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
System.out.println("订阅者:订阅频道["+channel+"],收到消息["+message+"],时间:"+df.format(new Date()));
}
@RequestMapping("subscribe")
public void subscribe(){
String host = "localhost";
int port = 6379;
Jedis redis = null;
redis = new Jedis(host,port);
redis.auth("123456");
System.out.println("启动subScribe订阅者");
RedisSubscribe redisSubscribe = new RedisSubscribe();
redis.subscribe(redisSubscribe,"suwei");
}
}`
这里是一个指定频道的订阅者;订阅者要继承JedisPubSub,重写onMessage方法获取消息;
订阅方法:Jedis.subscribe(当前订阅者,频道名)
@Controller
public class RedisPSubscribe extends JedisPubSub{
@Override
public void onMessage(String channel, String message) {
SimpleDateFormat df = new SimpleDateFormat("yyyy MM dd HH:mm:ss");
System.out.println("订阅者:订阅频道["+channel+"],收到消息["+message+"],时间:"+df.format(new Date()));
}
@RequestMapping("pSubScribe")
public void pSubScribe(){
Jedis redis = new Jedis("localhost",6379);
redis.auth("123456");
RedisPSubscribe redisPSubscribe = new RedisPSubscribe();
System.out.println("启动psubScribe订阅者");
redis.psubscribe(redisPSubscribe,"S*");
}
}
这里是一个通配符订阅者同样也要继承JedisPubSub,重写onMessage方法获取消息;
订阅方法:Jedis.psubscribe(当前订阅者,通配符频道(我这里取的是s开头的频道,不区分大小写))
@Controller
public class RedisPublish {
@RequestMapping("publish")
public void publish(){
String host = "localhost";
int port = 6379;
Jedis redis = null;
redis = new Jedis(host,port);
redis.auth("123456");
redis.publish("suwei","发布消息");
}
}
这里是一个发布者,发布方法Jedis.publish(频道名,消息);
发布者相当于客户端,消息订阅者是服务端