Rabbitmq 与springboot 总结文档
依赖
<!-- 引入rabbitmq-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
rabbit使用
@SpringBootTest
class RabbitmqcoulApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
//hello模式 不经过交换机
@Test
void contextLoads() {
//此方法可以把object转换为message对象
Map<String,Object> map=new HashMap<>();
map.put("msg","这是第一个消息");
map.put("data", Arrays.asList("hello",123,true));
rabbitTemplate.convertAndSend("hello",map);
}
//work模式 不经过交换机
@Test
void worktest(){
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend("work","work word");
}
}
@Test
//fanout 广播
public void testFanout(){
rabbitTemplate.convertAndSend("logs","","发送的消息");
}
@Test
//route路由模式
public void testRoute(){
rabbitTemplate.convertAndSend("directs","error","发送info的key的路由信息");
}
@Test
//订阅
public void testTopic(){
rabbitTemplate.convertAndSend("topics","user.sa","topics info");
}
}
hello
@Component
@RabbitListener(queuesToDeclare = @Queue("hello"))
public class Helloword {
@RabbitHandler
public void receivel(Map msg){
System.out.println(msg);
}
}
Work
@Component
public class Worktest {
@RabbitListener(queuesToDeclare = @Queue("work"))
public void work1(String s){
System.out.println("work1 = "+s);
}
@RabbitListener(queuesToDeclare = @Queue("work"))
public void work2(String s){
System.out.println("work2 = "+s);
}
}
Fanout
@Component
public class FanoutCustomer {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//创建临时队列
exchange = @Exchange(value = "logs",type = "fanout"))
})
public void receivel(String s){
System.out.println("15"+s);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,//创建临时队列
exchange = @Exchange(value = "logs",type = "fanout"))
})
public void receivel2(String s){
System.out.println("2"+s);
}
}
Route
@Component
public class RouteConsumer {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "directs",type = "direct"),//指定交换机名称与类型
key = {"info","error","warn"}
)
})
public void receive1(String msg){
System.out.println("info,error,warn"+msg);
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(value = "directs",type = "direct"),//指定交换机名称与类型
key = {"error"}
)
})
public void receive2(String msg){
System.out.println("error"+msg);
}
}
Topics
@Component
public class TopicsConsumer {
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic",name = "topics"),
key = {"order.#","product.#","user.*"}
)
})
public void recevel(String msg){
System.out.println(msg+"topic1");
}
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue,
exchange = @Exchange(type = "topic",name = "topics"),
key = {"user.save","product.*"}
)
})
public void recevel1(String msg){
System.out.println(msg+"topic2");
}
}