标签:
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <!--activemq  Begin-->       <dependency>           <groupId>org.springframework</groupId>           <artifactId>spring-jms</artifactId>           <version>${spring.version}</version>       </dependency>       <!-- <dependency>            <groupId>org.springframework</groupId>            <artifactId>spring-messaging</artifactId>            <version>${spring.version}</version>        </dependency>-->       <dependency>           <groupId>org.apache.activemq</groupId>           <artifactId>activemq-all</artifactId>           <version>5.14.0</version>       </dependency>       <!--activemq  End--> | 
2、activemq的配置文件:spring-jms.xml
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | <!-- 启用spring mvc 注解 -->   <context:component-scanbase-package="org.soa.test.activemq"/>   <!-- 配置JMS连接工厂 -->   <beanid="connectionFactory"class="org.apache.activemq.ActiveMQConnectionFactory">       <!--解决接收消息抛出异常:javax.jms.JMSException: Failed to build body from content. Serializable class not available to broke-->       <propertyname="trustAllPackages"value="true"/>       <!-- 是否异步发送 -->       <propertyname="useAsyncSend"value="true"/>   </bean>   <!--   Queue模式 Begin -->   <!-- 定义消息队列(Queue) -->   <beanid="queueDestination"class="org.apache.activemq.command.ActiveMQQueue">       <!-- 设置消息队列的名字 -->       <constructor-arg>           <value>defaultQueueName</value>       </constructor-arg>   </bean>   <!-- 配置JMS模板,Spring提供的JMS工具类,它发送、接收消息。(Queue) -->   <beanid="jmsTemplate"class="org.springframework.jms.core.JmsTemplate">       <propertyname="connectionFactory"ref="connectionFactory"/>       <propertyname="defaultDestination"ref="queueDestination"/>       <propertyname="pubSubDomain"value="false"/>       <!--接收超时时间-->       <!--<property name="receiveTimeout" value="10000" />-->   </bean>   <!--   Queue模式 End --> | 
三、队列发送端及测试程序
1、发送代码
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 | packageorg.soa.test.activemq.queues;importorg.soa.test.activemq.StudentInfo;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.beans.factory.annotation.Qualifier;importorg.springframework.jms.core.JmsTemplate;importorg.springframework.jms.core.MessageCreator;importorg.springframework.stereotype.Component;importjavax.jms.Destination;importjavax.jms.JMSException;importjavax.jms.Message;importjavax.jms.Session;importjava.util.List;/** * Created by JamesC on 16-9-22. */@ComponentpublicclassProduceMsg {    @Autowired    privateJmsTemplate jmsTemplate;    /**     * 向指定队列发送消息     */    publicvoidsendMessage(Destination destination, finalString msg) {        System.out.println("向队列"+ destination.toString() + "发送了消息------------"+ msg);        jmsTemplate.send(destination, newMessageCreator() {            publicMessage createMessage(Session session) throwsJMSException {                returnsession.createTextMessage(msg);            }        });    }    /**     * 向默认队列发送消息(默认队列名称在bean:queueDestination配置)     */    publicvoidsendMessage(finalString msg) {        String destination = jmsTemplate.getDefaultDestination().toString();        System.out.println("向队列"+ destination + "发送了消息------------"+ msg);        jmsTemplate.send(newMessageCreator() {            publicMessage createMessage(Session session) throwsJMSException {                returnsession.createTextMessage(msg);            }        });    }    /**     * 向默认队列发送消息     */    publicvoidsendMessageConvertAndSend(finalObject msg) {        String destination = jmsTemplate.getDefaultDestination().toString();        System.out.println("向队列"+ destination + "发送了消息------------"+ msg);        //使用内嵌的MessageConverter进行数据类型转换,包括xml(JAXB)、json(Jackson)、普通文本、字节数组        jmsTemplate.convertAndSend(destination, msg);    }    /**     * 向指定队列发送消息     */    publicvoidsendStudentInfo(Destination destination, finalStudentInfo msg) {        System.out.println("向队列"+ destination.toString() + "发送了消息------------"+ msg);        jmsTemplate.send(destination, newMessageCreator() {            publicMessage createMessage(Session session) throwsJMSException {                returnsession.createObjectMessage(msg);            }        });    }} | 
2、测试程序
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 | packageorg.soa.test.activemq.queues;importcom.alibaba.fastjson.JSON;importorg.apache.activemq.command.ActiveMQQueue;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.soa.test.activemq.StudentInfo;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.context.ApplicationContext;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;importjavax.jms.Destination;importjava.util.Date;/** * Created by JamesC on 16-9-22. */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("/spring-jms.xml")publicclassProduceMsgTest extendsAbstractJUnit4SpringContextTests {    @Autowired    protectedApplicationContext ctx;    /**     * 队列名queue1  这里使用jms配置文件中的数据     */    @Autowired    privateDestination queueDestination;    /**     * 队列消息生产者     */    @Autowired    privateProduceMsg produceMessage;    //向默认队列发消息(文本)    @Test    publicvoidproduceMsg_DefaultQueue() {        String msg = "这里是向默认队列发送的消息"+ newDate().toString();        produceMessage.sendMessage(msg);    }    //向默认队列发消息(Json字符串)    @Test    publicvoidproduceMsg_Json() {        StudentInfo info = newStudentInfo();        info.setId(1);        info.setStdName("李磊");        info.setStdNo("001");        info.setEnterDate(newDate());  //队列存放的是时间戳        String alibabaJson = JSON.toJSONString(info);        produceMessage.sendMessage(alibabaJson);    }    //向默认队列发消息(使用convertAndSend发送对象)    @Test    publicvoidproduceMsg_ConvertAndSend() {        StudentInfo info = newStudentInfo();        info.setId(1);        info.setStdName("李磊");        info.setStdNo("001");        info.setEnterDate(newDate());        produceMessage.sendMessageConvertAndSend(info);    }    //向指定队列发消息(文本)    @Test    publicvoidproduceMsg_CustomQueue() {        for(inti = 0; i < 20; i++) {            ActiveMQQueue myDestination = newActiveMQQueue("queueCustom");            produceMessage.sendMessage(myDestination, "----发送消息给queueCustom");        }    }    //向指定队列发消息(队列名称从XML读取)    @Test    publicvoidproduceMsg_XmlQueue() {        for(inti = 0; i < 20; i++) {            ActiveMQQueue destinationQueue = (ActiveMQQueue) applicationContext.getBean("queueDestination");            produceMessage.sendMessage(destinationQueue, "----send my msg to queueXml");        }    }    //向指定队列发消息(发送对象)    @Test    publicvoidproduceMsg_StudentInfo() {        StudentInfo info = newStudentInfo();        info.setId(1);        info.setStdName("李磊");        info.setStdNo("001");        info.setEnterDate(newDate());        ActiveMQQueue destination = newActiveMQQueue("StudentInfo");        produceMessage.sendStudentInfo(destination, info);    }} | 
四、队列消费端及测试程序
1、消费代码
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 | packageorg.soa.test.activemq.queues;importorg.soa.test.activemq.StudentInfo;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.jms.core.JmsTemplate;importorg.springframework.jms.support.JmsUtils;importorg.springframework.stereotype.Component;importjavax.jms.Destination;importjavax.jms.JMSException;importjavax.jms.ObjectMessage;importjavax.jms.TextMessage;/** * Created by JamesC on 16-9-22. */@ComponentpublicclassConsumeMsg {    @Autowired    privateJmsTemplate jmsTemplate;    /**     * 接受消息     */    publicString receive(Destination destination) {        TextMessage tm = (TextMessage) jmsTemplate.receive(destination);        String msg = "";        try{            msg = tm.getText();            System.out.println("从队列"+ destination.toString() + "收到了消息:\t"+ msg);        } catch(JMSException e) {            e.printStackTrace();            return"";        }        returnmsg;    }    /**     * 接受消息     */    publicStudentInfo receiveStudentInfo() {        try{            String destination = jmsTemplate.getDefaultDestination().toString();            ObjectMessage msg=(ObjectMessage)jmsTemplate.receive(destination);            return(StudentInfo)msg.getObject();        } catch(JMSException e) {            //检查性异常转换为非检查性异常            throwJmsUtils.convertJmsAccessException(e);        }    }    /**     * 接受消息     */    publicObject receiveConvertAndReceive() {        String destination = jmsTemplate.getDefaultDestination().toString();        Object msg = jmsTemplate.receiveAndConvert(destination);        returnmsg;    }} | 
2、测试程序
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | packageorg.soa.test.activemq.queues;importorg.apache.activemq.command.ActiveMQQueue;importorg.junit.Test;importorg.junit.runner.RunWith;importorg.soa.test.activemq.StudentInfo;importorg.springframework.beans.factory.annotation.Autowired;importorg.springframework.test.context.ContextConfiguration;importorg.springframework.test.context.junit4.SpringJUnit4ClassRunner;/** * Created by JamesC on 16-9-22. */@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration("/spring-jms.xml")publicclassConsumeMsgTest {    @Autowired    privateConsumeMsg consumeMsg;    //从指定队列接收消息(文本)    @Test    publicvoidreceiveMsg() {        //没有消息阻塞一段时间后会抛异常        //java.lang.NullPointerException        ActiveMQQueue destination = newActiveMQQueue("defaultQueueName");        consumeMsg.receive(destination);    }    //从指定队列接收消息(StudentInfo对象消息)    @Test    publicvoidreceiveStudentInfo() {        StudentInfo msg = consumeMsg.receiveStudentInfo();        System.out.println(msg.getStdName());    }    //从指定队列接收消息(Json对象)    @Test    publicvoidreceiveConvertAndReceive() {        StudentInfo msg =(StudentInfo) consumeMsg.receiveConvertAndReceive();        System.out.println(msg.getStdName());    }} | 
标签:
原文地址:http://www.cnblogs.com/gossip/p/5970090.html