Spring Data Redis實現一個訂閱/發佈系統

Redis是一個key-value的存儲系統,提供的key-value相似與Memcached而數據結構又多於memcached,並且性能優異.普遍用於緩存,臨時存儲等.而我今天 這個例子是使用Redis實現一個訂閱/發佈系統,而不是如何使用它存儲key-value的數據.

Redis是天生支持訂閱/發佈的,不是我牽強附會拼湊而實現這樣的效果,若是真是這樣性能無法保證,並且要實現訂閱/發佈這樣的系統是有不少解決方案的.

下載,安裝和配置Redis,見: http://my.oschina.net/u/729474/blog/79128 和http://www.php100.com/html/webkaifa/PHP/PHPyingyong/2011/0406/7873.html php

Spring一直秉承不發明輪子的,對於不少其餘技術都是提供一個模板:Template,如JDBC-JdbcTemplate,JMSTemplate等,Redis他也提供RedisTemplate,有了這個RedisTemplate你能夠作任何事,存取key-value,訂閱,發佈等都經過這個對象實現. html

實現一個RedisDAO,接口我不貼了 java

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;
    }
}
能夠看到,經過這個 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("Redis");
        bean.setOld((byte)2);
        bean.setSeliry((short)40);
        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=Redis,seliry=40,old=2,manbers={234567,3456789}]
current time: Fri Oct 26 20:38:34 CST 2012
current time: Fri Oct 26 20:38:37 CST 2012
OK他接收到了這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>
相關文章
相關標籤/搜索