RabbitMQ基本使用
1、配置application.yml
spring:
rabbitmq:
host: localhost
username: guest
password: guest
port: 5672
virtual-host: /
2、添加基于注解的RabbitMQ
/**
* 自动配置
* 1、RabbitAutoConfiguration
* 2、有自动配置了连接工厂ConnectionFactory;
* 3、RabbitProperties 封装了 RabbitMQ的配置
* 4、 RabbitTemplate :给RabbitMQ发送和接受消息;
* 5、 AmqpAdmin : RabbitMQ系统管理功能组件;
* AmqpAdmin:创建和删除 Queue,Exchange,Binding
* 6、@EnableRabbit + @RabbitListener 监听消息队列的内容
*
* @author nicemoe
*/
//基于注解的RabbitMQ模式
@EnableRabbit
@SpringBootApplication
public class AmqpApplication {
public static void main(String[] args) {
SpringApplication.run(AmqpApplication.class, args);
}
}
3、测试类测试
@RunWith(SpringRunner.class)
@SpringBootTest
class AmqpApplicationTests {
@Autowired
RabbitTemplate rabbitTemplate;
@Autowired
AmqpAdmin amqpAdmin;
@Test
public void createExchange(){
//amqpAdmin.declareExchange(new DirectExchange("amqpadmin.exchange"));
//System.out.println("创建完成");
//amqpAdmin.declareQueue(new Queue("amqpadmin.queue",true));
//创建绑定规则
//amqpAdmin.declareBinding(new Binding("amqpadmin.queue", Binding.DestinationType.QUEUE,"amqpadmin.exchange","amqp.news",null));
//删除等等
//amqpAdmin.declareExchange(..);
}
/**
* 1、单播(点对点)
*/
@Test
public void contextLoads() {
//Message需要自己构造一个;定义消息体内容和消息头
//rabbitTemplate.send(exchage,routeKey,message);
//object默认当成消息体,只需要传入要发送的对象,自动序列化发送给rabbitmq;
//rabbitTemplate.convertAndSend(exchage,routeKey,object);
Map<String,Object> map = new HashMap<>();
map.put("msg","这是第一个消息");
map.put("data", Arrays.asList("helloworld",123,true));
//对象被默认序列化以后发送出去
rabbitTemplate.convertAndSend("exchange.direct","zyjblogs.news",/*map*/new Book("西游记","吴承恩"));
}
//接受数据,如何将数据自动的转为json发送出去
@Test
public void receive(){
Object o = rabbitTemplate.receiveAndConvert("zyjblogs.news");
System.out.println(o.getClass());
System.out.println(o);
}
/**
* 广播
*/
@Test
public void sendMsg(){
rabbitTemplate.convertAndSend("exchange.fanout","",new Book("红楼梦","曹雪芹"));
}
}
4、配置类
@Configuration
public class MyAMQPConfig {
/**
* 数据自动的转为json
* @return
*/
@Bean
public MessageConverter messageConverter(){
return new Jackson2JsonMessageConverter();
}
}
5、service层,配置监听
@Service
public class BookService {
@RabbitListener(queues = "zyjblogs.news")
public void receive(Book book){
System.out.println("收到消息:"+book);
}
@RabbitListener(queues = "zyjblogs")
public void receive02(Message message){
System.out.println(message.getBody());
System.out.println(message.getMessageProperties());
}
}
6、Book类
public class Book {
private String bookName;
private String author;
public Book() {
super();
}
public Book(String bookName, String author) {
super();
this.bookName = bookName;
this.author = author;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book{" +
"bookName='" + bookName + '\'' +
", author='" + author + '\'' +
'}';
}
}