Redis的发布订阅
一、Message类
import java.io.Serializable;
public class Message implements Serializable{
private static final long serialVersionUID = 7792729L;
private int id;
private String content;
public Message(int id, String content) {
this.id = id;
this.content = content;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
}
二、消息订阅类
import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import redis.clients.jedis.BinaryJedisPubSub;
import redis.clients.jedis.Jedis;
public class Subscribe extends BinaryJedisPubSub {
/**byte[]转对象
* @param bytes
* @return
* @throws Exception
*/
public static Object bytesToObject(byte[] bytes) throws Exception{
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream sIn = new ObjectInputStream(in);
return sIn.readObject();
}
//subscribe是一个阻塞的方法,在取消订阅该频道前,会一直阻塞在这,只有当取消了订阅才会执行下面的other code,参考上面代码,我在onMessage里面收到消息后,调用了this.unsubscribe(); 来取消订阅,这样才会执行后面的other code
@Override
public void onMessage(byte[] channel, byte[] message) {
try {
Message m = (Message)bytesToObject(message);
System.out.println("id="+m.getId()+",content="+m.getContent());
this.unsubscribe();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
Subscribe su = new Subscribe();
byte[] channel = "channel".getBytes();
@SuppressWarnings("resource")
Jedis jedis = new Jedis("10.108.169.6",6379);
jedis.subscribe(su, channel);
System.out.println("exit");
jedis.disconnect();
}
}
三、消息发布类
public class PublishDemo {
/**对象转byte[]
* @param obj
* @return
* @throws IOException
*/
public static byte[] objectToBytes(Object obj) throws Exception{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
byte[] bytes = bo.toByteArray();
bo.close();
oo.close();
return bytes;
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
byte[] channel = "channel".getBytes();
Message message = new Message(1,"www1234");
@SuppressWarnings("resource")
Jedis jedis = new Jedis("10.108.169.6",6379);
//清空数据库中的数据,若不删除该数据会一直存在内存中,其他的连接也能获得该数据
jedis.flushDB();
jedis.publish(channel, objectToBytes(message));
jedis.disconnect();
}
}