0032ActiveMQ of producers and consumers to achieve java coding operations queue queue

Today, entry-level learning to write producer producer and consumer consumer operations activemq with java queue queue, in order to review after review, now doing summarized as follows:

maven project to build here will not explain, the following steps maven project has been to build a good premise:

1, pom.xml introduced two jar package required activemq

<dependency>

    <groupId>org.apache.activemq</groupId>

    <artifactId>activemq-all</artifactId>

    <version>5.15.9</version>

</dependency>

<dependency>

    <groupId>org.apache.xbean</groupId>

    <artifactId>xbean-spring</artifactId>

    <version>3.16</version>

</dependency>

2, JMS coding overall architecture

 

 

3, Manufacturer coded as follows:

Import org.apache.activemq.ActiveMQConnectionFactory;

Import the javax.jms *;.

public class JmsProduce {
    public static Final String ACTIVEMQ_URL = "TCP: //192.168.225.132: 61616" ;
    public static void main (String [] args) throws a JMSException {
        // 1 according to a given url address, username and password in the default factory to create a connection (constructor has three parameters, wherein the two parameters are user name and password)
       
ActiveMQConnectionFactory activeMQConnectionFactory = new new ActiveMQConnectionFactory ( ACTIVEMQ_URL );
        // 2 by to obtain connection factory connection
       
connection connection activeMQConnectionFactory.createConnection = ();
        //. 3Start the visit, the real connection is established, you need to make sure that the firewall server configured correctly so, where will it go
       
connection.start ();
        // 4 to create a session the session , false representatives do not open things, Session.AUTO_ACKNOWLEDGE behalf automatic sign
       
Session session = connection .createSession ( false , the Session. AUTO_ACKNOWLEDGE );
        // 5 to create a destination (specifically queue queue or topic topic ) , the parameter is the name of the queue
       
// return type can use queue reception, you can also use the destination reception, because queue inherited destination
       
= session.createQueue queue queue ( "Queue1" );
        // 6 to create a message producer, responsible for the production of a message to the specified queue
       
Producer = session.createProducer the MessageProducer (Queue);
        //. 7 created . 3 message, sent by the producer to a destination
       
for ( int I =. 1; I <=. 3; I ++) {
            // create message
           
TextMessage textMessage = session. createTextMessage ( "message" + I);
            // send message
           
producer.send (textMessage);
        }
        //. 8 Close resource
       
producer.close ();
        Session.close ();
        Connection.close ();
        . the System OUT .println ( " producer to activemq completion message production! " );
    }
}

4, the console see if the message is queued, as shown below:

 

 The meaning of each column are: the number of messages to be consumed, the number of consumers, the number of queued messages, the number of messages a team.

----------------------------------------- above process is a simple message producers to produce -----------------------------

------------------------------------ -------- consumer spending news process ----------------------------------------------

1, coded as follows (without latency):

Import org.apache.activemq.ActiveMQConnectionFactory;

Import the javax.jms *;.

public class JmsConsumer {
    public static Final String ACTIVEMQ_URL = "TCP: //192.168.225.132: 61616" ;
    public static void main (String [] args) throws a JMSException {
        // 1 according to a given url address, username and password in the default factory to create a connection (constructor has three parameters, wherein the two parameters are user name and password)
       
activeMQConnectionFactory activeMQConnectionFactory = new new activeMQConnectionFactory ( ACTIVEMQ_URL );
        // 2 by to obtain connection factory connection
       
connection connection activeMQConnectionFactory.createConnection = ();
        //. 3Start the visit, the real connection is established, you need to make sure that the firewall server configured correctly so, where will it go
       
connection.start ();
        // 4 to create a session the session , false representatives do not open things, Session.AUTO_ACKNOWLEDGE behalf automatic sign
       
Session session = connection .createSession ( false , the Session. AUTO_ACKNOWLEDGE );
        // 5 to create a destination (specifically queue queue or topic topic ) , the parameter is the name of the queue
       
// return type can use queue reception, you can also use the destination reception, because queue inherited destination
       
= session.createQueue Queue Queue ( "Queue1" );
        MessageConsumer consumer = session.createConsumer(queue);
        //
       
while(true){

            // receive () method can take a parameter, if the message is not to be consumed, and so on up to how long

           // receive wait parameter () method waits until a message is received, will be processed back
            TextMessage = Message (TextMessage) consumer.receive ();
            IF ( null == Message) {
                BREAK ;
            }
            String Message S = .getText ();
            . System OUT .println (S);
        }
        // 8 close the resource
       
consumer.close ();
        session.close ();
        Connection.close ();
        System. OUT .println ( " consumers from activemq consumption message complete! " );
    }
}

 

 

Discovery messages to be consumed is 0, there is a consumer, into the team news three, three out of the news team

If the consumer not to have to wait further that in the absence of the message, i.e., between consumers and disconnected Queue, or receive (n * 1000L) Wait n seconds to wait longer, the console displays information as follows (the consumer will be displayed from 1 to 0):

 

 

2 、测试含有等待时间的receive()方法,代码更改如下:

//TextMessage message = (TextMessage)consumer.receive();
TextMessage message = (TextMessage)consumer.receive(5000L);

生产者重新生产3条消息,控制台显示如下:

消费者换成含有等待时间的接收消息的方法,控制台显示如下:

 

将消费者处理完消息后,如果等待5秒还没有获得消息,则断开连接。

以上两种消费方式即:receive()方法不带参数,一直等待(生产者新生产了消息,消费者就会消费掉消息);带参数,超过等待时间就断开连接

3、 消费者以监听器的形式监听队列

import org.apache.activemq.ActiveMQConnectionFactory;

import javax.jms.*;
import java.io.IOException;

public class JmsConsumer {
    public static  final String ACTIVEMQ_URL = "tcp://192.168.225.132:61616";
    public static void main(String[] args) throws JMSException, IOException {
        //1 按照给定的url地址,采用默认的用户名密码创建连接工厂(有三个参数的构造方法,其中两个参数是用户名密码)
       
ActiveMQConnectionFactory activeMQConnectionFactory = new ActiveMQConnectionFactory(ACTIVEMQ_URL);
        //2 通过连接工厂获得连接
       
Connection connection = activeMQConnectionFactory.createConnection();
        //3 启动访问,真正建立连接,需要确保防火墙、服务端配置等都正确,能正常访问
       
connection.start();
        //4 创建会话sessionfalse代表不开启事物,Session.AUTO_ACKNOWLEDGE代表自动签收
       
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        //5 创建目的地(具体是队列queue还是主题topic,参数是队列的名称
       
//返回类型可以用Queue接收,也可以用Destination接收,因为Queue继承Destination
       
Queue queue = session.createQueue("queue1");
        MessageConsumer consumer = session.createConsumer(queue);
        //6 消费者消费消息
      
/* while(true){
            TextMessage message = (TextMessage)consumer.receive();
            //TextMessage message = (TextMessage)consumer.receive(5000L);
            if(null == message){
                break;
            }
            String s = message.getText();
            System.out.println(s);
        }*/
      
//6 以监听器的形式监听并消费消息
       
consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if(message != null && message instanceof  TextMessage){
                    TextMessage textMessage = (TextMessage)message;
                    try {
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //7 如果以监听器的形式监听消息,则需要此行代码,代表不关闭消费者,否则有可能上边还没有进行消费,下边就把资源都关闭了
       
//会抛出IOException
       
System.in.read();
        //8 关闭资源
       
consumer.close();
        session.close();
        connection.close();
        System.out.println("消费者从activemq消费消息完成!");
    }
}

结果如下:

 

 

监听器的形式也是资源不关闭,生产者生产消息,消费者就能够监听到并进行消费。监听器是异步非阻塞的方式,当消息到达后,系统自动调用监听器MessageListener的onMessage(Message message)方法。

如果启动两个消费者监听消息队列,然后生产者向queue生产消息,两个消费者会轮询消费消息,就像activemq自带负载均衡的感觉。

activemq队列小总结:无论先启动消费者,还是先启动生产者,消费者都能消费到生产者生产的消息,两个没有时间上的关系(异步),且mq中的消息一旦被消费者消费掉,就不再储存该条消息了,所以消息不会被重复消费。

 

若有理解不到之处,望指正!

Guess you like

Origin www.cnblogs.com/xiao1572662/p/12080812.html