一、pom.xml
项目 | 版本 |
---|---|
spring-boot-starter-parent | 2.1.6.RELEASE |
<!-- RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
二、RabbitMQ配置
package com.example.rabbitmq.configs;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitConfig {
@Bean
public Queue queue() {
//队列名称
return new Queue("q_hello");
}
}
三、消息生产者
package com.example.rabbitmq.Sender;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 消息生产者
*/
@Component
public class HelloSender {
@Autowired
private AmqpTemplate rabbitTemplate;
public void send() {
String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String context = "hello " + date;
System.out.println("Sender : " + context);
//简单对列的情况下routingKey即为Q名
this.rabbitTemplate.convertAndSend("q_hello", context);
}
}
四、消息消费者
package com.example.rabbitmq.Receiver;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* 消息消费者
*/
@Component
@RabbitListener(queues = "q_hello")
public class HelloReceiver {
@RabbitHandler
public void process(String hello) {
System.out.println("Receiver : " + hello);
}
}
五、消息触发
package com.example.rabbitmq.controller;
import com.example.rabbitmq.Sender.HelloSender;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class RabbitmqController {
@Autowired
private HelloSender helloSender;
@RequestMapping("test")
public String hello(){
helloSender.send();
return "hello";
}
}
六、参考鸣谢
https://blog.csdn.net/hellozpc/article/details/81436980