redis如今比較長用作緩存服務器,nosql數據庫,同時它還具備實現消息的發佈訂閱的功能。本篇文章將會實現一個用redis實現發佈訂閱功能的一個demojava
首先用一個實體對象redis
package com.wtf.demo.redis; import java.io.Serializable; public class UserBean implements Serializable { private String username; private String address; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
咱們會發布這個對象,當這個對象,而且能夠更改這個對象 的屬性,發佈的代碼 以下sql
package com.wtf.demo.redis; import redis.clients.jedis.Jedis; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; public class TestPub { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub Jedis jedis = new Jedis("127.0.0.1",6379); UserBean ub = new UserBean(); ub.setUsername("張三"); ub.setAddress("上海市"); ByteArrayOutputStream os = new ByteArrayOutputStream(); ObjectOutputStream op = new ObjectOutputStream(os); op.writeObject(ub); String msg1 = os.toString("ISO-8859-1"); jedis.publish("ub", msg1); } }
發佈完成之後,咱們創建一個訂閱的類,以上發佈了ub這個對象,在訂閱類中,咱們須要JedisPubSub這個對象,而且實現裏面的相關方法。數據庫
package com.wtf.demo.redis; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPubSub; import java.io.ByteArrayInputStream; import java.io.ObjectInputStream; public class TestSub { public static void main(String[] args) { Jedis jedis = new Jedis("uat.www.nanapanda.cn",6379); JedisPubSub jedisPubSub = new JedisPubSub() { @Override public void onUnsubscribe(String channel, int subscribedChannels) { } @Override public void onSubscribe(String channel, int subscribedChannels) { } @Override public void onPUnsubscribe(String pattern, int subscribedChannels) { } @Override public void onPSubscribe(String pattern, int subscribedChannels) { } @Override public void onPMessage(String pattern, String channel, String message) { } @Override public void onMessage(String channel, String message) { try { ByteArrayInputStream bis = new ByteArrayInputStream( message.getBytes("ISO-8859-1"));//此處指定字符集將字符串編碼成字節數組,此處的字符集須要與發佈時的字符集保持一致 ObjectInputStream ois = new ObjectInputStream(bis); UserBean bean = (UserBean) ois.readObject(); System.out.println(bean.getUsername()); System.out.println(bean.getAddress()); } catch (Exception e) { e.printStackTrace(); } finally { } } }; jedis.subscribe(jedisPubSub, "ub"); } }
這樣在運行 了TestPub類之後,再運行TestSub類,將會有以下輸出數組
--------------------緩存
張三
上海市服務器
在TestPub中更改UserBean 的屬性,把地址更改成北京,在訂閱窗口將會獲得以下值nosql
------------------ide
張三this
北京