Freshly released, this is the most detailed springboot integrated messaging service on the whole network. It is recommended to collect it!

springboot integrates activeMq

ActiveMq is an open source message system provided by Apache, which is implemented in java,

Well supports JMS (Java Message Service) specification

ActiveMq installation: http://activemq.apache.org/components/classic/download/ Download and install the corresponding version on the official website

After downloading, unzip it and use it

The default port number of ActiveMq is 8161. Both the user name and password can be used locally by admin http://localhost:8161 Go visit

springboot integrates ActiveMq

1. Import dependency

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

  

2. Configure activeMq in the properties file

spring.activemq.broker-url=tcp://localhost:61616
#If it is a point-to-point queue, it should be false by default here. If it is a publish subscription, it must be set to true
spring.activemq.packages.trust-all=true
spring.activemq.user=admin
spring.activemq.password=admin

  

3. Write queue

@Component
public class QueueBean{
    //Create a queue instance
    @Bean
    Queue queue(){
        //The message set here is the name of the queue
        return new ActiveMQQueue("hello.javaboy");
    }
}

  

4. Create the sender and consumer of the message

@Component
public class JmsComponent{
    //Message template provided by springboot
    @Autowired
    JmsMessagingTemplate jmsMessagingTemplate;
    //Self created queue instances
    @Autowired
    Queue queue;
    /**
     * send message
     * @param message
     */
    public void send(Message message){
        jmsMessagingTemplate.convertAndSend(this.queue,message);
    }
    /**
     * receive messages
     * @param message
     */
    //Indicates to listen to messages sent by the queue name
    @JmsListener(destination = "hello.javaboy")
    public void readMessage(Message message){
        System.out.println(message);
    }
​
}

  

5. Above Message entity class

public class Message implements Serializable {
    private String content;//Message body
    private Date sendDate;//Time the message was sent
    //Omit get, set, tostring methods
}

  

6. Send and consume messages

Inject 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);
    }
}

  

First, start the project and send messages in the running test class:

The console will print the message content:

 

 

springboot integrates RabbitMQ

rabbitmq installation is complicated. Here, the docker container is used for installation. Docker installation is very convenient. One command is all done

Installing rabbitmq through docker

-P (large p) indicates automatic mapping to host port

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

  

Import dependencies first

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

  

Write profile:

#Configuring rabbitMQ
spring.rabbitmq.host=localhost
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
spring.rabbitmq.port=32771

  

RabbitMQ has four switching modes:

Direct exchange

Fanout exchange

Main switch: Topic exchange

Header exchange

The following describes the four switching modes:

1,Direct exchange

//Direct policy (only forwarded to users matching routingKey)
@Configuration
public class RabbitDirectConfig {
    public final static String DIRECTNAME = "javaboy-direct";
    //Message queue
    @Bean
    Queue queue(){
        //The name value is the queue name, and routingKey will match it
        return 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 after being unused for a long time
        return new DirectExchange(DIRECTNAME,true,false);
    }
    @Bean
    Binding binding(){
        //Bind queue and DirectExchange together
        return BindingBuilder.bind(queue()).to(directExchange()).with("direct");
    }
    @Bean
    Binding binding1(){
        //Bind queue and DirectExchange together
        return BindingBuilder.bind(queue1()).to(directExchange()).with("direct");
    }
​
}

  

2. Configure consumer DirectReceiver:

//Configure consumer
@Component
public class DirectReceiver {
    //Listen only to messages on the queue()
    @RabbitListener(queues = "hello.RabbitMQ")
    public void hanlder(String msg){
        System.out.println("hanlder>>>"+msg);
​
    }
    //Listen only to queue1() queue messages
    @RabbitListener(queues = "hello.RabbitMQ1")
    public void hanlder1(String msg){
        System.out.println("hanlder1>>>"+msg);
​
    }
}

  

Test code:

Inject the rabbittemplate (RabbitMQ template provided by springboot) into the test class of springboot

 @Autowired
    RabbitTemplate rabbitTemplate;
    @Test
    void contextLoads() {
        //The first parameter is routingKey and the second is message content
        rabbitTemplate.convertAndSend("hello.RabbitMQ","hello RabbitMQ test");
        rabbitTemplate.convertAndSend("hello.RabbitMQ1","hello RabbitMQ test222");
    }

  

After starting the project, run the test class to see that only the consumers matching the routingkey receive the corresponding messages:

2,Fanout exchange

Fanout policy (as long as it is a queue bound to it, it will receive messages that are independent of the routingKey)

1. To configure RabbitFanoutConfig:

//Fanout policy (as long as it is a queue bound to it, it will receive messages that are independent of the routingKey)
@Configuration
public class RabbitFanoutConfig {
    public final static String FANOUTNAME = "javaboy-fanout";
    //Two message queues queueOne and queueTwo are configured
    @Bean
    Queue queueOne(){
        return new Queue("queue-one");
    }
    @Bean
    Queue queueTwo(){
        return new Queue("queue-two");
    }
    @Bean
    FanoutExchange fanoutExchange(){
        return new FanoutExchange(FANOUTNAME,true,false);
    }
    //Bind two queues to FanoutExchange
    @Bean
    Binding bindingOne(){
        return BindingBuilder.bind(queueOne()).to(fanoutExchange());
    }
    @Bean
    Binding bindingTwo(){
        return BindingBuilder.bind(queueTwo()).to(fanoutExchange());
    }
}

  

2. Configure consumer FanoutReceiver:

//Configure consumer
@Component
public class FanoutReceiver {
    //Two consumers listen to 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);
​
    }
}

  

3. Test class:

@Test
    void rabbitFanout(){
        //The three parameters represent the name, routingkey and message content of RabbitFanoutConfig
        rabbitTemplate.convertAndSend(RabbitFanoutConfig.FANOUTNAME,null,"hello fanout test");
    }

  

This method has nothing to do with routingkey. Just write null

View output: you can see that both consumers have received messages

 

3,Topic exchange

The topic policy can match the queue for forwarding according to the routingKey rule (wildcard method). The rule is.\* Is a word, \

For example, routingkey is xiaomi# With xiaomi The first queue will receive this message

Routingkey is: \ Phone# Indicates that when the routingkey of the message contains a phone, it will match the queue with a phone

1. To configure RabbitTopicConfig:

/topic Policies can be based on routingKey To match the queue for forwarding. The rule is*.#.*
    //*Is a word, \
@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 if the routingKey of the message starts with xiaomi, it will be routed to xiaomi's queue
        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 all the phones in the routingKey of the message will be routed to the phone queue
        return BindingBuilder.bind(phone()).to(topicExchange()).with("#.phone.#");
    }
}

  

2. Configure consumer TopicReceiver:

@Component
public class TopicReceiver {
    //Listen to the queues named xiaomi, huawei and phone respectively
    @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);
    }
}

  

3. Test class:

@Test
    void rabbitTopic(){
        //According to the matching rule, this message can only be received by xiaomi's queue
        rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME,"xiaomi.news","Xiaomi news");
        //According to the matching rule, this message can only be received by the phone queue
        rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME,"vivo.phone","vivo mobile phone");
        //According to the matching rule, the message can be received separately from huawei and phone queues
        rabbitTemplate.convertAndSend(RabbitTopicConfig.TOPICNAME,"huawei.phone","Huawei mobile phone");
​
    }

  

View output:

 
 

You can see that the routingkey is huawei The phone messages match two queues, and the other two match only one queue

4,Headers exchange

This pattern is matched according to the header of the routing rule. When matching, a map set needs to be passed in. routingkey can match the key value in the map. The matching rule can make any or all. Any means that any information is included, and all means that all information must be matched

1. To configure 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 header s
    @Bean
    Queue queueName(){
        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 the routingKey matches the key value in the map set, the message will be forwarded to the corresponding route
        return BindingBuilder.bind(queueName()).to(headersExchange()).whereAny(map).match();
    }
​
    @Bean
    Binding bindingAge(){
        return BindingBuilder.bind(queueAge()).to(headersExchange()).where("age").exists();
    }
}

  

2. Create 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));
    }
}

  

3. Test code:

@Test
    public void rabbitHeader(){
        //Set the message and set the header. setHeader("name","hello") indicates the key and value in the map set respectively
        Message 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);
    }

  

View output:

 

Change the value in setheader to view the result:

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

  

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

 

 

last

If you don't understand anything after reading, you can leave a message below to discuss it. You can also follow my private letter and ask me. I will answer it when I see it. You are also welcome to pay attention to my official account: bright future, golden, silver and four job hopping interview season. More than 1000 Java interview questions with nearly 500 pages of pdf documents have been sorted out. The articles will be updated in it, and the sorted materials will also be put in it. Thank you for watching. If you think the article is helpful to you, remember to pay attention to me and give me a favor!

Tags: Java Spring Programmer

Posted by sv4rog on Wed, 01 Jun 2022 17:20:14 +0530