ActiveMQ Getting Started Tutorial

activeMQ download link
Before introducing ActiveMQ, first briefly introduce the JMS specification:
The basic components of JMS
1. Connection factory The
connection factory is the object that the client uses to create the connection, such as ActiveMQConnectionFactory provided by ActiveMQ.

2. Connection
JMS Connection encapsulates a virtual connection between the client and the JMS provider.

3. Session
JMS Session is a single-threaded context for producing and consuming messages. Sessions are used to create message producers, message consumers, and messages. Sessions provide a transactional context in which a set of send and receive is combined into an atomic operation.

4. Destination A
destination is an object that a client uses to specify the destination of the messages it produces and the source of the messages it consumes. Two messaging domains are defined in the JMS1.0.2 specification: point-to-point (PTP) messaging domains and publish/subscribe messaging domains. Peer-to-peer messaging domains are characterized as follows:
• There can be only one consumer per message.
• There is no temporal correlation between message producers and consumers. The consumer can ingest messages whether or not they are running when the producer sends them.
The characteristics of the publish/subscribe messaging domain are as follows:
• Each message can have multiple consumers.
• There is a temporal correlation between producers and consumers. A consumer subscribed to a topic can only consume messages published since it subscribed. The JMS specification allows clients to create durable subscriptions, which somewhat relaxes the temporal dependency requirement. A durable subscription allows a consumer to consume messages it sends when it is not active.
In the point-to-point messaging domain, the destination is called a queue; in the publish/subscribe messaging domain, the destination is called a topic.

  1. Message Producer A
    message producer is an object created by a session to send a message to a destination.

6. Message Consumer A
message consumer is an object created by a session to receive messages sent to a destination. Messages can be consumed in one of two ways:
• Synchronous consumption. Explicitly fetch messages from the destination by calling the consumer's receive method. The receive method can block until a message arrives.
• Asynchronous consumption. Clients can register a message listener for consumers to define actions to be taken when messages arrive.

  1. Messages
    JMS messages consist of the following three parts:
    • The message header. Each header field has corresponding getter and setter methods.
    • Message properties. If values ​​other than message header fields are required, then message properties can be used.
    • Message body. The message types defined by JMS are TextMessage, MapMessage, BytesMessage, StreamMessage and ObjectMessage.
    First, let's use the code to show the message queue mode of activeMQ without spring management:
    Step 1: Unzip the downloaded activeMQ and open the link, as shown in the figure:
    Check your computer's operating system

start the service

Browser input: http://localhost:8161 Enter the 8161 management port because the default configuration port number in the jetty configuration file in activemq is 8161
jetty.xml
After successful startup:
write picture description here

The default username and password of activemq are both admin. After the login is successful, the interface:
write picture description here
Next, we will start writing the code level.
Step 2 : Build a maven project and introduce the jar package dependency of activeMQ.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zzit.jms</groupId>
    <artifactId>activemq_test</artifactId>
    <version>0.0.1-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-all</artifactId>
            <version>5.9.0</version>
        </dependency>
    </dependencies>
</project>

Step 3: Write the sender of the activemq message:

package com.zzit.jms;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.activemq.ActiveMQConnectionFactory;
/**
 * activeMQ消息发送端
 * @author yufu
 *
 */
public class ActivemqSend {

    private static final String url = "tcp://localhost:61616";
    private static final String queueName = "myqueue";

    public static void main(String[] args) {
        //1.创建一个连接工厂
        ConnectionFactory factory = new ActiveMQConnectionFactory(ActiveMQConnectionFactory.DEFAULT_USER,
                ActiveMQConnectionFactory.DEFAULT_PASSWORD, url);
        Connection conn;
        Session session;
        Destination destination;
        MessageProducer producer;
        TextMessage message;
        try {
            //2.创建连接
            conn = factory.createConnection();
            //3.启动连接
            conn.start();
            // 演示学习,不使用事务
            //4.创建会话
            session = conn.createSession(Boolean.FALSE, Session.AUTO_ACKNOWLEDGE);
            //5.创建一个一个目的地队列
            destination = session.createQueue(queueName);
            //6.创建生产者
            producer = session.createProducer(destination);
            for (int i = 0; i < 100; i++) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //7.创建消息
                message = session.createTextMessage("发送消息" + i);
                //8.发送消息
                producer.send(message);
                System.out.println("发送成功:" + message.getText());
            }
            //9.关闭连接
            conn.close();
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}

Let's start the main method of the ActivemqSend class and let him start sending messages:
write picture description here
Let's remember to start the main method of the ActivemqReceive class, and let him start receiving messages:
write picture description here
Watch Activemq's message queue: write picture description here
Here we only start one consumer. After writing this, let's sort out the relationship between these interfaces.
First, we start a ConnectionFactory, create a Connection connection through the ConnectionFactory, and then create a session through the Connection. The session can create a producer MessageProducer, a consumer MessageConsumer and a message TextMessage, and finally the producer sends messages to the queue, and the consumer takes it from the queue. information.

Let's talk about the development of integrating mq through spring.
We will not repeat the problem of starting the connection. The
first step : create a new maven project and introduce the related dependency jar packages of activemq and spring

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.zzit.jms</groupId>
    <artifactId>activemq_spring</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <properties>
        <spring.version>4.2.5.RELEASE</spring.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jms</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.activemq</groupId>
            <artifactId>activemq-core</artifactId>
            <version>5.7.0</version>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework</groupId>
                    <artifactId>spring-context</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>
</project>

Step 2: Producer Development:

package com.zzit.spring.activemq;

import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
/**
 * mq和spring整合后的生产者
 * @author yufu
 *
 */
public class MqProducer {
    @Autowired
    private JmsTemplate jmsTemplate;
    @Autowired
    private Destination destination;

    public void setJmsTemplate(JmsTemplate jmsTemplate) {
        this.jmsTemplate = jmsTemplate;
    }

    public void setDestination(Destination destination) {
        this.destination = destination;
    }

    public void sendMessage(final String message) {
        jmsTemplate.send(destination, new MessageCreator() {

            public Message createMessage(Session session) throws JMSException {
                TextMessage msg = session.createTextMessage(message);
                return msg;
            }
        });
        System.out.println("发送的消息:" + message);
    }

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring_producer.xml");
        MqProducer mqProducer = (MqProducer) context.getBean("mqProducer");
        for (int i = 0; i < 1000; i++) {
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mqProducer.sendMessage("消息:" + i);
        }
    }
}

Step 3: Introduce the producer's spring configuration file:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!-- mq为我们提供的connectionFactory -->
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"></property>
    </bean>
    <!-- spring jms提供的连接池 -->
    <!-- 引入连接工厂(spring的jms为我们提供了2个connectionFactory,一个是SingleConnectionFactory,另一个是CachingConnectionFactory) -->
    <bean id="connectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory" ref="targetConnectionFactory"></property>
    </bean>

    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>queue</value>
        </constructor-arg>
    </bean>

    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
    </bean>

    <bean id="mqProducer" class="com.zzit.spring.activemq.MqProducer">
        <property name="jmsTemplate" ref="jmsTemplate"></property>
        <property name="destination" ref="destination"></property>
    </bean>
</beans>

Next, we can start the producer, which is similar to the previous one, so there is no more screenshots here.
Let's take a look at the development of consumers next. To develop consumers, we first need to create consumer listeners:

package com.zzit.spring.activemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

public class ConsumerMessageListener implements MessageListener {

    public void onMessage(Message message) {
        TextMessage textMessage=(TextMessage) message;
        try {
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("接收消息:"+textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }

}

Consumers only need to load the spring configuration file.

package com.zzit.spring.activemq;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
 * mq和spring整合后的消费者
 * @author yufu
 *
 */
public class MqReceiver {

    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("spring_consumer.xml");

    }
}

Development of consumer spring profile:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context    http://www.springframework.org/schema/context/spring-context.xsd"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="targetConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="tcp://localhost:61616"></property>
    </bean>
    <bean id="connectionFactory"
        class="org.springframework.jms.connection.SingleConnectionFactory">
        <property name="targetConnectionFactory" ref="targetConnectionFactory"></property>
    </bean>
    <bean id="destination" class="org.apache.activemq.command.ActiveMQQueue">
        <constructor-arg>
            <value>queue</value>
        </constructor-arg>
    </bean>
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="connectionFactory"></property>
    </bean>

    <!-- 配置消息容器 -->
    <bean id="jmsContainer"
        class="org.springframework.jms.listener.DefaultMessageListenerContainer">
        <property name="connectionFactory" ref="connectionFactory"></property>
        <property name="destination" ref="destination"></property>
        <property name="messageListener" ref="consumerMessageListener"></property>
    </bean>
    <!-- 消息监听器 -->
    <bean id="consumerMessageListener" class="com.zzit.spring.activemq.ConsumerMessageListener"></bean>

</beans>

Finally, it can be seen in the message queue of mq:write picture description here

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324658291&siteId=291194637