springboot服务简单使用rabbitmq消息队列,以下是基本使用流程
一、引入依赖
<!--集成消息队列-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
二、配置信息
在application.properties或者application.yml中添加配置信息
spring:
rabbitmq:
host: 127.0.0.1
port: 5672
username: admin
password: admin
消息队列注册配置类,分别注册队列(queue)、交换机(exchange)、绑定(绑定队列和交换机)Bean;
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
/** 队列名 */
public final static String DM_RECEIVE_QUEUE = "test_queue";
/** 交换机 */
public final static String DM_RECEIVE_EXCHANGE = "test.exchange";
/** 通过routeKey把队列和交换机绑定 */
public final static String DM_RECEIVE_ROUTE_KEY = "test.routeKey";
/** 申请一个队列 */
@Bean
public Queue dmReceiveQueue(){
return new Queue(RabbitMQConfig.DM_RECEIVE_QUEUE);
}
/** 申请一个交换机,交换机类型选择DirectExchange,类型区别自行百度 */
@Bean
public DirectExchange dmReceiveExchange(){
return new DirectExchange(DM_RECEIVE_EXCHANGE);
}
/** 绑定队列和交换机 */
@Bean
public Binding binding(){
return BindingBuilder.bind(dmReceiveQueue()).to(dmReceiveExchange()).with(DM_RECEIVE_ROUTE_KEY);
}
}
交换机常用的类型有fanout、direct、topic三种
1.fanout:不做任何匹配,把消息发送给所有绑定到交换机上的队列中,不需要key绑定;
2.direct:完全匹配匹配routeKey,通过routeKey把queue和exchange绑定一起,发送消息也指定routeKey,消息才能被绑定的queue接收;
3.topic:模糊匹配routeKey,routeKey通常是以“.”连接多个单词,支持"*"和"#"两种通配符,"*"匹配单个单词,"#"匹配一个或多个单词:
三、消息生产者
可以在业务需要的地方直接注入RabbitTemplate,直接使用对象方法convertAndSend()发送消息;
rabbitTemplate.convertAndSend(exchange, routeKey, value);
四、消息消费者
如果消息需要在不同项目中进行消费,那么消费者项目也需要跟(二、配置信息)同样的配置;
创建消费者
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class RabbitConsumer {
/** 监听"test_queue"队列,参数为消息的内容,可以为具体的类型,和发送者的消息类型一致 */
@RabbitListener(queues = "test_queue")
public void queueListener(Object object){
/**
* 具体的业务代码
*/
}
}