標籤:jedis io redis
redis支援發布/訂閱的訊息佇列機制,jedis提供了java訪問redis的用戶端,本文將描述如何用jedis實現簡單的訊息佇列,並傳輸對象。
redis支援發布、訂閱的功能,基本的命令有publish、subscribe等。在jedis中,有對應的java方法,並且只能發布字串訊息。為了傳輸對象,需要將對象進行序列化,並封裝成字串進行處理。將對象序列化後,只能成為位元組流,如何封裝成字串是一個痛點,具體可參考下面的代碼。
實現三個類,一個對應publish、一個對應subscribe、一個對應要傳遞的對象實體類。
實體類:
public class Bean implements Serializable {//需要實現序列化介面private String name;public String getName() {return name;}public void setName(String name) {this.name = name;}}
publish類:
public class TestPub {public static void main(String[] args) {Jedis jedis = new Jedis("127.0.0.1");try {Bean bean = new Bean();bean.setName("test"); //使用ObjectOutputStream和ByteArrayOutputStream將對象轉換成位元組流ByteArrayOutputStream baos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(baos);oos.writeObject(bean);String msg1 = baos.toString("ISO-8859-1");//指定字元集將位元組流解碼成字串,否則在訂閱時,轉換會有問題。// msg1 = URLEncoder.encode(msg1, "UTF-8");jedis.publish("foo", msg1);} catch (Exception e) {}}}
subscribe類:
public class TestSub {public static void main(String[] args) {Jedis jedis = new Jedis("127.0.0.1");JedisPubSub jedisPubSub = new JedisPubSub() {@Overridepublic void onUnsubscribe(String channel, int subscribedChannels) {}@Overridepublic void onSubscribe(String channel, int subscribedChannels) {}@Overridepublic void onPUnsubscribe(String pattern, int subscribedChannels) {}@Overridepublic void onPSubscribe(String pattern, int subscribedChannels) {}@Overridepublic void onPMessage(String pattern, String channel,String message) {}@Overridepublic void onMessage(String channel, String message) {try {ByteArrayInputStream bis = new ByteArrayInputStream(message.getBytes("ISO-8859-1"));//此處指定字元集將字串編碼成位元組數組,此處的字元集需要與發布時的字元集保持一致ObjectInputStream ois = new ObjectInputStream(bis);Bean bean = (Bean) ois.readObject();System.out.println(bean.getName());} catch (Exception e) {e.printStackTrace();} finally {}}};jedis.subscribe(jedisPubSub, "foo");}}
jedis實現redis的訊息佇列、發布對象訊息、位元組數組與字串相互轉換