- 导入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
- 配置相关信息
spring:
rabbitmq:
host: # 你的虚拟机IP
port: 5672 # 端口
virtual-host: # 虚拟主机
username:# 用户名
password: # 密码
- 编写消费者及队列
package com.itheima.consumer.mq;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import java.time.LocalTime;
@Slf4j
@Component
public class SpringRabbitListener {
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1",durable = "true"),
exchange = @Exchange(name="c.direct",type = ExchangeTypes.DIRECT),
key = {"red","blue"}
))
public void listenDirectQueue1(String message){
System.err.println("消费者1.....接收到"+message+","+ LocalTime.now());
}
}
- 测试发送消息
@Test
public void testDirectQueue(){
String exchangeName="c.direct";
String message = "hello,everyone!";
rabbitTemplate.convertAndSend(exchangeName, "yellow" ,message);
}
改变默认的消息转换器
导入依赖
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.10</version>
</dependency>
编写配置
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}