1.在父工程中引入依赖
org.springframework.boot
spring-boot-starter-amqp
2.在application.yml中配置MQ服务器地址,连接MQ
spring:
rabbitmq:
host: 192.168.150.101 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: itcast # 用户名
password: 123321 # 密码
3.自动注入RabbitTemplate
rabbitTemplate.convertAndSend()来发送消息
convertAndSend(队列名,信息)
convertAndSend(交换机名,key,信息)
1.配置MQ地址,在接收类的application.yml中
spring:
rabbitmq:
host: 192.168.150.101 # 主机名
port: 5672 # 端口
virtual-host: / # 虚拟主机
username: itcast # 用户名
password: 123321 # 密码
2.创建接收类,并使用@Compant注解
//简单队列模型
@RabbitListener(queues = "simple.queue")
public void listenSimpleQueueMessage(String msg) throws InterruptedException {
System.out.println("spring 消费者接收到消息:【" + msg + "】");
}
//任务模型,让多个消费者共同消费队列中的消息,Work queues
@RabbitListener(queues = "simple.queue")
public void listenWorkQueue1(String msg) throws InterruptedException {
System.out.println("消费者1接收到消息:【" + msg + "】" + LocalTime.now());
Thread.sleep(20);
}
......
//Fanout,广播
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "fanout.queue1"),
exchange = @Exchange(name = "fanoutEX",type = ExchangeTypes.FANOUT)))
public void listenFanoutQueue1(String msg){
System.out.println("fanout.queue1接收到的信息为:"+msg);
}
......
//Direct,可以指定要发给哪一个
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "itcast.direct", type = ExchangeTypes.DIRECT),
key = {"red", "blue"}
))
public void listenDirectQueue1(String msg){
System.out.println("消费者接收到direct.queue1的消息:【" + msg + "】");
}
......
//Topic,在Direct的基础上key加了通配符的功能
@RabbitListener(bindings = @QueueBinding(
value = @Queue(name = "topic.queue1"),
exchange = @Exchange(name = "itcast.topic", type = ExchangeTypes.TOPIC),
key = "china.#"
))
public void listenTopicQueue1(String msg){
System.out.println("消费者接收到topic.queue1的消息:【" + msg + "】");
}
......
3.任务模型需要在配置文件中配置
spring:
rabbitmq:
listener:
simple:
prefetch: 1 # 每次只能获取一条消息,处理完成才能获取下一个消息
4.Topic的key的通配符功能,key由一个或多个单词构成,用","隔开,#匹配一个或多个词,*只匹配一个词,注意:是词
默认情况下Spring采用的序列化方式是JDK序列化。众所周知,JDK序列化存在下列问题:
数据体积过大
有安全漏洞
可读性差
因此在接收端和发送端最好使用定义的统一的格式来,先引入依赖
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.9.10
在启动类中添加一个Bean
@Bean
public MessageConverter jsonMessageConverter(){
return new Jackson2JsonMessageConverter();
}