一、本文章包含的内容
1、列举了ActiveMQ中通过Queue方式发送、消费队列的代码(普通文本、json/xml字符串、对象数据)
2、spring+activemq方式
 
二、配置信息
1、activemq的pom.xml信息
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-scan base-package="org.soa.test.activemq"/>
 
   <!-- 配置JMS连接工厂 -->
   <bean id="connectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
       <property name="brokerURL" value="failover:(tcp://192.168.146.129:61616)" />
       <!--解决接收消息抛出异常:javax.jms.JMSException: Failed to build body from content. Serializable class not available to broke-->
       <property name="trustAllPackages" value="true"/>
       <!-- 是否异步发送 -->
       <property name="useAsyncSend" value="true" />
   </bean>
 
   <!--   Queue模式 Begin -->
 
   <!-- 定义消息队列(Queue) -->
   <bean id="queueDestination" class="org.apache.activemq.command.ActiveMQQueue">
       <!-- 设置消息队列的名字 -->
       <constructor-arg>
           <value>defaultQueueName</value>
       </constructor-arg>
   </bean>
 
   <!-- 配置JMS模板,Spring提供的JMS工具类,它发送、接收消息。(Queue) -->
   <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
       <property name="connectionFactory" ref="connectionFactory" />
       <property name="defaultDestination" ref="queueDestination" />
       <property name="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
package org.soa.test.activemq.queues;
 
import org.soa.test.activemq.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Component;
 
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import java.util.List;
 
/**
 * Created by JamesC on 16-9-22.
 */
@Component
public class ProduceMsg {
 
    @Autowired
    private JmsTemplate jmsTemplate;
 
    /**
     * 向指定队列发送消息
     */
    public void sendMessage(Destination destination, final String msg) {
        System.out.println("向队列" + destination.toString() + "发送了消息------------" + msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }
 
    /**
     * 向默认队列发送消息(默认队列名称在bean:queueDestination配置)
     */
    public void sendMessage(final String msg) {
        //queue://queue1
        String destination = jmsTemplate.getDefaultDestination().toString();
        System.out.println("向队列" + destination + "发送了消息------------" + msg);
        jmsTemplate.send(new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }
 
    /**
     * 向默认队列发送消息
     */
    public void sendMessageConvertAndSend(final Object msg) {
 
        String destination = jmsTemplate.getDefaultDestination().toString();
        System.out.println("向队列" + destination + "发送了消息------------" + msg);
        //使用内嵌的MessageConverter进行数据类型转换,包括xml(JAXB)、json(Jackson)、普通文本、字节数组
        jmsTemplate.convertAndSend(destination, msg);
    }
 
    /**
     * 向指定队列发送消息
     */
    public void sendStudentInfo(Destination destination, final StudentInfo msg) {
        System.out.println("向队列" + destination.toString() + "发送了消息------------" + msg);
        jmsTemplate.send(destination, new MessageCreator() {
            public Message createMessage(Session session) throws JMSException {
                return session.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
package org.soa.test.activemq.queues;
 
import com.alibaba.fastjson.JSON;
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.soa.test.activemq.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
import javax.jms.Destination;
import java.util.Date;
 
 
/**
 * Created by JamesC on 16-9-22.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-jms.xml")
public class ProduceMsgTest extends AbstractJUnit4SpringContextTests {
 
    @Autowired
    protected ApplicationContext ctx;
 
    /**
     * 队列名queue1  这里使用jms配置文件中的数据
     */
    @Autowired
    private Destination queueDestination;
 
    /**
     * 队列消息生产者
     */
    @Autowired
    private ProduceMsg produceMessage;
 
 
    //向默认队列发消息(文本)
    @Test
    public void produceMsg_DefaultQueue() {
        String msg = "这里是向默认队列发送的消息" + new Date().toString();
        produceMessage.sendMessage(msg);
    }
 
    //向默认队列发消息(Json字符串)
    @Test
    public void produceMsg_Json() {
        StudentInfo info = new StudentInfo();
        info.setId(1);
        info.setStdName("李磊");
        info.setStdNo("001");
        info.setEnterDate(new Date());  //队列存放的是时间戳
 
        String alibabaJson = JSON.toJSONString(info);
        produceMessage.sendMessage(alibabaJson);
    }
 
    //向默认队列发消息(使用convertAndSend发送对象)
    @Test
    public void produceMsg_ConvertAndSend() {
        StudentInfo info = new StudentInfo();
        info.setId(1);
        info.setStdName("李磊");
        info.setStdNo("001");
        info.setEnterDate(new Date());
 
        produceMessage.sendMessageConvertAndSend(info);
    }
 
    //向指定队列发消息(文本)
    @Test
    public void produceMsg_CustomQueue() {
        for (int i = 0; i < 20; i++) {
            ActiveMQQueue myDestination = new ActiveMQQueue("queueCustom");
            produceMessage.sendMessage(myDestination, "----发送消息给queueCustom");
        }
    }
 
    //向指定队列发消息(队列名称从XML读取)
    @Test
    public void produceMsg_XmlQueue() {
        for (int i = 0; i < 20; i++) {
            ActiveMQQueue destinationQueue = (ActiveMQQueue) applicationContext.getBean("queueDestination");
            produceMessage.sendMessage(destinationQueue, "----send my msg to queueXml");
        }
    }
 
    //向指定队列发消息(发送对象)
    @Test
    public void produceMsg_StudentInfo() {
 
        StudentInfo info = new StudentInfo();
        info.setId(1);
        info.setStdName("李磊");
        info.setStdNo("001");
        info.setEnterDate(new Date());
 
        ActiveMQQueue destination = new ActiveMQQueue("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
package org.soa.test.activemq.queues;
 
import org.soa.test.activemq.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.support.JmsUtils;
import org.springframework.stereotype.Component;
 
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.ObjectMessage;
import javax.jms.TextMessage;
 
/**
 * Created by JamesC on 16-9-22.
 */
@Component
public class ConsumeMsg {
    @Autowired
    private JmsTemplate jmsTemplate;
 
    /**
     * 接受消息
     */
    public String 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 "";
        }
        return msg;
    }
 
    /**
     * 接受消息
     */
    public StudentInfo receiveStudentInfo() {
        try {
            String destination = jmsTemplate.getDefaultDestination().toString();
            ObjectMessage msg=(ObjectMessage)jmsTemplate.receive(destination);
            return (StudentInfo)msg.getObject();
 
        } catch (JMSException e) {
            //检查性异常转换为非检查性异常
            throw JmsUtils.convertJmsAccessException(e);
        }
    }
 
    /**
     * 接受消息
     */
    public Object receiveConvertAndReceive() {
        String destination = jmsTemplate.getDefaultDestination().toString();
        Object msg = jmsTemplate.receiveAndConvert(destination);
        return 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
package org.soa.test.activemq.queues;
 
import org.apache.activemq.command.ActiveMQQueue;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.soa.test.activemq.StudentInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
 
/**
 * Created by JamesC on 16-9-22.
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring-jms.xml")
public class ConsumeMsgTest {
 
    @Autowired
    private ConsumeMsg consumeMsg;
 
    //从指定队列接收消息(文本)
    @Test
    public void receiveMsg() {
        //没有消息阻塞一段时间后会抛异常
        //java.lang.NullPointerException
        ActiveMQQueue destination = new ActiveMQQueue("defaultQueueName");
        consumeMsg.receive(destination);
    }
 
    //从指定队列接收消息(StudentInfo对象消息)
    @Test
    public void receiveStudentInfo() {
        StudentInfo msg = consumeMsg.receiveStudentInfo();
        System.out.println(msg.getStdName());
    }
 
    //从指定队列接收消息(Json对象)
    @Test
    public void receiveConvertAndReceive() {
 
        StudentInfo msg =(StudentInfo) consumeMsg.receiveConvertAndReceive();
        System.out.println(msg.getStdName());
    }
}

ActiveMQ_点对点队列(二)的更多相关文章

  1. SDUT-2132_数据结构实验之栈与队列二:一般算术表达式转换成后缀式

    数据结构实验之栈与队列二:一般算术表达式转换成后缀式 Time Limit: 1000 ms Memory Limit: 65536 KiB Problem Description 对于一个基于二元运 ...

  2. RabbitMQ 消息队列 二

    一:查看MQ的用户角色 rabbitmqctl list_users 二:添加新的角色,并授予权限 rabbitmqctl add_user xiaoyao 123456 rabbitmqctl se ...

  3. ActiveMQ笔记之点对点队列(Point-to-Point)

    1. 点对点通信 点对点是一种一对一通信方式,更像是有一个队列,一个人往队列里放消息,另一个人从队列中取消息,其最大的特点是一个消息只会被消费一次,即使有多个消费者同时消费,他们消费的也是不同的消息. ...

  4. day43-python消息队列二-queue模块

    Python提供了Queue模块来专门实现消息队列Queue对象 Queue对象实现一个fifo队列(其他的还有lifo.priority队列,这里不再介绍).queue只有maxsize一个构造参数 ...

  5. Sword 内核队列二

    #ifndef __GTC_FIFO_H_ #define __GTC_FIFO_H_ #ifndef GTC_MAX #define GTC_MAX(a,b) ((a) > (b) ? (a) ...

  6. 剖析nsq消息队列(二) 去中心化代码源码解析

    在上一篇帖子剖析nsq消息队列(一) 简介及去中心化实现原理中,我介绍了nsq的两种使用方式,一种是直接连接,还有一种是通过nslookup来实现去中心化的方式使用,并大概说了一下实现原理,没有什么难 ...

  7. linux网络编程之system v消息队列(二)

    今天继续学习system v消息队列,主要是学习两个函数的使用,开始进入正题: 下面则开始用代码来使用一下该发送函数: 在运行之前,先查看一下1234消息队列是否已经创建: 用上次编写的查看消息队列状 ...

  8. .net core使用rabbitmq消息队列 (二)

    之前有写过.net core集成使用rabbitmq的博文,见.net core使用rabbitmq消息队列,但是里面的使用很简单,而且还有几个bug,想改下,但是后来想了想,还是算了,之前使用的是. ...

  9. 数据结构实验之栈与队列二:一般算术表达式转换成后缀式(SDUT 2132)

    题目链接 #include <bits/stdc++.h> using namespace std; typedef long long ll; int ok(char ch, char ...

随机推荐

  1. 【一周读书】All life is problem solving

    书籍:<开放的智力> 采铜是我在知乎关注最早的大V之一,那时我脑里有一大堆疑惑和问题,是他的答案帮助我理清了思绪.我从他身上学习到对书籍的爱好,对思维方法的关注,对智慧的向往.读这本小集子 ...

  2. Learning Spark: Lightning-Fast Big Data Analysis 中文翻译

    Learning Spark: Lightning-Fast Big Data Analysis 中文翻译行为纯属个人对于Spark的兴趣,仅供学习. 如果我的翻译行为侵犯您的版权,请您告知,我将停止 ...

  3. 在Windows Azure虚拟机上开发Windows 8 应用

    前提条件 Windows Azure开发者账号:如果您拥有微软MSDN Subscription账户,那么意味着您可免费申请Windows Azure开发者账号. 创建虚拟机 点击Windows Az ...

  4. red5安装时候出现服务不能启动异常

    Exception java.lang.ClassCastException: org.slf4j.helpers.BasicMDCAdapter cannot be cast to ch.qos.l ...

  5. 使用mx:Repeater在删除和添加item时列表闪烁

    使用mx:Repeater在删除和添加item时列表闪烁 不可能在用户界面上闪闪的吧,recycleChildren属性可帮助我们 recycleChildren属性==缓存,设为true就可以了 本 ...

  6. java 25 - 5 网络编程之多线程实现聊天室

    平时聊天都是在同一个窗口的,所以,这个窗口同时实现发送数据和接收数据,这时就需要多线程实现. 建立一个类: 把聊天的发送端和接收端放在同一个类,启动一个窗口 public class CharRoom ...

  7. Zygote浅谈

    Zygote是什么 操作系统中,进程实际上是文件到地址空间的映射像.进程将要运行时,由操作系统将其映射到地址空间,完成这项工作的事物本质也应是一个进程,我们称这个进程为孵化进程,那么这个进程怎么收到消 ...

  8. 字符串截取函数substr()

    substr(参数1,参数2[,参数3]); 该系统函数返回被截后的子字符串,它接受2个必选参数,参数1为要截取的字符串,参数2为截取的开始位置,参数3可选,表示截取长度. 例子:substr(&qu ...

  9. usb驱动开发15之设备生命线

    总算是进入了HCD的片儿区,既然来到一个片区,怎么都要去拜会一下山头几个大哥吧.,先回忆一些我们怎么到这里的?给你列举一个调用函数过程usb_control_msg->usb_internal_ ...

  10. python数字图像处理(15):霍夫线变换

    在图片处理中,霍夫变换主要是用来检测图片中的几何形状,包括直线.圆.椭圆等. 在skimage中,霍夫变换是放在tranform模块内,本篇主要讲解霍夫线变换. 对于平面中的一条直线,在笛卡尔坐标系中 ...