Integrate springboot activeMq

ActiveMq is an open source message system provided by Apache and implemented by Java.

The JMS (Java Message Service) specification is well supported

ActiveMq installation: activemq.apache.org/components/… Download and install the corresponding version from the official website

After downloading, unzip it and use it

The default port number of ActiveMq is 8161. Both the user name and password are admin, which can be accessed by http://localhost:8161 on the local machine

Integrate springboot ActiveMq

1. Import dependencies

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

2. Configure activeMq in the Properties file

spring.activemq.broker-url=tcp://localhost:61616
The default should be false for queue, and true for publish and subscribe
spring.activemq.packages.trust-all=true
spring.activemq.user=admin
spring.activemq.password=admin
Copy the code

3. Write a queue

@Component public class QueueBean{// Create a Queue instance @bean Queuequeue(){// The message set here is the queue namereturn new ActiveMQQueue("hello.javaboy"); }}Copy the code

4. Create message senders and consumers

@Component public class JmsComponent{Autowired JmsMessagingTemplate JmsMessagingTemplate; @autowired Queue Queue; /** * @param message */ public void send(message){ jmsMessagingTemplate.convertAndSend(this.queue,message); } /** * receive messages * @param message */ / listen for messages sent by the queue name @jMSListener (destination ="hello.javaboy")
    public void readMessage(Message message){ System.out.println(message); }}Copy the code

5. The above Message entity class

public class Message implements Serializable { private String content; // Message body private Date sendDate; // when the message is sent //setTostring method}Copy the code

6. Send and consume messages

Inject the JmsComponent into the test class and call the send() method to forward the message

@SpringBootTest
class ActivemqApplicationTests {
    @Autowired
    JmsComponent jmsComponent;
    @Test
    void contextLoads() {
        Message message = new Message();
        message.setContent("hello activeMq"); message.setSendDate(new Date()); jmsComponent.send(message); }}Copy the code

Start the project first and send the message after running the test class:

The console prints the message:

The RabbitMQ springboot integration

Rabbitmq installation is tedious, here to use the Docker container for installation, docker installation is very convenient, a command all done

Install RabbitMQ using docker

-p (large P) indicates that the port is automatically mapped to the host port

docker run -d --hostname my-rabbitmq --name some-rabbitmq -P rabbitmq:3-management
Copy the code

First import dependencies

 <dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-amqp</artifactId>
 </dependency>
Copy the code

Writing configuration files:

# configuration the rabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=32771
Copy the code

RabbitMQ has four switching modes:

Direct switch: Direct Exchange

Sector switch: Fanout Exchange

Main switch: Topic Exchange

First switch: Headers Exchange

The following describes the switching modes in 4:

1, the Direct exchange

@configuration public class RabbitDirectConfig {public final static String DIRECTNAME ="javaboy-direct"; // Message Queue @bean Queuequeue(){// the name value is the queue name, which the routingKey matchesreturn new Queue("hello.RabbitMQ");
    }
    @Bean
    Queue queue1() {return new Queue("hello.RabbitMQ1");
    }
    @Bean
    DirectExchange directExchange(){// The first parameter is DIRECTNAME, the second parameter indicates whether it is valid after restart, and the third parameter indicates whether it is deleted if it has not been used for a long timereturn new DirectExchange(DIRECTNAME,true.false);
    }
    @Bean
    Binding binding(){// bind the queue to DirectExchangereturn BindingBuilder.bind(queue()).to(directExchange()).with("direct");
    }
    @Bean
    Binding binding1(){// bind the queue to DirectExchangereturn BindingBuilder.bind(queue1()).to(directExchange()).with("direct"); }}Copy the code

2. Configure DirectReceiver for consumers:

@Component Public class DirectReceiver {// Only listen to messages in queue() @rabbitListener (Queues =)"hello.RabbitMQ")
    public void hanlder(String msg){
        System.out.println("hanlder>>>"+msg); } // Just listen to messages on queue1() @rabbitListener (queues ="hello.RabbitMQ1")
    public void hanlder1(String msg){
        System.out.println("hanlder1>>>"+msg); }}Copy the code

Test code:

Inject RabbitTemplate into springBoot’s test class (the RabbitMQ template provided by SpringBoot)

 @Autowired
    RabbitTemplate rabbitTemplate;
    @Test
    void contextLoads() {/ / the first two parameters are routingKey, the second for the message contents rabbitTemplate. ConvertAndSend ("hello.RabbitMQ"."hello RabbitMQ test");
        rabbitTemplate.convertAndSend("hello.RabbitMQ1"."hello RabbitMQ test222");
    }
Copy the code

After starting the project, running the test class can see that only consumers that match the RoutingKey receive the corresponding message:

2, the Fanout exchange

Fanout policy (any queue bound to it receives a message regardless of the routingKey)

1. Configure RabbitFanoutConfig

// The Fanout policy (as long as the queue is bound to it, @configuration public class RabbitFanoutConfig {public final static String FANOUTNAME ="javaboy-fanout"; QueueOne and queuetwo-@bean Queue are configuredqueueOne() {return new Queue("queue-one");
    }
    @Bean
    Queue queueTwo() {return new Queue("queue-two");
    }
    @Bean
    FanoutExchange fanoutExchange() {return new FanoutExchange(FANOUTNAME,true.false); } // Bind both queues to FanoutExchange with @bean BindingbindingOne() {return BindingBuilder.bind(queueOne()).to(fanoutExchange());
    }
    @Bean
    Binding bindingTwo() {returnBindingBuilder.bind(queueTwo()).to(fanoutExchange()); }}Copy the code

2. Configure consumer FanoutReceiver:

Public class FanoutReceiver {// Two consumers listen on two different queues @rabbitListener (Queues =)"queue-one")
    public void hanlder1(String msg){
        System.out.println("FanoutReceiver:hanlder1>>>"+msg);
​
    }
    @RabbitListener(queues = "queue-two")
    public void hanlder2(String msg){
        System.out.println("FanoutReceiver:hanlder2>>>"+msg); }}Copy the code

3. Test classes:

@Test
    void rabbitFanoutThree parameters () {/ / said RabbitFanoutConfig, routingkey, the name of the news contents rabbitTemplate. ConvertAndSend (RabbitFanoutConfig FANOUTNAME, null,"hello fanout test");
    }
Copy the code

This method has nothing to do with a RoutingKey. Just write null

Look at the output: You can see that both consumers received the message

3, Topic exchange

Topic strategies can be used to match queues according to routingKey rules (wildcard mode).#. * is the word, and # represents fuzzy matching

For example, routingkey is: xiaomi.# then with xiaomi. The leading queue will receive the message

The routingkey is: #.phone.# indicates that messages with a phone in the routingkey will be matched to queues with phones

1. Configure RabbitTopicConfig

The /topic policy can be based on the routingKey rule (wildcard mode) to match the queue for forwarding rule *.* #.//* is the word,# represents fuzzy matching
@Configuration
public class RabbitTopicConfig {
    public final static String TOPICNAME = "javaboy-topic";
​
    @Bean
    TopicExchange topicExchange() {return new TopicExchange(TOPICNAME,true.false);
    }
    @Bean
    Queue xiaomi() {return new Queue("xiaomi");
    }
    @Bean
    Queue huawei() {return new Queue("huawei");
    }
    @Bean
    Queue phone() {return new Queue("phone");
    }
​
    @Bean
    Binding xiaomiBinding(){
        //xiaomi.# : indicates that the routingKey of a message that starts with xiaomi will route to the queue of Xiaomi
        return BindingBuilder.bind(xiaomi()).to(topicExchange()).with("xiaomi.#");
    }
    @Bean
    Binding huaweiBinding() {return BindingBuilder.bind(huawei()).to(topicExchange()).with("huawei.#");
    }
    @Bean
    Binding phoneBinding() {/ /#.phone.# : Indicates that messages with phones in the routingKey are routed to the phone queue
        return BindingBuilder.bind(phone()).to(topicExchange()).with("#.phone.#"); }}Copy the code

2. Configure consumer TopicReceiver:

@component public class TopicReceiver {// Listen on queues named xiaomi, Huawei, phone @rabbitListener (Queues ="xiaomi")
    public void handlerXM(String msg){
        System.out.println("TopicReceiver:handlerXM>>>"+msg);
    }
    @RabbitListener(queues = "huawei")
    public void handlerHW(String msg){
        System.out.println("TopicReceiver:handlerHW>>>"+msg);
    }
    @RabbitListener(queues = "phone")
    public void handlerPHONE(String msg){
        System.out.println("TopicReceiver:handlerPHONE>>>"+msg); }}Copy the code

3. Test classes:

@Test
    void rabbitTopic() {/ / according to the matching rules of the message can only be xiaomi queue received rabbitTemplate. ConvertAndSend (RabbitTopicConfig TOPICNAME,"xiaomi.news".Xiaomi News); / / according to the matching rules of the message can only be phone queue received rabbitTemplate. ConvertAndSend (RabbitTopicConfig TOPICNAME,"vivo.phone"."Vivo mobile phone"); / / according to the matching rules can the message don't huawei and phone received two queue rabbitTemplate. ConvertAndSend (RabbitTopicConfig TOPICNAME,"huawei.phone".Huawei Mobile);
​
    }
Copy the code

View the output:

You can see that the RoutingKey matches two queues for messages from Huawei. Phone, and the other two only match one queue

4, Headers exchange

The matching mode is based on the header of a routing rule. During the matching, a map set is passed in. A routingKey can be used to match the key value in the map

1. RabbitHeaderConfig:

@Configuration
public class RabbitHeaderConfig {
    public final static String HEADERNAME = "javaboy-header";
​
    @Bean
    HeadersExchange headersExchange() {return new HeadersExchange(HEADERNAME,true.false); } // Create two queues with different headers @bean QueuequeueName() {return new Queue("name-queue");
    }
    @Bean
    Queue queueAge() {return new Queue("age-queue");
    }
    @Bean
    Binding bindingName(){
        Map<String,Object> map = new HashMap<>();
        map.put("name"."hello"); // indicates that if a key value in a map set matches a routingKey, the message will be forwarded to the corresponding routereturn BindingBuilder.bind(queueName()).to(headersExchange()).whereAny(map).match();
    }
​
    @Bean
    Binding bindingAge() {return BindingBuilder.bind(queueAge()).to(headersExchange()).where("age").exists(); }}Copy the code

Create a consumer HeaderReceiver:

@Component
public class HeaderReceiver {
    @RabbitListener(queues = "name-queue")
    public void handlerName(byte[] msg){
        System.out.println("HeaderReceiver:handlerName>>>>"+new String(msg,0,msg.length));
    }
    @RabbitListener(queues = "age-queue")
    public void handlerAge(byte[] msg){
        System.out.println("HeaderReceiver:handlerAge>>>>"+new String(msg,0,msg.length)); }}Copy the code

3. Test code:

@Test
    public void rabbitHeader(){// Set the message and set the header,setHeader("name"."hello"NameMessage = MessageBuilder.withBody("hello name".getBytes()).setHeader("name"."hello").build();
        Message ageMessage =
            MessageBuilder.withBody("hello 99 age".getBytes()).setHeader("age"."99").build();
        rabbitTemplate.send(RabbitHeaderConfig.HEADERNAME,null,nameMessage);
        rabbitTemplate.send(RabbitHeaderConfig.HEADERNAME,null,ageMessage);
    }
Copy the code

View the output:

Change the value in setheader to see the result:

 Message nameMessage = 
            MessageBuilder.withBody("hello name".getBytes()).setHeader("name"."javaboy").build();
Copy the code

You can see that only one message is printed because the key and value do not match.

The last

You can leave a comment below to discuss what you don’t understand. You can also pay attention to my private letter and ask me. I will answer it after I see it. Also welcome everyone to pay attention to my official account: bright future, Golden Three silver four job-hunting interview season, sorted out more than 1000 nearly 500 pages of PDF documents of Java interview questions, articles will be updated in it, sorted out the information will be placed in it. Thank you for watching, think the article is helpful to you remember to pay attention to me a thumb-up support!