首先导入坐标
使用 生产者:
package com.example.flyway;
import lombok.Data;
import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.amqp.RabbitTemplateConfigurer;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FlywayApplicationTests {
@Test
void contextLoads() {
}
@Autowired
protected RabbitTemplate rabbitTemplate;
@Test
public void test()
{
rabbitTemplate.convertAndSend("hello" , "hello world");
}
}
如果只有生产者去生产消息, 而没有消费者去消费消息, 那么rabbitmq不会创建队列。(重点) 因为没有消费者的队列时没有意义的。
当有消费者消费时, 队列才会被创建。
是基于消费者去创建交换机
package rabbitmq;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queuesToDeclare = @Queue("hello"))
public class Consumer {
@RabbitHandler
public void receivel(String message)
{
System.out.println("message = " + message);
}
}
广播模式 消费者端:
// 广播模式
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue, //创建一个临时队列 @Queue(value = "xxx" ) 创建一个具名队列
exchange = @Exchange(value = "交换机名称" , type="交换机类型" ) // fanout direct topic
)
})
public void receive2(String message)
{
System.out.println("message" + message);
}
动态路由 消费者端:
// 动态路由
@RabbitListener(bindings = {
@QueueBinding(
value = @Queue, //创建一个临时队列 @Queue(value = "xxx" ) 创建一个具名队列
exchange = @Exchange(value = "topic" , type="topic" ), // fanout direct topic
key = {"user.save" , "user.delete"}
)
})
public void receive3(String message)
{
System.out.println("message" + message);
}