1.引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2. 配置RabbitMQ连接
在application.properties或application.yml中配置RabbitMQ服务器的连接参数:
3.创建一个消费者(DirectExchange)
package com.by.consumer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 消费者
@Configuration
public class DirectConsumer {
// 注册一个队列
@Bean // 启动的时候,它会根据这个Direct_Q1去找有没有这个队列,如果有什么都不做,没有则新建
public Queue queue(){
return QueueBuilder.durable("Direct_Q1").maxLength(100).build();
}
// 注册交换机
@Bean
public DirectExchange exchange(){
// 同理 有则不动,无则新建
return ExchangeBuilder.directExchange("Direct_E1").build();
}
// 绑定交换机和队列关系
@Bean
public Binding binding(Queue queue,DirectExchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("RK1");
}
//启动一个消费者
@RabbitListener(queues = "Direct_Q1")
public void receiveMessage(String msg){
System.out.println("消费者1收到消息"+msg);
}
}
随后启动启动类就会生成Exchanges、Queues及二者的绑定关系,有routingKey来连接
4.创建一个生产者
package com.by.provider;
import com.by.moder.RegisterOk;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
// 生产者
@Component
public class DirectProvider {
@Autowired
private RabbitTemplate rabbitTemplate;
public void send (String message){
rabbitTemplate.convertAndSend("Direct_E1","RK1",message);
}
}
5.测试
@SpringBootTest
class AppTests {
@Autowired
DirectProvider directProvider;
@Test
void Test1() {
for (int i = 1; i <=5; i++) {
RegisterOk build = RegisterOk.builder().id(i).name("杨" + i).build();
String s = JSONUtil.toJsonStr(build);
System.out.println("生产了"+i);
directProvider.send(s);
}
}
}