引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置配置文件
spring:
application:
name: springboot_rabbitmq
rabbitmq:
host: 10.15.0.9
port: 5672
username: ems
password: 123
virtual-host: /ems
由于springboot对rabbitmq进行了封装,所以我们直接可以在autoconfigure中找到配置文件的配置参数,然后在yml中进行编辑
第一种hello world模型使用
正常情况下我们需要创建两个boot项目,一个为消费者,一个为服务者
provider:触发事件进行消息发送
package com.example.springboot_rabbitmq_provider;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class aa {
@Autowired
private RabbitTemplate rabbitTemplate;
@RequestMapping("/hello")
public String contextLoads() {
rabbitTemplate.convertAndSend("hello","hello world");
// 生产端没有指定交换机只有routingKey和Object。
//消费方产生hello队列,放在默认的交换机(AMQP default)上。
//而默认的交换机有一个特点,只要你的routerKey的名字与这个
//交换机的队列有相同的名字,他就会自动路由上。
//生产端routingKey 叫hello ,消费端生产hello队列。
//他们就路由上了
return "hello world";
}
}
Consumer:进行消息的监听
package com.example.springboot_rabbitmq_consumer;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
// 生产端没有指定交换机只有routingKey和Object。
//消费方产生hello队列,放在默认的交换机(AMQP default)上。
//而默认的交换机有一个特点,只要你的routerKey的名字与这个
//交换机的队列有相同的名字,他就会自动路由上。
//生产端routingKey 叫hello ,消费端生产hello队列。
//他们就路由上了
@RabbitListener(queuesToDeclare = @Queue(value = "hello",))
public class HelloCustomer {
@RabbitHandler
public void receive1(String message){
System.out.println("message = " + message);
}
}
springboot中队列的声明在消费者中,所以先启动消费者进行消息监听,再启动生产者消息发送
后文为了方便我们采用Test以及java搭配测试(添加手动确认消息)
第二种work模型使用
provider:
package com.example.springboot_rabbitmq_consumer;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class SpringbootRabbitmqConsumerApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void contextLoads() {
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work", "hello work!");
}
}
}
Consumer:
package com.example.springboot_rabbitmq_consumer;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class WorkCustomer {
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receive1(String message){
System.out.println("work message1 = " + message);
}
@RabbitListener(queuesToDeclare = @Queue("work"))
public void receive2(String message){
System.out.println("work message2 = " + message);
}
}