1.在父工程 或 所有子工程 引入依赖
<!--AMQP依赖,包含RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>2.9.10</version>
</dependency>
2.docker启动rabbitMQ,并在所有需要用MQ的子工程yml中进行配置
spring:
rabbitmq:
host: localhost
port: 5672
virtual-host: /
username: root
password: 123456
listener:
simple:
prefetch: 3 #指消费者最多能预取的消息数,相当于先从mq中拿再慢慢处理,服务器的性能越高该数值越大
3.引入消息json序列化的bean到spring容器中
@SpringBootApplication
public class ConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(ConsumerApplication.class, args);
}
@Bean
public MessageConverter jsonConverter(){
return new Jackson2JsonMessageConverter();
}
}
4.创建消息体并开启序列化
@Data
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class MQObject implements Serializable {
int msg;
String code;
}
5.编写接受者
@Component
public class SpringRabbitListener {
//直接接收,一个消息只能消费一次
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueue(String msg) {
System.out.println("what receive is :"+msg);
}
//@RabbitListener 单注解直接创建并绑定交换机与队列和bindingKey
//广播接收,消息会被广播到每个队列,消息可重用
@RabbitListener(bindings = @QueueBinding(
//队列名
value = @Queue(name ="testFanout.queue"),
//交换机
exchange = @Exchange(name = "test.direct",type = ExchangeTypes.FANOUT)
))
public void listenFanoutQueue(String msg) {
System.out.println("what receive in testDirect.queue is :"+msg);
}
//DIRECT模式,指具有某令牌bindingKey的消息才会被接受
@RabbitListener(bindings = @QueueBinding(
//队列名
value = @Queue(name ="testDirect.queue2"),
//交换机
exchange = @Exchange(name = "test.direct",type = ExchangeTypes.DIRECT),
//bindingKey
key = {"red","yellow"}
))
public void listenDirectQueue2(String msg) {
System.out.println("what receive in testDirect.queue2 is :"+msg);
}
//TOPIC模式,指满足令牌规则的消息能被接受,#指任意字符串,*指单个字符
@RabbitListener(bindings = @QueueBinding(
//队列名
value = @Queue(name ="testTopic.queue1"),
//交换机
exchange = @Exchange(name = "test.topic",type = ExchangeTypes.TOPIC),
//bindingKey
key = {"china.#"}
))
public void listenTopicQueue1(String msg) {
System.out.println("what receive in testTopic.queue1 is :" + msg);
}
}
6.编写发送者
@Test
public void sendMessageToExchangeTopicObject() {
String exchangeName = "test.topic";
MQObject msg = new MQObject(1, "1001");
//routingKey指使消息具有某令牌
String routingKey = "japan.weather";
rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
}
7.开启服务器