<!-- 父工程依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
1、rbbitmq配置
server:
port: 8080
spring:
rabbitmq:
host: 192.168.131.171
port: 5672
username: jihu
password: jihu
virtual-host: /jihu
2、队列和交换机配置:
@Configuration
public class RabbitMQConfig {
private static final String EXCHANGE_NAME = "exchange_boot_topic";
private static final String QUEUE_NAME = "boot_queue";
// 声明交换机
@Bean
public Exchange bootExchange() {
return ExchangeBuilder.fanoutExchange(EXCHANGE_NAME).durable(true).build();
}
// 声明队列
@Bean
public Queue bootQueue() {
return QueueBuilder.durable(QUEUE_NAME).build();
}
// 队列与交换机绑定
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
3、启动类
@SpringBootApplication
public class ProducerApplication {
public static void main(String[] args) {
SpringApplication.run(ProducerApplication.class);
}
}
@SpringBootTest
@RunWith(SpringRunner.class)
public class TestSendMsg {
private static final String EXCHANGE_NAME = "exchange_boot_topic";
private static final String QUEUE_NAME = "boot_queue";
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void send() {
rabbitTemplate.convertAndSend(EXCHANGE_NAME, "boot.test","boot exchange test ...");
}
}
此时我们来查看交换机和队列:
可以看到,交换机队列都已经创建成功!
<!-- 父工程依赖 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
1、rabbitmq配置
spring:
rabbitmq:
host: 192.168.131.171
port: 5672
username: jihu
password: jihu
virtual-host: /jihu
2、监听类
@Component
public class RabbitMQListener {
// 定义方法进行信息的监听
@RabbitListener(queues = "boot_queue") // 参数是队列名称
public void ListenerQueue(Message message) {
System.out.println("[消费者收到消息] " + message.toString());
}
}
3、启动类
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class);
}
}
我们来启动消费者。
因为我们上面的生产者已经向队列“boot_queue”中发送了一条消息,所以此时启动后应该可以直接读取到消息:
然后我们试着用生产者再发一条消息:
@Test
public void send2() {
rabbitTemplate.convertAndSend(EXCHANGE_NAME, "boot.test","boot exchange test2 ...");
}