1,新建spring boot项目,过程百度
2,引入maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> <version>1.5.2.RELEASE</version> </dependency>
3,修改rabbitmq配置文件

4,新建direct配置类
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class DirectConfig {
@Bean
public Queue directQueue(){
return new Queue("direct",false); //队列名字,是否持久化
}
@Bean
public DirectExchange directExchange(){
return new DirectExchange("direct",false,false);//交换器名称、是否持久化、是否自动删除
}
@Bean
Binding binding(Queue queue, DirectExchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("direct");
5,新建消息发送类
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* 消息发送--生产消息
*/
@Component
public class Sender {
@Autowired
AmqpTemplate rabbitmqTemplate;
public void send(String message){
System.out.println("发送消息:"+message);
rabbitmqTemplate.convertAndSend("direct",message);
}
public void send2(String message){
System.out.println("发送消息:"+message);
rabbitmqTemplate.convertAndSend("direct2",message);
}
}
6,新建消息接收类
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "direct")
public class Receiver {
@RabbitHandler
public void handler(String message){
System.out.println("接收消息:"+message);
}
}
新建controller测试接口
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/rabbitmq")
public class MyRabbitmqController {
@Autowired
Sender sender;
@RequestMapping("/sender")
@ResponseBody
public String sender(){
System.out.println("send string:hello world");
sender.send("hello world");
return "sending...";
}
@RequestMapping("/sender2")
@ResponseBody
public String sender2(){
System.out.println("send string:hello world");
sender.send2("hello world2");
return "sending2...";
}
}
浏览器输入:http://localhost:8089/rabbitmq/sender

成功
来源:CSDN
作者:刘弘扬fine
链接:https://blog.csdn.net/qq_35101267/article/details/103464540