起步依赖
<!--rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
配置
spring:
rabbitmq:
host: localhost
port: 5672
username: guest
password: guest
virtual-host: /
?测试
//创建交换机 主题模式
@Bean
public TopicExchange topicExchange(){
return new TopicExchange("topic_exchange_springcloud1");
}
//创建队列
@Bean
public Queue queue(){
return new Queue("queue_springcloud1");
}
//创建绑定
@Bean
public Binding binding(){
//将指定的队列绑定给指定的交换机 ,
return BindingBuilder.bind(queue()).to(topicExchange()).with("item.*");
}
package com.example;
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 Day45SpringcloudRabbitmqApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void sendMesssage() {
rabbitTemplate.convertAndSend("topic_exchange_springcloud1","item.insert","哈哈哈");
//测试
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
消费者
package com.example.listenner;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class Consumer {
//@RabbitListener 监听某个队列
@RabbitListener(queues = "queue_springcloud1")
public void msg(String msg){
System.out.println(msg);
}
}
|