当前位置:网站首页>ActiveMQ Basics

ActiveMQ Basics

2022-04-23 14:12:00 All the names I thought of were used

One 、 The role of message middleware

( One ) The application of decoupling

For example, during login , After receiving the registration message, the server writes the user information into the database , Then call the push system to send a short message to the user to inform that the registration is successful . However , The push system may be separate from this application , We can deliver the message to the push system through message middleware , After the push system receives the message , call service Push text messages to users .
Some students said , Then I use dubbo It can also complete the corresponding functions . Yes , But not as fast as message oriented middleware , Because it is an asynchronous , As long as the server sends the message, it can respond to the user without waiting for the result returned by the push system

( Two ) Traffic peak clipping

In the second kill system , The second kill request initiated by the user will first reach the message middleware , Then the second kill system takes out the messages from the message queue in order , The rest of the message is returned , Tell the user that the second kill failed .

Two 、ActiveMq Basic components

( One ) ConnectionFactory

This class is used to create connection Connected

// Define the link factory 
ConnectionFactory connectionFactory = null;
connectionFactory = new ActiveMQConnectionFactory("admin", "admin", "tcp://192.168.70.151:61616");

( Two ) Connection: Connection between client and middleware

// Create connection objects 
connection = connectionFactory.createConnection();
			
// Start the connection 
connection.start();

( 3、 ... and ) Session: Session between client and middleware

/**
* transacted: Whether to use transactions   Optional value is :true|false
 *            true: With a transaction   When setting the secondary variable value .Session.SESSION_TRANSACTED
 *            false: Not applicable to matters , Set the secondary variable   be acknowledgeMode Parameters must be set 
 * acknowledgeMode:
* Session.AUTO_ACKNOWLEDGE: Automatic message acknowledgment mechanism 
 * Session.CLIENT_ACKNOWLEDGE: Client confirmation mechanism 
* Session.DUPS_OK_ACKNOWLEDGE: Client acknowledgement message mechanism with replica 
 */
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

( Four ) destination

Point to point mode :queue
A subscription model :topic

// Create destination , The destination name is the name of the queue . The consumer of the message needs to access the corresponding queue by this name 
destination = session.createQueue("my-destination");

destination = session.createTopic("my-destination");

( 5、 ... and ) Producer && Consumer

// Create the producer of the message  
MessageProducer producer = session.createProducer(destination);

// Create consumers of messages 
MessageConsumer consumer = session.createConsumer(destination);

( 6、 ... and ) Message

// Create a text message 
message = session.createTextMessage(”hello“);
producer.send(message);

// Receive text message 
TextMessage message = (TextMessage)consumer.receive();
string text = message.getText();
// Create object message 
message = session.createObjectMessage(obj);
producer.send(message);
// Object receive message 
ObjectMessage message = (ObjectMessage)consumer.receive();
User user = message.getObject();

3、 ... and 、Springboot Integrate activeMq

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

( One ) yml To configure

spring:
 activemq:
  broker-url: tcp://127.0.0.1:61616
  user: admin
  password: admin
  jms:
   pub-sub-domain: true #  The default is false:queue   true:topic
queue: queue_mq #  Point to point consumer names 
topic: topic_mq #  Subscription consumer name 

( Two ) destination To configure

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.annotation.EnableJms;

import javax.jms.Queue;
import javax.jms.Topic;

@Configuration
@EnableJms
public class ActiveMqConfig {

    @Value("${queue}")// Corresponding yml Defined in the file queue
    private String queue;

    @Value("${topic}")// Corresponding yml Defined in the file topic
    private String topic;
    /**
     *  Create a peer-to-peer queue    A message can only be consumed by one consumer   ---  one-on-one 
     * @return
     */
    @Bean
    public Queue queue(){
        return new ActiveMQQueue(queue);
    }
    /**
     *  Create a subscription queue    A message can be consumed by multiple consumers  ---  One to many 
     * @return
     */
    @Bean
    public Topic topic(){
        return new ActiveMQTopic(topic);
    }
}

( 3、 ... and ) producer

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.core.JmsMessagingTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.jms.Queue;
import javax.jms.Topic;

@RestController
public class ProducerController {

    @Autowired
    private Queue queue;

    @Autowired
    private Topic topic;

    @Autowired
    private JmsMessagingTemplate jmsMessagingTemplate;

    /**
     *  Producers of peer-to-peer message queues 
     * @param string
     */
    @GetMapping("/queue")
    public void sendMsgQueue(@RequestParam String string){
        System.out.println(" The message has been sent , Ready to be consumed , The message is  ---> "+string);
        jmsMessagingTemplate.convertAndSend(queue,string);
    }

    /**
     *  Producers of one to many message queues 
     * @param string
     */
    @GetMapping("/topic")
    public void sendMsgTopic(@RequestParam String string){
        System.out.println(" The message has been sent , Ready to be consumed , The message is  ---> "+string);
        jmsMessagingTemplate.convertAndSend(topic,string);
    }

}

( Four ) consumer

import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;

@Component
public class TopicConsumer {
    
    /**
     *  Listen to the message , Name is the name sent by the producer , Should agree , Otherwise we won't be able to monitor .
     *  Because it's subscriber mode , There can be multiple consumers , Here are two examples to test 
     * @param string
     */
    @JmsListener(destination = "${topic}")
    public void consumerTopicOne(String string){

        System.out.println(" I'm consumer one : Consumption message succeeded , The message is ---> "+string);

    }

    @JmsListener(destination = "${topic}")
    public void consumerTopicTwo(String string){

        System.out.println(" I'm consumer number two : Consumption message succeeded , The message is ---> "+string);

    }
}

版权声明
本文为[All the names I thought of were used]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231404419510.html