通过 ActiveMQ 演示如何使用 JMS API

来源:互联网 发布:美国人工智能上市公司 编辑:程序博客网 时间:2024/06/01 10:25

出处:http://www.oschina.net/question/12_57749#tags_nav


消息机制是软件组件和应用程序之间通讯的一种方法,一个消息系统是一个点对点的服务:消息客户端可以发送消息也可以接收消息,每一个客户端连接到一个消息代理,这个代理提供了消息的创建、发送、接收和读取的功能。

因为是松散耦合的架构使得消息机制很适合用在分布式通讯。组件将消息发送到目的地,而接收者从目的地获取所发送的消息。但是不要求发送者和接收者都同时有效。事实上,发送者不需要知道接收者的信息,而接收者也不知道了解发送者信息。发送者和接收者唯一需要一致的是消息的格式,以及使用哪个目标地址。消息机制跟一些紧耦合的技术例如 RMI 远程方法调用是完全不同的,因为 RMI 必须知道远端应用所提供的方法。

点对点消息域

一个点对点 (PTP) 的产品或者应用是基于消息队列、发送者和接收者的概念来构建的。每个消息被定为到一个特定的队列,接收者从队列中提取发送给它的消息,队列将保留所有的消息直到消息被取走或者过期。

JMS

每个消息只有唯一一个接收者(消费者)

  • 消息的发送者和接收者没有时间上的依赖,接收者可在消息过期前的任意时间内去获取消息,而不一定得发送者是在线的
  • 接收者需要确认成功的处理了消息
  • 使用 PTP 消息机制可确保一个消息只有一个接收者

发布/订阅消息域

publishSubscribe

在一个基于发布/订阅模型的应用或者产品中,客户端根据主题来订阅消息,有点像公告牌。发布者和订阅者一般都是匿名的,而且可以动态的发布或者订阅内容。消息系统会谨慎处理消息的分发到订阅了某个主题的所有订阅者,消息只会发送给当前订阅者,然后就失效,新的订阅者无法接收到刚刚失效的消息。

发布和订阅的消息机制具有以下特征:

  • 每个消息可以有多个消费者
  • 发布者和订阅者是有时间依赖,只有当前订阅了某个主题的订阅者才能收到消息,订阅者必须保持活跃以获取消息

当一个消息可能会有多于1个的接收者是,请使用发布/订阅消息机制。

接下来我们使用 ActionMQ 来简单演示消息的发送和接收。

首先下载 ActiveMQ for windows (HERE)

下载后解压到任意目录,然后执行 apache-activemq-5.5.1\bin 目录下的 activemq 程序。

运行的提示信息如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
.............
 
.............
 
-0:1) started
 INFO | jetty-7.1.6.v20100715
 INFO | ActiveMQ WebConsole initialized.
 INFO | Initializing Spring FrameworkServlet'dispatcher'
 INFO | ActiveMQ Console at http://0.0.0.0:8161/admin
 INFO | ActiveMQ Web Demos at http://0.0.0.0:8161/demo
 INFO | RESTfulfile access application at http://0.0.0.0:8161/fileserver
 INFO | Started SelectChannelConnector@0.0.0.0:8161

这样 ActiveMQ 服务器就已经启动成功了,你可以按 Ctrl+C 来关闭它,但先别急,因为我们马上要写一些程序来做测试。ActiveMQ 提供一个很不错的管理控制台,你可以在浏览器上打开 http://localhost:8161/admin/ 来访问它。

这里是发送消息的代码:

?
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
import javax.jms.*;
 
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
public class Producer {
    // URL of the JMS server. DEFAULT_BROKER_URL will just mean
    // that JMS server is on localhost
    privatestatic String url = ActiveMQConnection.DEFAULT_BROKER_URL;
 
    // Name of the queue we will be sending messages to
    privatestatic String procon ="QUEUETOTEST";
 
    publicstatic void main(String[] args) throws JMSException {
        // Getting JMS connection from the server and starting it
        ConnectionFactory connectionFactory =
            newActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();
 
        // JMS messages are sent and received using a Session. We will
        // create here a non-transactional session object. If you want
        // to use transactions you should set the first parameter to 'true'
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);
 
        // Destination represents here our queue 'QUEUETOTEST' on the
        // JMS server. You don't have to do anything special on the
        // server to create it, it will be created automatically.
        Destination destination = session.createQueue(procon);
 
        // MessageProducer is used for sending messages (as opposed
        // to MessageConsumer which is used for receiving them)
        MessageProducer producer = session.createProducer(destination);
 
        // We will send a small text message
        TextMessage message = session.createTextMessage("I am First Message");
 
        // Here we are sending the message!
        producer.send(message);
        System.out.println("Sent message '"+ message.getText() + "'"+ " On Queue - "+ procon);
 
        connection.close();
    }
}

下面是 Consumer 类的代码:

?
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
import javax.jms.*;
 
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
 
public class Consumer {
    // URL of the JMS server
    privatestatic String url = ActiveMQConnection.DEFAULT_BROKER_URL;
 
    // Name of the queue we will receive messages from
    privatestatic String procon ="QUEUETOTEST";
 
    publicstatic void main(String[] args) throws JMSException {
        // Getting JMS connection from the server
        ConnectionFactory connectionFactory
            =new ActiveMQConnectionFactory(url);
        Connection connection = connectionFactory.createConnection();
        connection.start();
 
        // Creating session for sending messages
        Session session = connection.createSession(false,
            Session.AUTO_ACKNOWLEDGE);
 
        // Getting the queue 'QUEUETOTEST'
        Destination destination = session.createQueue(procon);
 
        // MessageConsumer is used for receiving (consuming) messages
        MessageConsumer consumer = session.createConsumer(destination);
 
        // Here we receive the message.
        // By default this call is blocking, which means it will wait
        // for a message to arrive on the queue.
        Message message = consumer.receive();
 
        // There are many types of Message and TextMessage
        // is just one of them. Producer sent us a TextMessage
        // so we must cast to it to get access to its .getText()
        // method.
        if(message instanceofTextMessage) {
            TextMessage textMessage = (TextMessage) message;
            System.out.println("Received message '"
                + textMessage.getText() +"'" + " On Queue - "+ procon);
        }
        connection.close();
    }
}

你可以在 ActiveMQ 的管理控制台 http://localhost:8161/admin/queues.jsp 中看到在 QUEUETOTEST 的队列中有一个消息。

首先运行上面的 Producer 程序,我们可以看到如下输出:

JMS producer

JMS producer

然后运行 Consumer 程序,输出如下:

jms consumer

consumer

现在运行 Consumer 程序,将会在 Queues 中得到如下结果:

consumer_first

consumer_first

Java Message Service (JMS) API 是 Java EE 平台上用于处理消息的标准。

如果你想了解更多关于 JMS 技术,可以访问 JMS Tutorial on Sun’s webpage.

英文原文,OSCHINA原创翻译

0 0