springboot details of the excavation (ActiveMq integration)

Download the official website:

http://activemq.apache.org/?utm_source=csdn_toolbar

 

When the difference between downloading: ActiveMQ 5 "Classic" and ActiveMQ Artemis


Long-established, unlimited pluggable architecture for many generations of applications and services.

JMS clients with a full realization (including JNDI) 1.1

The use of shared storage high availability

Familiar jms-based addressing model

For distributing the load of "agency network"

KahaDB for durability and JDBC options

 



The next generation event-driven messaging applications, high-performance, non-blocking architecture.

JMS 1.1 and 2.0, with a complete client-side implementation, including JNDI

Using shared storage or network-based replication for high availability

Simple but powerful protocol-independent addressing model

For flexible load distribution cluster

Advanced Logging for low latency and persistence to achieve JDBC

With high intrinsic parity activemq5 to simplify the migration

 


windows service is installed under: 

Download the results show:

Before using ActiveMQ, you first need to start it. Just unpacked directory in a bin directory, there are two Win32 and Win64 directories, according to their own computer select one to open and run activemq.bat where to start ActiveMQ.

ActiveMQ JMS and presentation

What is JMS

According to Baidu Encyclopedia explained:

I.e. Java Message Service JMS (Java Message Service) application program interface, API Java platform is message-oriented middleware (MOM), and sends a message with the interval between two applications, or distributed system, in order to achieve asynchronous communication. JMS is an independent and platform-specific API, MOM vast majority of providers offer support for JMS.

Just JMS interfaces, different providers or open source organizations because they have different implementations, ActiveMQ is one of them, it supports JMS, introduced by Apache.

There are several JMS object model:

Connection factory: ConnectionFactory
JMS connection: Connection
JMS session: the Session
JMS purpose: Destination
JMS producer: Producer
JMS consumer: Consumer
JMS messages of two types: point to point and publish / subscribe.

It can be seen JMS and JDBC actually somewhat similar, JDBC API can be used to access many different relational databases, and JMS also provides a vendor-independent access methods to access messaging services. In this paper, it is using ActiveMQ.

ActiveMQ

Apache ActiveMQ is the introduction of a strong ability to open source message bus. Full support for ActiveMQ JMS 1.1 and J2EE 1.4 specification, although a long time has been the introduction of the JMS specification, JMS in today's Java EE application still plays a special role. ActiveMQ is mainly used in the handling of asynchronous messages, namely the so-called asynchronous message processing without waiting for the message sender and the message recipient to return, even without concern for whether the message is sent successfully.

There are two main forms of asynchronous message queue (Queue) and topic (Topic), messaging queue for point-form theme for publish / subscribe messaging. In this paper to learn about how to use these two forms of news in the Spring Boot.

 

News producers to produce messages posted to the Queue, Queue message is removed from the consumer, and consumer news. It should be noted that, after the message is consumer spending, Queue is no longer its storage, so consumers will not consume the message to the message that has been consumed. Message Queue supports multiple consumers, but for a message, it will only be a consumer spending, which is what we call point in the form of news communication.

After startup, enter in your browser: http://127.0.0.1:8161/admin/access ActiveMQ server, user name and password are both admin. as follows:

We can see Queues and Topics are two options, both options are point to point messaging and publish / subscribe messaging viewing window. The above describes peer messaging communication, what is publish / subscribe messaging messages about communications?

Publish / subscribe message, the message producer (release) will be released in a message to Topic, there are multiple messages consumers (subscription) consume the message. And point to point in different ways, a message posted to the Topic will be consumed all subscribers. Analyzes of both specific implementation below.

ActiveMQ integration

Import and configuration dependent

In Spring Boot ActiveMQ integrated starter need to import the following dependence:

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

Then in  application.yml the configuration file, to do the next ActiveMQ configuration:

、spring:
  activemq:
      # activemq url
    broker-url: tcp://localhost:61616
    in-memory: true
    pool:
      # 如果此处设置为true,需要添加activemq-pool的依赖包,否则会自动配置失败,无法注入JmsMessagingTemplate
      enabled: false

Queue and Topic created

First you need to create two message Queue and Topic, we put ActiveMqConfig created, as follows:

/**
 * activemq的配置
 * @author  shengwu ni
 */
@Configuration
public class ActiveMqConfig {
    /**
     * 发布/订阅模式队列名称
     */
    public static final String TOPIC_NAME = "activemq.topic";
    /**
     * 点对点模式队列名称
     */
    public static final String QUEUE_NAME = "activemq.queue";

    @Bean
    public Destination topic() {
        return new ActiveMQTopic(TOPIC_NAME);
    }

    @Bean
    public Destination queue() {
        return new ActiveMQQueue(QUEUE_NAME);
    }
}

Queue and Topic can be seen that two types of messages, are used  new ActiveMQQueue , and  new ActiveMQTopic to create, on the back of the parameters corresponding to the write message name. In this way, in other places can be directly injected into these two components come as news.

Interface messages sent

In Spring Boot, we just let the JmsMessagingTemplate template to quickly send the message, as follows:

/**
 * 消息发送者
 * @author shengwu ni
 */
@Service
public class MsgProducer {

    @Resource
    private JmsMessagingTemplate jmsMessagingTemplate;

    public void sendMessage(Destination destination, String msg) {
        jmsMessagingTemplate.convertAndSend(destination, msg);
    }
}

The method convertAndSend first parameter is the destination of the message sent by the second parameter is the specific message content.

Point news production and consumption

Production-point message

Message production, we put the Controller do, since the above components Queue message has been generated, it is injected directly into the Controller we can come. After calling the above method for transmitting messages sendMessage to the successful production of a message.

/**
 * ActiveMQ controller
 * @author shengwu ni
 */
@RestController
@RequestMapping("/activemq")
public class ActiveMqController {

    private static final Logger logger = LoggerFactory.getLogger(ActiveMqController.class);

    @Resource
    private MsgProducer producer;
    @Resource
    private Destination queue;

    @GetMapping("/send/queue")
    public String sendQueueMessage() {

        logger.info("===开始发送点对点消息===");
        producer.sendMessage(queue, "Queue: hello activemq!");
        return "success";
    }
}

Consumer-point message

Consumer-point message is very simple, as long as we can specify the destination, JMS listener always monitor whether there is a message here, if there is, then the consumer.

/**
 * 消息消费者
 * @author shengwu ni
 */
@Service
public class QueueConsumer {

    /**
     * 接收点对点消息
     * @param msg
     */
    @JmsListener(destination = ActiveMqConfig.QUEUE_NAME)
    public void receiveQueueMsg(String msg) {
        System.out.println("收到的消息为:" + msg);
    }
}

As can be seen, the use of  @JmsListener annotation to listen to the specified destination, in the internal message receiving method, we can do the corresponding logic processing according to specific business needs.

have a test

Start the project in the browser, type: http://localhost:8081/activemq/send/queueobserve the output log in the console, the following description appears send messages and logs consumer success.

收到的消息为:Queue: hello activemq!

Publish / subscribe message production and consumption

Publish / subscribe messaging production

And peer to peer messages, we inject Topic sendMessage method and call the producer to send a subscription message, the following will not be repeated:

@RestController
@RequestMapping("/activemq")
public class ActiveMqController {

    private static final Logger logger = LoggerFactory.getLogger(ActiveMqController.class);

    @Resource
    private MsgProducer producer;
    @Resource
    private Destination topic;

    @GetMapping("/send/topic")
    public String sendTopicMessage() {

        logger.info("===开始发送订阅消息===");
        producer.sendMessage(topic, "Topic: hello activemq!");
        return "success";
    }
}

Publish / subscribe messaging consumption

Publish / subscribe messaging different consumer and point-to-subscribe messaging support more consumer spending together. Secondly, Spring Boot the default messages point to point, so use the Topic, will not work, we need to add a configuration profile application.yml in:

spring:
  jms:
    pub-sub-domain: true

This configuration is false, then, for the point to point messages, but also Spring Boot default. This does solve the problem, but so configured, the message point mentioned above can not normally consumed. But not both, so this is not a good solution.

Let's look at a better solution. The definition of a factory, @JmsListener notes Queue default only receive messages, if you want to receive a message Topic, need to set up containerFactory. We are still above the ActiveMqConfig configuration class added:

/**
 * activemq的配置
 *
 * @author shengwu ni
 */
@Configuration
public class ActiveMqConfig {
    // 省略其他内容

    /**
     * JmsListener注解默认只接收queue消息,如果要接收topic消息,需要设置containerFactory
     */
    @Bean
    public JmsListenerContainerFactory topicListenerContainer(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        // 相当于在application.yml中配置:spring.jms.pub-sub-domain=true
        factory.setPubSubDomain(true);
        return factory;
    }
}

After such configuration,  @JmsListener designated this container plant annotations can consume Topic messages. as follows:

/**
 * Topic消息消费者
 * @author shengwu ni
 */
@Service
public class TopicConsumer1 {

    /**
     * 接收订阅消息
     * @param msg
     */
    @JmsListener(destination = ActiveMqConfig.TOPIC_NAME, containerFactory = "topicListenerContainer")
    public void receiveTopicMsg(String msg) {
        System.out.println("收到的消息为:" + msg);
    }

}

ContainerFactory specified above our own properties for configuration topicListenerContainer can be. Topic messages can be many times the consumer, the consumer class that we can copy more to test, I will not paste the code, you can refer to my source test.

have a test

Start the project in the browser, type: http://localhost:8081/activemq/send/topicobserve the output log in the console, the following description appears send messages and logs consumer success.

收到的消息为:Topic: hello activemq!
收到的消息为:Topic: hello activemq!

to sum up

This paper describes the ActiveMQ JMS and related concepts and installation and startup, and detailed analysis of the Spring Boot messages point to point and publish / subscribe messaging configured in two ways, news production and consumption. ActiveMQ is a strong ability to open source message bus, is useful in dealing with asynchronous messages.

Guess you like

Origin blog.csdn.net/chehec2010/article/details/93510175