springboot整合rabbitMQ
一、依赖
<!--rabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
二、相关配置
application.yml
spring:
# rabbitMQ配置
rabbitmq:
host: 39.97.123.123
port: 5672
virtual-host: my_vhost #虚拟主机(相当于mysql的数据库库名)
username: amdin
password: admin
三、配置文件
RabbitMQConfig
package com.jinv.studentinfo.config;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: jinv
* @CreateTime: 2020-06-12 09:41
* @Description: RabbitMQ配置类
*/
@Configuration
public class RabbitMQConfig {
//交换机名称
public static final String ITEM_TOPIC_EXCHANGE="item_topic_exchange";
//队列名称
public static final String ITEM_QUEUE="item_queue";
//声明交换机
@Bean("itemTopicExchange")
public Exchange topicExchange(){
return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
}
//声明队列
@Bean("itemQueue")
public Queue itemQueue(){
return QueueBuilder.durable(ITEM_QUEUE).build();
}
//绑定队列和交换机
@Bean
public Binding itemQueueExchange(@Qualifier("itemQueue")Queue queue,
@Qualifier("itemTopicExchange")Exchange exchange){
return BindingBuilder.bind(queue).to(exchange).with("item.#").noargs();
}
}
生产者
Controller
RabbitMQController
package com.jinv.studentinfo.web;
import com.jinv.studentinfo.config.RabbitMQConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* @Author: jinv
* @CreateTime: 2020-06-12 09:55
* @Description: 测试rabbitMQ的controller
*/
@RestController
public class RabbitMQController {
@Autowired
private RabbitTemplate rabbitTemplate; //注入rabbitMQ的模板
@GetMapping("/sendmsg")
public String sendMsg(@RequestParam String msg,@RequestParam String key){
/**
* 发送消息
* 参数1:交换机名称
* 参数2:路由key
* 参数3:发送的消息
*/
rabbitTemplate.convertAndSend(RabbitMQConfig.ITEM_TOPIC_EXCHANGE,key,msg);
System.out.println("发送消息成功!");
return "发送消息成功!";
}
}
测试:
生产者测试成功!
消费者
Mylistener监听类
package com.jinv.studentinfo.consumer;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
/**
* @Author: jinv
* @CreateTime: 2020-06-12 11:31
* @Description: rabbitMQ消费者监听类
*/
@Component
public class Mylistener {
@RabbitListener(queues = "item_queue")
public void msg(String msg){
System.out.println("消费者消费了消息:"+msg);
}
}
启动测试
再用生产者生产消息,看是否依然能监听到
监听成功
其实生产者和消费者不应该在同一个工程里(这里图快捷方便),后期应该应用在分布式——生产者模块和消费者模块