activemq中spring接受消息

参考:西北小强的博客,网址:http://yuxisanren.iteye.com/blog/1918024

在dev-core.xml文件中添加

 <Factory class="SpringBeanFactory" name="springFactory" config="spring-config.xml" />


对于spring-config.xml文件,起对应的如下:

 
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:amq="http://activemq.apache.org/schema/core"
    xmlns:jms="http://www.springframework.org/schema/jms"
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.0.xsd
        http://www.springframework.org/schema/jms
        http://www.springframework.org/schema/jms/spring-jms-4.0.xsd
        http://activemq.apache.org/schema/core
        http://activemq.apache.org/schema/core/activemq-core-5.8.0.xsd">
    
    <!-- Spring提供的JMS工具类,它可以进行消息发送、接收等 -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <!-- 这个connectionFactory对应的是我们定义的Spring提供的那个ConnectionFactory对象 -->
        <property name="connectionFactory" ref="connectionFactory"/>
    </bean>

    <!-- 真正可以产生Connection的ConnectionFactory,由对应的 JMS服务厂商提供-->
    
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"/>
    </bean>
     
    <!-- Spring用于管理真正的ConnectionFactory的ConnectionFactory -->
    <bean id="connectionFactory" class="org.springframework.jms.connection.SingleConnectionFactory">
        <!-- 目标ConnectionFactory对应真实的可以产生JMS Connection的ConnectionFactory -->
        <property name="targetConnectionFactory" ref="targetConnectionFactory"/>
    </bean>
    
     <!--这个是队列目的地-->
    <bean id="topicDestination" class="org.apache.activemq.command.ActiveMQTopic">
        <constructor-arg>
            <value>topicName</value>
        </constructor-arg>
    </bean>
    
    <!-- 消息监听器 -->
    <bean id="consumerMessageListener" class="cn.cmri.dev.ConsumerMessageListener"/>
    
    <!-- 消息监听容器 -->
    <bean id="jmsContainer"   class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory"  ref="connectionFactory" />
        <property name="destination" ref="topicDestination" />
        <property name="messageListener" ref="consumerMessageListener" />
    </bean>
    
</beans> 


对于ConsumerMessageListener.java如下

@Component
public class ConsumerMessageListener implements MessageListener{

    @Override
    public void onMessage(Message message) {
        // TODO Auto-generated method stub
        //这里我们知道生产者发送的就是一个纯文本消息,所以这里可以直接进行强制转换,或者直接把onMessage方法的参数改成Message的子类TextMessage
        TextMessage textMsg = (TextMessage) message;
        System.out.println("接收到一个纯文本消息。");
        try {
            System.out.println("消息内容是:" + textMsg.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }    
    
}


对于消息的接受:

  1. public void onMessage(Message message) {  
  2.         /**  
  3.          * 接受文本类型的消息   
  4.          */  
  5.         if(message instanceof TextMessage){ //instanceof 测试它所指向的对象是否是TextMessage类  
  6.             TextMessage text = (TextMessage) message;  
  7.             try {  
  8.                 System.out.println("发送的文本消息内容为:"+text.getText()); //接受文本消息   
  9.             } catch (JMSException e) {  
  10.                 e.printStackTrace();  
  11.             }  
  12.         }  
  13.         /**  
  14.          * 接受Map类型的消息  
  15.          */  
  16.         if(message instanceof MapMessage){  
  17.             MapMessage map = (MapMessage) message;  
  18.             try {  
  19.                 System.out.println("姓名:"+map.getString("name"));  
  20.                 System.out.println("是否是英雄:"+map.getBoolean("IsHero"));  
  21.                 System.out.println("年龄:"+map.getInt("age"));  
  22.             } catch (JMSException e) {  
  23.                 e.printStackTrace();  
  24.             }  
  25.         }  
  26.         if(message instanceof ObjectMessage){  
  27.             ObjectMessage objMsg = (ObjectMessage) message;  
  28.             try {  
  29.                 Person person=(Person) objMsg.getObject();  
  30.                 System.out.println("用户名:"+person.getName()+"年龄:"+person.getAge()+"地址:"+person.getAddress());  
  31.             } catch (JMSException e) {  
  32.                 e.printStackTrace();  
  33.             }  
  34.         }  
  35.     } 


其他sendTopic代码如下:

package cn.cmri.activeMQ;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import net.sf.json.JSONArray;

import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;

import cn.cmri.conf.Common;

public class SendMessage{

    public static void sendTopicMessage(JSONArray msgM) {
        // ConnectionFactory:连接工厂,JMS用它创建连接
        ConnectionFactory connectionFactory;
        // Connection:JMS客户端到JMS Provider的连接
        Connection connection = null;
        // Session:一个发送或接收消息的线程
        Session session;
        // Destination:消息的目的地;消息发送给谁.
        Destination destination;
        // MessageProducer:消息发送者
        MessageProducer producer;
        // TextMessage message;
        // 构造ConnectionFactory实例对象,此处采用ActiveMq的实现jar
        connectionFactory = new ActiveMQConnectionFactory(
        ActiveMQConnection.DEFAULT_USER,
        //ActiveMQConnection.DEFAULT_PASSWORD,"tcp://127.0.0.1:61616");
        ActiveMQConnection.DEFAULT_PASSWORD,Common.ActiveMQConnection);
        try {
            // 构造从工厂得到连接对象
            connection = connectionFactory.createConnection();
            // 启动
            connection.start();
            // 获取操作连接
            session = connection.createSession(true, Session.AUTO_ACKNOWLEDGE);
            // 获取session注意参数值FirstTopic是一个服务器的topic(与queue消息的发送相比,这里是唯一的不同)
            destination = session.createTopic(Common.sendMessageName);
            // 得到消息生成者【发送者】
            producer = session.createProducer(destination);
            // 设置不持久化,此处学习,实际根据项目决定
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
            // 构造消息,此处写死,项目就是参数,或者方法获取
            sendMessageMethod(session, producer,msgM);
            session.commit();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != connection)
                    connection.close();
            } catch (Throwable ignore) {
                
            }
        }
    }
    
    public static void sendMessageMethod(Session session, MessageProducer producer,JSONArray msgM)
            throws Exception {
        
            //TextMessage message = session.createTextMessage("ActiveMq sendTopic message " + i);
            // 发送消息到目的地方
            //System.out.println("sendMessage :" + "ActiveMq sendMessage" + i);
            ObjectMessage message=session.createObjectMessage( msgM);
            
            producer.send(message);
    }
    public static void main(String[] args) {

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值