Five minutes to quickly understand ActiveMQ, the case is simple and detailed!

Posted by danrah on Sun, 19 May 2019 03:28:10 +0200

Recently, I had a leisure to explore ActiveMQ.

ActiveMQ message queue, the container for sending and receiving information, functions as asynchronous message, traffic sharpening, application coupling.
There are also Kafka, RabbitMQ, RocketMQ, ZeroMQ and MetaMQ.

install

Download address: http://activemq.apache.org/co...

Double-click / bin/activemq.bat to start after the decompression of the Windows version

It has its own visual page: http://localhost:8161/admin/

The default access password is admin/admin
If you need to modify it in: / conf/jetty-realm.properties

JmsTemplate

Integrating on spring boot, using spring's JmsTemplate to manipulate ActiveMQ
First, import the required jar package coordinates in the pom file:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-activemq</artifactId>
    </dependency>
    <dependency>
        <groupId>org.apache.activemq</groupId>
        <artifactId>activemq-pool</artifactId>
    </dependency>

2. Add an ActiveMQ configuration file spring-jms.xml

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

    <!-- To configure JMS Connection factory -->
    <bean id="innerConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="${spring.activemq.broker-url}" />
    </bean>
    <!--Configure connection pool-->
    <bean id="pooledConnectionFactory" class="org.apache.activemq.pool.PooledConnectionFactory"
        destroy-method="stop">
        <property name="connectionFactory" ref="innerConnectionFactory" />
        <property name="maxConnections" value="100"></property>
    </bean>
    <!-- To configure JMS Template, Spring Provided JMS Tool class -->
    <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate">
        <property name="connectionFactory" ref="pooledConnectionFactory" />
        <property name="defaultDestination" ref="JmsSenderDestination" />
        <property name="receiveTimeout" value="10000" />
    </bean>
</beans>

Configuration on Startup Class for Effectiveness

@ImportResource(locations={"classpath:/config/spring-jms.xml"})

IV. Configuring ActiveMQ Connecting Address in application.properties

spring.activemq.broker-url=tcp://localhost:61616

Get ready; start writing about producers and consumers, and I'll put producers and consumers in one project. Before that, two concepts need to be understood.
Queue and Topic

Transfer model

Queue and Topic are two messaging models supported by JMS:

  1. point-to-point (PTP) Queue messaging model:
    A message producer corresponds to a consumer
  2. pub/sub Topic messaging model:
    A message producer corresponds to multiple consumers

QUEUE

  1. First add the configuration queue name Queue_love in spring-jms.xml

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

    </bean>

  2. Create a producer to send messages; @Qualifier ("JmsSender Destination") specifies the Queue_love queue sent to the above configuration

    @Component
    public class JmsSender {
    @Autowired
    private JmsTemplate jmsTemplate;
    
    @Qualifier("JmsSenderDestination")
    @Autowired
    protected Destination destination;
    
    public void sendMessage(final String msg) {
    
        logger.info("QUEUE destination :" + destination.toString() + ", Send a message:" + msg);
        jmsTemplate.send(destination, new MessageCreator() {
            @Override
            public Message createMessage(final Session session) throws JMSException {
                return session.createTextMessage(msg);
            }
        });
    }}
  3. Create a consumer to consume messages:

    @Component
    public class JmsTemplateListener implements MessageListener {
    
    @Override
    public void onMessage(Message message) {
        final TextMessage tm = (TextMessage) message;
        try {
            logger.info("QUEUE Receiving information==="+tm.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }
    }}
  4. Consumers need to configure in spring-jms.xml which queue messages the consumer needs to consume

    <!-- Configure message queue listeners -->
    <bean id="JmsListener" class="com.mashu.activeMq.jmsTemplate.JmsTemplateListener" />
    
    <!-- Use spring Conduct configuration monitoring -->
    <bean id="JmsTemplateListenerContainer"
      class="org.springframework.jms.listener.DefaultMessageListenerContainer">
    <property name="connectionFactory" ref="pooledConnectionFactory"></property>
    <property name="destination" ref="JmsSenderDestination"></property>
    <property name="messageListener" ref="JmsListener"></property>
    <property name="sessionTransacted" value="false"></property>
    <property name="concurrentConsumers" value="6"></property>
    <property name="concurrency" value="2-4"></property>
    <property name="maxConcurrentConsumers" value="10"></property>
    </bean>

Such a simple message queue transceiver has been written to see the results.

The message is consumed immediately. We can annotate the consumer first. We can see the content of the message on the visual page only by sending the message by the producer.

Topic

Topic is similar to Queue in that it only needs calss = org. apache. activemq. command. ActiveMQ opic when defining queues

<bean id="JmsSenderTDestination" class="org.apache.activemq.command.ActiveMQTopic">
    <constructor-arg>
        <value>Topic_love</value>
    </constructor-arg>
</bean>

Message

In addition to using the createTextMessage() method to send pure string messages, there are

  1. Forms of serialized objects
    session.createObjectMessage();
  2. Stream form, which can be used to pass files
    session.createStreamMessage();
  3. Form of bytes
    session.createBytesMessage();
  4. The form of map
    session.createMapMessage();

Security configuration

ActiveMQ, like MySQL, can also configure username and password. By default, we can open it:

  1. Add the following information to conf/activemq.xml (be sure to place it on the < system Usage > tab)

        <plugins>
             <simpleAuthenticationPlugin>
                 <users>
                     <authenticationUser username="${activemq.username}"
                      password="${activemq.password}" groups="users,admins"/>
                 </users>
             </simpleAuthenticationPlugin>
         </plugins>
    
  2. The corresponding username password is configured in / conf/credentials.properties

    activemq.username=admin
    activemq.password=123456
    guest.password=password
  3. Then we need to add user name and password to application.properties in the project:

    spring.activemq.broker-url=tcp://localhost:61616
    spring.activemq.user=admin
    spring.activemq.password=123456

Message persistence

Messages saved by default are in the data kahadb directory, and MySQL is also supported.
The producer sends the message to the database and the consumer consumes it and the message disappears from the database.

  1. Modify/conf/activemq.xml
    Will:

        <persistenceAdapter>
                <kahaDB directory="${activemq.data}/kahadb"/>
        </persistenceAdapter>
    

    Revised to:

    <persistenceAdapter>
        <jdbcPersistenceAdapter dataDirectory="${activemq.base}/data" dataSource="#mysql-ds"/>
    </persistenceAdapter>
    
  2. Add / conf/activemq.xml to configure MySQL connection information

    <bean id="mysql-ds" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/db_activemq?relaxAutoCommit=true"/>
    <property name="username" value="root"/>
    <property name="password" value="123456"/>
    <property name="poolPreparedStatements" value="true"/>
    </bean>
    
  3. Add mysql-connector-java.jar to the / bin directory
  4. New database db_activemq

After restarting ActiveMQ, the database generates three tables: activemq_acks, activemq_lock and activemq_msgs.

Topics: Java Spring Apache MySQL xml