Spring Data Redis實現一個訂閱/發布系統
Redis是一個key-value的存儲系統,提供的key-value類似與Memcached而數據結構又多于memcached,而且性能優異.廣泛用于緩存,臨時存儲等.而我今天 這個例子是使用Redis實現一個訂閱/發布系統,而不是如何使用它存儲key-value的數據.
Redis是天生支持訂閱/發布的,不是我牽強附會拼湊而實現這樣的效果,如果真是這樣性能沒法保證,而且要實現訂閱/發布這樣的系統是有很多解決方案的.
下載,安裝和配置Redis
Spring一直秉承不發明輪子的,對于很多其他技術都是提供一個模板:Template,如JDBC-JdbcTemplate,JMSTemplate等,Redis他也提供RedisTemplate,有了這個RedisTemplate你可以做任何事,存取key-value,訂閱,發布等都通過這個對象實現.
實現一個RedisDAO,接口我不貼了
public class RedisDAOImpl implements RedisDAO {private RedisTemplate<String, Object> redisTemplate = null; public RedisDAOImpl() { } @Override public void sendMessage(String channel, Serializable message) { redisTemplate.convertAndSend(channel, message); } public RedisTemplate getRedisTemplate() { return redisTemplate; } public void setRedisTemplate(RedisTemplate redisTemplate) { this.redisTemplate = redisTemplate; }
}</pre>可以看到,通過這個 sendMessage方法,我可以把一條可序列化的消息發送到channel頻道,訂閱者只要訂閱了這個channel,他就會接收發布者發布的消息.
當然有了發布消息的sendMessage也得有個接收消息的Listener,用于接收訂閱到的消息.
代碼如:public class MessageDelegateListenerImpl implements MessageDelegateListener { @Override public void handleMessage(Serializable message) { //什么都不做,只輸出 if(message == null){ System.out.println("null"); } else if(message.getClass().isArray()){ System.out.println(Arrays.toString((Object[])message)); } else if(message instanceof List<?>) { System.out.println(message); } else if(message instanceof Map<? , ?>) { System.out.println(message); } else { System.out.println(ToStringBuilder.reflectionToString(message)); } } }好了,有上面的兩個類,加上Spring基本上就可以工作了.當然還得啟動Redis.
Spring Schema:<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:redis="http://www.springframework.org/schema/redis" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/redis http://www.springframework.org/schema/redis/spring-redis-1.0.xsd"> <bean id="redisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:hostName="localhost" p:port="6379" p:usePool="true"> </bean> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="redisConnectionFactory"/> <bean id="redisDAO" class="net.dredis.dao.impl.RedisDAOImpl"> <property name="redisTemplate" ref="redisTemplate" /> </bean> <bean id="listener" class="net.dredis.listener.impl.MessageDelegateListenerImpl"/> <!-- the default ConnectionFactory --> <bean id="jdkSerializer" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> <redis:listener-container> <!-- the method attribute can be skipped as the default method name is "handleMessage" --> <redis:listener ref="listener" serializer="jdkSerializer" method="handleMessage" topic="java" /> </redis:listener-container> </beans>如上面的配置, jdkSerializer是jdk默認的序列化的實現,當然還有很多其他序列化Java對象的方法,這里使用jdk默認實現.
Method屬性是配置訂閱系統接收消息的方法,默認也是"handleMessage"
topic就是訂閱的channel頻道,是有發布到java這個channel的消息才會被接收.
測試類:
public static void main(String[] args) { new ClassPathXmlApplicationContext("pubsubAppContext1.xml");; while (true) { //這里是一個死循環,目的就是讓進程不退出,用于接收發布的消息 try { System.out.println("current time: " + new Date()); Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } } }OK,啟動了訂閱系統后,我們就可以發布消息,測試類如:
@Test public void testPublishMessage() throws Exception { String msg = "Hello, Redis!"; redisDAO.sendMessage("java", msg); //發布字符串消息 RedisTestBean bean = new RedisTestBean("123456"); bean.setName("ZhenQin"); bean.setOld((byte)23); bean.setSeliry((short)4000); bean.setManbers(new String[]{"234567", "3456789"}); redisDAO.sendMessage("java", bean); //發布一個普通的javabean消息 Integer[] values = new Integer[]{21341,123123,12323}; redisDAO.sendMessage("java", values); //發布一個數組消息 }如測試,我連續發布了3條消息,都是不同的數據類型.訂閱端輸出如:current time: Fri Oct 26 20:38:31 CST 2012 [21341, 123123, 12323] java.lang.String@379faa8c[value={H,e,l,l,o,,, ,R,e,d,i,s,!},hash=1345989452] net.dredis.entity.RedisTestBean@7dee05dc[uid=123456,name=ZhenQin,seliry=4000,old=23,manbers={234567,3456789}] current time: Fri Oct 26 20:38:34 CST 2012 current time: Fri Oct 26 20:38:37 CST 2012OK他接收到了這3條消息,而且和預期一樣.
對于Spring還有傳統風格的配置方式,實現的功能和前面一模一樣.
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <bean id="jedisConnectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory" p:hostName="localhost" p:port="6379" p:usePool="true"> </bean> <!-- redis template definition --> <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" p:connectionFactory-ref="jedisConnectionFactory"/> <bean id="redisDAO" class="net.dredis.dao.impl.RedisDAOImpl"> <property name="redisTemplate" ref="redisTemplate" /> </bean> <bean id="serialization" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" /> <bean id="messageDelegateListener" class="net.dredis.listener.impl.MessageDelegateListenerImpl" /> <bean id="messageListener" class="org.springframework.data.redis.listener.adapter.MessageListenerAdapter"> <property name="delegate" ref="messageDelegateListener" /> <property name="serializer" ref="serialization" /> </bean> <bean id="redisContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer"> <property name="connectionFactory" ref="jedisConnectionFactory"/> <property name="messageListeners"> <!-- map of listeners and their associated topics (channels or/and patterns) --> <map> <entry key-ref="messageListener"> <bean class="org.springframework.data.redis.listener.ChannelTopic"> <constructor-arg value="java" /> </bean> </entry> </map> </property> </bean> </beans>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!