生产者
1.创建生产者spring boot工程
2.maven依赖坐标
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
3.配置文件yml
server:
port: 9001
spring:
rabbitmq:
host: 192.168.56.101
port: 5672
virtual-host: /ems
username: admin
password: admin
4.定义交换机,队列以及绑定关系配置类
@Configuration
public class RabbitmqConfig {
public static final String BOOT_EXCHANGE = "bootExchange";
public static final String BOOT_QUEUE = "bootQueue";
// 交换机
@Bean("bootExchange")
public Exchange bootExchange(){
return ExchangeBuilder.topicExchange(BOOT_EXCHANGE).durable(true).build();
}
// 队列
@Bean("bootQueue")
public Queue bootQueue(){
return QueueBuilder.durable(BOOT_QUEUE).build();
}
// 队列与交换机绑定
@Bean
public Binding binding(
@Qualifier("bootQueue") Queue queue,
@Qualifier("bootExchange") Exchange exchange
){
return BindingBuilder.bind(queue).to(exchange).with("boot.#").noargs();
}
}
5.注入RabbitmqTemplate,调用方法,发送消息
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRabbitmqProducerDemoApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void contextLoads() {
rabbitTemplate.convertAndSend(RabbitmqConfig.BOOT_EXCHANGE,"boot.xiaoming","你好,小明");
}
}
消费者
1.maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.配置文件yml
server:
port: 9002
spring:
rabbitmq:
host: 192.168.56.101
port: 5672
virtual-host: /ems
username: admin
password: admin
3.消费者
@Component
public class RabbitmqListener {
@RabbitListener(queues = "bootQueue")
public void receive(Message message){
System.out.println(message);
System.out.println(new String(message.getBody()));
}
}