Technology Sharing

SpringAMQP message sending and receiving demo

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

First, we need to create a microservice architecture, because generally speaking, this is used in a microservice architecture (of course, there is nothing wrong with a single unit, see qps)

In the parent project we need to introduce the amqp dependency

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

Then select the sub-service we need to complete the initial message

First, the message is sent, using RabbitTemplate as the message sending template, method convertAndSend

@SpringBootTest
public class SpringAmqpTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Test
    void testMsgCaiyiTestQueue(){
        String msg = "this is message from caiyi";
        rabbitTemplate.convertAndSend("cybg_study_queue",msg);
    }
}

Then we can create the listener class under the listener package (Need to be registered as a spring bean) completion message, through @RabbitListener

@RabbitListener(queues = "cybg_study_queue")
public void listenQueueMsg(String msg){
    System.out.println("接收到的msg:"+msg);
}

OK, so far the message sending and receiving for rabbitmq under springAMQP is completed