生产者
package com.example.newrabbitmq;
import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@SpringBootTest( classes = NewRabbitMqApplication.class)
@RunWith( SpringRunner.class )
class NewRabbitMqApplicationTests {
@Autowired
private RabbitTemplate rabbitTemplate;
// 动态路由模式
@Test
void contextLoads5() {
rabbitTemplate.convertAndSend( "springboot_topic","user.info.age", "正在发送用户年龄消息");
rabbitTemplate.convertAndSend( "springboot_topic","user.phone", "正在发送用户手机号消息");
}
}
消费者
package com.example.newrabbitmq.serive;
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;
@Component
public class Customer5 {
@RabbitListener(
bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "springboot_topic", type = "topic"),
key = {"user.info.*"}
)
}
)
public void test1(String s) throws InterruptedException {
System.out.println( "消费者1 " + s);
}
@RabbitListener(
bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "springboot_topic", type = "topic"),
key = {"user.#"}
)
}
)
public void test2(String s) throws InterruptedException {
System.out.println( "消费者2 " + s);
}
}
运行截图