spring-redis實現訂閱發布

來源:互聯網
上載者:User

匯入包:
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.0.3.RELEASE</version>
        </dependency>

生產端代碼: 介面省略

package jredis;import java.io.Serializable;import org.springframework.data.redis.core.RedisTemplate ;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;    }}
用戶端代碼:用於監聽redis
package jredis;import com.sun.tools.javac.util.List;import com.sun.xml.internal.xsom.impl.scd.Iterators;import org.apache.commons.lang.builder.ToStringBuilder;import java.io.Serializable;import java.util.Arrays;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 Iterators.Map<? , ?>) {            System.out.println(message);        } else {            System.out.println(ToStringBuilder.reflectionToString(message));            System.out.println(message);        }    }}

先啟消費端,消費端測試類別:

package jredis;import org.junit.Before;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import java.util.Date;public class TestRedisConsumer {    private MessageDelegateListenerImpl messageDelegateListener=null;    @Before    public void setUp() throws Exception {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-consumer-test.xml");        messageDelegateListener = (MessageDelegateListenerImpl) applicationContext.getBean("messageDelegateListener");    }    public static void main(String[] args) {        new ClassPathXmlApplicationContext("spring-consumer-test.xml");        System.out.println("消費者1");        while (true) { //這裡是一個死迴圈,目的就是讓進程不退出,用於接收發布的訊息            try {                Thread.sleep(3000);            } catch (InterruptedException e) {                e.printStackTrace();            }        }    }}

生產端測試類別:

package jredis;import service.weibo.impl.TencentOauthV1BackgroundServiceImpl;import service.weibo.impl.TencentOauthV1ForegroundServiceImpl;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class TestRedisProduce {    private RedisDAOImpl redisDAO=null;    @Before    public void setUp() throws Exception {        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-service-test.xml");        redisDAO = (RedisDAOImpl) applicationContext.getBean("redisDAO");        }    @Test    public void testPublishMessage() throws Exception {        String msg = "Hello, Redis!";        redisDAO.sendMessage("java", msg); //發布字串訊息       Integer[] values = new Integer[]{21341,123123,12323};        redisDAO.sendMessage("java", values);  //發布一個數組訊息    }}
生產端xml配置:

<?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="10.25.172.174" 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="jredis.RedisDAOImpl">        <property name="redisTemplate" ref="redisTemplate" />    </bean>    <bean id="listener" class="jredis.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>

消費端XML配置:

<?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="10.25.172.174" 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="jredis.RedisDAOImpl">        <property name="redisTemplate" ref="redisTemplate" />    </bean>    <bean id="serialization" class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />    <bean id="messageDelegateListener" class="jredis.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" />   <!-- 這裡配置消費端需要訂閱的頻道,可以是多個。該一例子訂閱JAVA這個頻道  -->                    </bean>                </entry>            </map>        </property>    </bean></beans>
缺點:

因為spring-redis是基於用戶端的,所以如果將用戶端進行分布式部署,部署幾個執行個體就有幾個執行個體收到相同的訊息。大多數情況我們並不需要如此。我們只需要其中的一個執行個體處理該條訊息即可。這種情況,redis有沒有提供處理辦法呢。本人還沒有找到,歡迎大家提供方案。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.