java Redis消息队列

maven依赖:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-redis</artifactId>
    <version>1.5.2.RELEASE</version>
</dependency>

两个包的版本可能会引起冲突(之前spring-data-redis版本是1.0.2),导致TOMCAT启动后报错。经过几次尝试,用这两个版本不会冲突,要注意。

 -------------------------------------------------------------------------------------------------------------------------------

配置文件:

<?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.2.xsd
      http://www.springframework.org/schema/context  http://www.springframework.org/schema/context/spring-context-3.2.xsd"
      default-lazy-init="true">

   <description>Jedis Configuration</description>

   <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
      <property name="maxIdle" value="50" /> <!-- 最大能够保持idel状态的对象数  -->
      <property name="maxTotal" value="1000" /> <!-- 最大分配的对象数 -->
      <property name="testOnBorrow" value="true" /> <!-- 当调用borrow Object方法时,是否进行有效性检查 -->
   </bean>
   
    <!-- spring date redis 配置 -->
<bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory"  
   p:host-name="192.168.0.215" p:port="6379" p:password="123456"  p:pool-config-ref="jedisPoolConfig"/>  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">  
        <property name="connectionFactory"   ref="connectionFactory" />  
        <property name="keySerializer">
          <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
         </property>
         <property name="valueSerializer">
             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />
         </property>
    </bean> 
    
    <bean id="redisMessageListener" class="com.yooeee.web.redis.RedisMessageListener">  
        <property name="redisTemplate" ref="redisTemplate"/>  
    </bean> 
    
    <bean id="topicContainer" class="org.springframework.data.redis.listener.RedisMessageListenerContainer" destroy-method="destroy">  
        <property name="connectionFactory" ref="connectionFactory"/>  
        <property name="taskExecutor">
            <bean class="org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler">  
                <property name="poolSize" value="3"></property>  
            </bean>  
        </property>  
        <property name="messageListeners">  
            <map>  
                <entry key-ref="redisMessageListener">  
                    <bean class="org.springframework.data.redis.listener.ChannelTopic">  
                        <constructor-arg value="order:topic"/>  
                    </bean>  
                </entry>  
            </map>  
        </property>  
    </bean>
   
   <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
      <constructor-arg index="0" ref="jedisPoolConfig" />
      <constructor-arg index="1" value="${redis.host}" />
      <constructor-arg index="2" value="${redis.port}" type="int" />
      <constructor-arg index="3" value="${redis.timeout}" type="int" />
      <constructor-arg index="4" value="${redis.requirepass}"/>
   </bean>
   
   <!--Redis service -这个是一个redis工具类,可以包含一些redis基本的操作。这里主要用的是publish方法->
   <bean id="redisService" class="com.yooeee.pj.business.service.cache.RedisService">
      <constructor-arg name="jedisPool" ref="jedisPool"/>
   </bean>
   
</beans>

----------------------------------------------------------------------------------------------------------------------------------

发送消息:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring-context-jedis.xml" })
public class RedisTopicTest {

   @Autowired
   private RedisTemplate<Serializable, Serializable> redisTemplate;


   @Test
   public void pub() {
      // 这里因为业务需要定义成map,一般可以定义为String,按照实际情况变通。orderMap.put("4499605762317320-9683121", "pRwImXJf");
      String channel = "order:topic";
      redisTemplate.convertAndSend(channel, orderMap);
      System.out.println("pub success...");
   }

}

 ---------------------------------------------------------------------------------------------------------------------------------

接收消息:

public class RedisMessageListener implements MessageListener {
   private static final Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);
   private RedisTemplate<Serializable, Serializable> redisTemplate;

   public void setRedisTemplate(RedisTemplate<Serializable, Serializable> redisTemplate) {
      this.redisTemplate = redisTemplate;
   }

   @Overridepublic void onMessage(Message message, byte[] pattern) {
      // logger.warn("接收到订单提醒,开始提醒商户。");
      System.out.println("接收到订单提醒,开始提醒商户。");
      byte[] body = message.getBody();
      byte[] channel = message.getChannel();


      final Map<String,String> msgContent = (Map<String,String>) redisTemplate.getValueSerializer().deserialize(body);
      String topic = (String) redisTemplate.getStringSerializer().deserialize(channel);
      logger.warn("msgContent is : {},topic is : {}",msgContent,topic);
      System.out.println("收到消息为:" + msgContent );
   }
}

猜你喜欢

转载自liyang678.iteye.com/blog/2395886