org.springframework.boot
spring-boot-starter-amqp
spring:
#RabbitMQ
rabbitmq:
#服务器地址和端口
host: 192.168.220.128
port: 5672
#账号和密码
username: admin
password: 123456 #
#虚拟主机,从控制台对应的账号下面找
virtual-host: /
@Configuration
public class RabbitConf {
@Bean //Queue包:import org.springframework.amqp.core.Queue;
public Queue queueT1(){
//public Queue(String name, boolean durable, boolean exclusive, boolean autoDelete)
//durable:是否持久化
//exclusive:默认false,只能在当前创建连接时使用,连接关闭后队列自动删除,该优先级高于durable
//autoDelete:是否自动删除,当没有生产者或消费者使用该交换机时,会自动删除
return new Queue("queue1");
}
}
@RestController
@RequestMapping("testRabbitMQ")
public class Producer {
@Autowired
private AmqpTemplate amqpTemplate;
@GetMapping
public String sendMSG(){
ResultObject resultObject = new ResultObject(100, "发送成功", "data...");
amqpTemplate.convertAndSend("queue1",resultObject);
return "发送成功";
}
}
@Component
public class Consumer {
@RabbitListener(queues = "queue1")
@RabbitHandler
public void receiveMsg(ResultObject resultObject){
System.out.println(resultObject);
}
}
以上是简单模式和工作模式,工作模式只需要创建多个消费者即可
注意:每个生产者都需要导包、配置文件、配置类,每个消费者需要导包、配置文件
/*订阅发布模式*/
@Bean
public Queue queue2(){
return new Queue("queue2");
}
//配置订阅模式交换机
@Bean
public FanoutExchange ex1(){
//public FanoutExchange(String name, boolean durable, boolean autoDelete)
// durable:是否持久化
//autoDelete:是否自动删除,当没有生产者或消费者使用该交换机时,会自动删除
return new FanoutExchange("ex1");
}
//绑定队列(需要发布多少个队列就绑定多少个队列)
@Bean
public Binding bindingQ2Ex1(Queue queue2,FanoutExchange ex1){
return BindingBuilder.bind(queue2).to(ex1);
}
@GetMapping("/test2")
public String sendMSG2(){
ResultObject resultObject = new ResultObject(100, "发送成功", "data...");
amqpTemplate.convertAndSend("ex1","",resultObject);
return "发送成功";
}
消费者不变
/*路由模式*/
@Bean
public Queue queue3(){
return new Queue("queue3");
}
@Bean
public Queue queue4(){
return new Queue("queue4");
}
//配置路由模式交换机
@Bean
public DirectExchange ex2(){
return new DirectExchange("ex2");
}
//绑定队列,将队列3绑定到路由交换机上并且设置key为key1
@Bean
public Binding bindingEx2Q3(Queue queue3,DirectExchange ex2){
return BindingBuilder.bind(queue3).to(ex2).with("key1");
}
//将队列4绑定到路由交换机上并且设置key为key2
@Bean
public Binding bindingEx2Q4(Queue queue4,DirectExchange ex2){
return BindingBuilder.bind(queue4).to(ex2).with("key2");
}
//路由模式发布消息
@GetMapping("/test3")
public String sendMSG3(){
amqpTemplate.convertAndSend("ex2","key1","发送到key为:key1的队列中");
amqpTemplate.convertAndSend("ex2","key2","发送到key为:key1的队列中");
return "发送成功";
}
消费者只需要消费对应队列即可