官方网站:https://www.rabbitmq.com/
1、添加依赖(默认就是rabbitmq)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
2、在application.yml中添加配置
spring:
rabbitmq:
host: 192.168.121.38
username: zhangsan
password: 123456
virtual-host: /app
port: 5672
3、测试代码
消费者
@Component
public class Listener{
@RabbitListener(bindings = @QueueBinding(
value = @Queue(value = "queue",durable = "true"),
exchange = @Exchange(
value = "exchange",
ignoreDeclarationExceptions = "true",
type = ExchangeTypes.TOPIC
),
key = {"#.#}))
public void listen(String msg){
System.out.println("接收到消息: " + msg);
}
}
@Componet:类上的注解,注册到Spring容器
@RabbitListener:声明消费者方法
key后边的通配符:#表示匹配0或多个词,*号表示匹配不多不少恰好1个词
生产者
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MQDemo{
@Autowired
private AmqpTemplate amqpTemplate;
@Test
public void testSend() throws InterruptedException{
String msg = "hello world";
amqpTemplate.convertAndSend(exchange:"exchange",routingKey:"a.b",msg);
//等待10s后结束
Thread.sleep(millis:10000);
}
}