一:maven中引入rabbitmq
<!--RabbitMQ-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
二:创建MQConfig---用于创建交换机--创建Queue---创建Queue和交换机的绑定
/**
* RabbitMQ配置
*/
@Configuration
public class MQConfig {
/**
* 定义队列--用于rpc响应queue
* @return
*/
@Bean
public Queue scanCodeResQueue() {
//参数说明:1.队列名称,2.队列是否持久化,3.队列是否排他,4.队列是否自动删除
return new Queue("queue的名称", false, true, true);
}
/**
* 定义交换机
* @return
*/
@Bean
TopicExchange topicExchange() {
return new TopicExchange("交换机名称");
}
/**
* 将队列与交换机绑定
* @return
*/
@Bean
public Binding binding_db_parking() {
//链式写法: 用指定的路由键将队列绑定到交换机
Binding binding = BindingBuilder.bind(scanCodeResQueue()).to(topicExchange()).with("规则key");//*.xxx.#--*代表一个#任意个
return binding;
}
}
三:定义一个发送者
/**
* RabbitMQ发送
* ConfirmCallback接口用于实现消息发送到RabbitMQ交换器后接收ack回调。
* ReturnCallback接口用于实现消息发送到RabbitMQ交换器,但无相应队列与交换器绑定时的回调。
*/
@Component
public class Sender {
private static Logger logger = LoggerFactory.getLogger(Sender.class);
@Autowired
private RabbitTemplate rabbitTemplate;
/**
* RPC请求
*/
public void sendRpcFindProcessingWordOrder(){
logger.info("Sender发送请求);
CorrelationData correlationData = new CorrelationData();
// 发送数据
JSONObject rpc_obj = new JSONObject();
rpc_obj.put("a", "123");
// 设置属性:
MessageProperties properties = new MessageProperties();
properties.setReplyTo("指定结果返回到哪个queue中");//将返回的数据, 存放到对应的queue中.
properties.setCorrelationId(correlationData.getId());//设置ID, 用于数据存储的主键.
Message message = new Message(rpc_obj.toJSONString().getBytes(), properties);
//往交换机发消息--以routingKey发送--绑定了对应key的queue就能收到信息
rabbitTemplate.send("交换机名称", "routingKey", message);
}
}
四:定义接收者
@Component
public class Receiver {
/**
* 接收rpc请求并返回
* @param message
*/
@RabbitListener(queues = "queues")
public String scanCodeRPCListener(Message message){
//将byte数组转string类型
String content = new String(message.getBody());
String correlationId = message.getMessageProperties().getCorrelationId();
return "success";
}
说明:该接收者是接收rpc的请求--处理完请求将返回结果直接return,rabbitmq会把这个return的返回结果放到当时发送时指定的queue里。只要发送者再监听对应的queue就能取到对应的返回值。