消息生产端:
pom.xml
<!--1. 父工程依赖-->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.4.RELEASE</version>
</parent>
<dependencies>
<!--2. rabbitmq-->
<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>
resources目录下application.yml 文件
# 配置RabbitMQ的基本信息 ip 端口 username password..
spring:
rabbitmq:
host: 172.16.98.133 # ip
port: 5672
username: guest
password: guest
virtual-host: /
创建交换机,队列,设置绑定的配置类
@Configuration
public class RabbitMQConfig {
public static final String EXCHANGE_NAME = "boot_topic_exchange";
public static final String QUEUE_NAME = "boot_queue";
//1.交换机
@Bean("bootExchange")
public Exchange bootExchange(){
// 需要什么类型就 . 什么类型,传入交换机名称
// 是否持久化,其他设置可以 一直链式编程 . 调用,最后build 方法返回
return ExchangeBuilder.topicExchange(EXCHANGE_NAME).durable(true).build();
}
//2.Queue 队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(QUEUE_NAME).build();
}
//3. 队列和交互机绑定关系 Binding
/*基于队列绑定交换机,noargs不传入参数。with 路由规则
1. 知道哪个队列
2. 知道哪个交换机
3. routing key
*/
@Bean
public Binding bindQueueExchange(@Qualifier("bootQueue") Queue queue, @Qualifier("bootExchange") Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
springBoot测试类:
@SpringBootTest
@RunWith(SpringRunner.class)
public class ProducerTest {
//1.注入RabbitTemplate,导入依赖自动创建并注入
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSend(){
//交换机名称,路由规则,消息对象
rabbitTemplate.convertAndSend(RabbitMQConfig.EXCHANGE_NAME,"boot.haha","boot mq hello~~~");
}
}
消息消费端:
pom.xml
<!--RabbitMQ 启动依赖-->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
resources目录下application.yml 文件
# 配置RabbitMQ的基本信息 ip 端口 username password..
spring:
rabbitmq:
host: 172.16.98.133 # ip
port: 5672
username: guest
password: guest
virtual-host: /
自定义监听类:
package com.xst.consumerspringboot;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
public class RabbimtMQListener {
//定义监听的 回调函数方法,参数为监听的消息队列名称
@RabbitListener(queues = "boot_queue")
public void ListenerQueue(Message message, Channel channel){
//System.out.println(message);
System.out.println(new String(message.getBody()));
}
}
springBoot启动类:
@SpringBootApplication
public class ConsumerSpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerSpringbootApplication.class, args);
}
}