本文轉載自【微信公眾號:java進階架構師,ID:java_jiagoushi】經微信公眾號授權轉載,如需轉載與原文作者聯繫
public Object convertSendAndReceive(final String routingKey, final Object message) throws AmqpException {
return this.convertSendAndReceive(this.exchange, routingKey, message, null);
}
spring整合Rabbit MQ提供了Reply來實現RPC,AMQP協議定義了14中消息的屬性,其中兩項,一項是Replyto,表示返回消息的隊列,一個是correlationId 用來表示發送消息和返回消息的標誌,來區分是否是一個調用
下面一步步來實現RPC
首先貼出spring配置文件代碼
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:prpc="http://www.pinnettech.com/schema/rpc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.pinnettech.com/schema/rpc
http://www.pinnettech.com/schema/springtag.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit-1.0.xsd">
<context:component-scan
base-package="com.temp.rabbit">
</context:component-scan>
<!-- rabbit消息發送方 -->
<!-- 連接服務配置 如果MQ伺服器在遠程伺服器上,請新建用戶用新建的用戶名密碼 guest默認不允許遠程登錄-->
<rabbit:connection-factory id="rabbitConnectionFactory" host="localhost" username="dengwei" password="dengwei"
port="5672" virtual-host="/" channel-cache-size="5"/>
<rabbit:admin connection-factory="rabbitConnectionFactory"/>
<!-- 發送消息可以帶*,綁定關係需全單詞 -->
<rabbit:direct-exchange name="rpc.bao.direct.goods" durable="true" auto-delete="false">
<rabbit:bindings>
<rabbit:binding queue="rpc.bao.goods" key="dengwei.goods"/>
</rabbit:bindings>
</rabbit:direct-exchange>
<!-- durable是否持久化 exclusive:是否排外的-->
<rabbit:queue durable="true" auto-delete="false" exclusive="false" name="rpc.bao.goods"/>
<!-- 消息轉換器 -->
<bean id="byteMessageConverter"/>
<!-- 發送消息模板 -->
<rabbit:template id="amqTemplate" exchange="rpc.bao.direct.goods"
connection-factory="rabbitConnectionFactory" message-converter="byteMessageConverter" />
<!-- 消息發送方 end -->
<!-- 消息接受方處理器 -->
<bean id="msgHandler"/>
<!-- 消息消費者 -->
<bean id="msgLisenerAdapter">
<constructor-arg name="delegate" ref="msgHandler"/>
<constructor-arg name="messageConverter" ref="byteMessageConverter"/>
</bean>
<!-- 消費者容器 -->
<rabbit:listener-container connection-factory="rabbitConnectionFactory" acknowledge="auto">
<rabbit:listener queues="rpc.bao.goods" ref="msgLisenerAdapter"/>
</rabbit:listener-container>
<!-- 消息接收方 end -->
<!-- RPC 配置 -->
<!-- 消息服務提供接口實現 -->
<bean id="service1"/>
<!-- 代理類 -->
<bean id="service1Proxy">
<property name="t" ref="service1"></property>
</bean>
<!-- 代理對象 -->
<bean id="proxyService" factory-bean="service1Proxy" factory-method="getProxy"/>
</beans>
其中消息轉換器類
package com.temp.rabbit;import org.springframework.amqp.core.Message;import org.springframework.amqp.core.MessageProperties;import org.springframework.amqp.support.converter.AbstractJsonMessageConverter;import org.springframework.amqp.support.converter.MessageConversionException;import org.springframework.util.SerializationUtils;public class BytesMessageConverter extends AbstractJsonMessageConverter{@Overrideprotected Message createMessage(Object msg, MessageProperties msgPro) {byte[] data = SerializationUtils.serialize(msg);msgPro.setContentLength(data.length);System.out.println("create message "+msg.getClass());return new Message(data , msgPro);}@Overridepublic Object fromMessage(Message msg) throws MessageConversionException {byte[] data = msg.getBody() ;Object result = SerializationUtils.deserialize(data);System.out.println("create obj "+result.getClass());return result;}}
消費者處理handler
package com.temp.rabbit.receive;import java.lang.reflect.Method;import com.temp.rabbit.bean.RpcRequest;import com.temp.rabbit.bean.RpcResponse;import com.temp.rabbit.bean.TempServiceImp;public class MessageHandler {//沒有設置默認的處理方法的時候,方法名是handleMessagepublic RpcResponse handleMessage(RpcRequest message){Class<?> clazz = message.getClassName() ;RpcResponse response = new RpcResponse();Method method;try {method = clazz.getMethod(message.getMethodName(), message.getParamType());Object result = method.invoke(new TempServiceImp(), message.getParams());response.setResult(result);} catch (Exception e) {e.printStackTrace();}return response ;}}
服務提供:
package com.temp.rabbit.bean;public class TempServiceImp implements TempService {public String sayHello(){return "TempServiceImp hello ... " ;}}
代理類:
package com.temp.rabbit.receive.proxy;import java.io.Serializable;import java.lang.reflect.Method;import org.springframework.beans.factory.annotation.Autowired;import com.temp.rabbit.bean.RpcRequest;import com.temp.rabbit.bean.RpcResponse;import com.temp.rabbit.send.SendRabbitMsgImp;import net.sf.cglib.proxy.Enhancer;import net.sf.cglib.proxy.MethodInterceptor;import net.sf.cglib.proxy.MethodProxy;public class ServiceProxy<T> implements MethodInterceptor{private Enhancer enhancer = new Enhancer();private T t ;public void setT(T t){this.t = t ;}@Autowiredprivate SendRabbitMsgImp rabbitMsg ;public Object getProxy(){enhancer.setSuperclass(t.getClass());enhancer.setCallback(this);return enhancer.create();}@Overridepublic Object intercept(Object obj, Method method, Object[] param, MethodProxy proxy) throws Throwable {RpcRequest request = new RpcRequest();request.setMethodName(method.getName());request.setClassName(t.getClass());Class<?>[] paramType = new Class<?>[param.length];Serializable[] para = new Serializable[param.length];for(int i = 0 ; i < param.length ; i ++){paramType[i] = param[i].getClass();para[i] = (Serializable)param[i];}request.setParams(para);request.setParamType(paramType);RpcResponse result = (RpcResponse)rabbitMsg.sendAdcReceive("dengwei.goods", request) ;return result.getResult();}}
主程序
package com.temp;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import com.temp.rabbit.bean.TempService;public class Main {public static void main(String[] args) {ApplicationContext app = new ClassPathXmlApplicationContext("classpath:spring.xml");TempService proxy = (TempService)app.getBean("proxyService");System.out.println("main result " + proxy.sayHello()) ;}}
消息發送實現:
package com.temp.rabbit.send;import org.springframework.amqp.rabbit.core.RabbitTemplate;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Component;@Component("sendMsg")public class SendRabbitMsgImp implements SendRabbitMsg{@Autowiredprivate RabbitTemplate template ;@Overridepublic void sendData2Queue(String queueKey, Object msg) {try {template.convertAndSend(queueKey, msg);} catch (Exception e) {e.printStackTrace();System.out.println("send data 2 msg erro ");}System.out.println("消息已發送");}@Overridepublic Object sendAdcReceive(String queueKey , Object msg){try {return template.convertSendAndReceive(queueKey, msg);} catch (Exception e) {e.printStackTrace();System.out.println("send data 2 msg erro ");}System.out.println("消息已發送");return null ;}}
這裡面的RpcRequest和RpcResponse就不貼代碼了
這裡講一下原理實現,我們可以跟著源碼看一下
首先調用的是RabbitTemplate的
public Object convertSendAndReceive(final String routingKey, final Object message) throws AmqpException {return this.convertSendAndReceive(this.exchange, routingKey, message, null);}
然後一路走下去
@Overridepublic Object convertSendAndReceive(final String exchange, final String routingKey, final Object message,final MessagePostProcessor messagePostProcessor) throws AmqpException {Message requestMessage = convertMessageIfNecessary(message);if (messagePostProcessor != null) {requestMessage = messagePostProcessor.postProcessMessage(requestMessage);}Message replyMessage = this.doSendAndReceive(exchange, routingKey, requestMessage);if (replyMessage == null) {return null;}return this.getRequiredMessageConverter().fromMessage(replyMessage);}protected Message doSendAndReceive(final String exchange, final String routingKey, final Message message) {if (this.replyQueue == null) {return doSendAndReceiveWithTemporary(exchange, routingKey, message);}else {return doSendAndReceiveWithFixed(exchange, routingKey, message);}}
到這裡我們會看到,有一個分支如果replyqueue不為空則是走另外的一個方法,因為之前沒有設置replyqueue所以,這裡會
走第一步方法,也就是doSendAndReceiveWithTemporary
來看一下這個方法源碼
protected Message doSendAndReceiveWithTemporary(final String exchange, final String routingKey, final Message message) {return this.execute(new ChannelCallback<Message>() {@Overridepublic Message doInRabbit(Channel channel) throws Exception {final ArrayBlockingQueue<Message> replyHandoff = new ArrayBlockingQueue<Message>(1);Assert.isNull(message.getMessageProperties().getReplyTo(),"Send-and-receive methods can only be used if the Message does not already have a replyTo property.");DeclareOk queueDeclaration = channel.queueDeclare();String replyTo = queueDeclaration.getQueue();message.getMessageProperties().setReplyTo(replyTo);String consumerTag = UUID.randomUUID().toString();DefaultConsumer consumer = new DefaultConsumer(channel) {@Overridepublic void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties,byte[] body) throws IOException {MessageProperties messageProperties = messagePropertiesConverter.toMessageProperties(properties, envelope, encoding);Message reply = new Message(body, messageProperties);if (logger.isTraceEnabled()) {logger.trace("Message received " + reply);}try {replyHandoff.put(reply);}catch (InterruptedException e) {Thread.currentThread().interrupt();}}};channel.basicConsume(replyTo, true, consumerTag, true, true, null, consumer);doSend(channel, exchange, routingKey, message, null);Message reply = (replyTimeout < 0) ? replyHandoff.take() : replyHandoff.poll(replyTimeout,TimeUnit.MILLISECONDS);channel.basicCancel(consumerTag);return reply;}});}
這裡流程就是申明一個大小為1的臨時隊列,然後發送消息,然後監聽返回的消息,放到臨時隊列,然後取出返回消息。
那麼因為每次都會創建臨時隊列,所以對性能是個考驗那麼有第二種方式,在rabbitmq中申明一個返回隊列,用來存放該服務的返回消息。
那麼需要在spring配置文件中配置一個reply隊列
<rabbit:queue durable="true" auto-delete="false" exclusive="false" name="reply"/>
然後在消息監聽容器中再配置一個發送消息的模板template為消費者
<!-- 消費者容器 --> <rabbit:listener-container connection-factory="rabbitConnectionFactory" acknowledge="auto"> <rabbit:listener queues="reply" ref="amqTemplate"/> <rabbit:listener queues="rpc.bao.goods" ref="msgLisenerAdapter"/> </rabbit:listener-container>
最後再發送消息的實現中即SendRabbitMsgImp類中注入隊列
@Autowired@Qualifier("reply")private Queue reply ;
然後設置template的replyqueue為reply ;template.setReplyQueue(reply);
這個設置代碼可以再初始化方法中,也可以再發送消息之前,其實最好的實在spring中設置
那麼該說原理了,我們可以看最開始發送消息的第二個方法
protected Message doSendAndReceive(final String exchange, final String routingKey, final Message message) {
if (this.replyQueue == null) {
return doSendAndReceiveWithTemporary(exchange, routingKey, message);
}
else {
return doSendAndReceiveWithFixed(exchange, routingKey, message);
}
}
protected Message doSendAndReceiveWithFixed(final String exchange, final String routingKey, final Message message) {
return this.execute(new ChannelCallback<Message>() {
@Override
public Message doInRabbit(Channel channel) throws Exception {
final PendingReply pendingReply = new PendingReply();
String messageTag = UUID.randomUUID().toString();
RabbitTemplate.this.replyHolder.put(messageTag, pendingReply);
// Save any existing replyTo and correlation data
String savedReplyTo = message.getMessageProperties().getReplyTo();
pendingReply.setSavedReplyTo(savedReplyTo);
if (StringUtils.hasLength(savedReplyTo) && logger.isDebugEnabled()) {
logger.debug("Replacing replyTo header:" + savedReplyTo
+ " in favor of template's configured reply-queue:"
+ RabbitTemplate.this.replyQueue.getName());
}
message.getMessageProperties().setReplyTo(RabbitTemplate.this.replyQueue.getName());
String savedCorrelation = null;
if (RabbitTemplate.this.correlationKey == null) { // using standard correlationId property
byte[] correlationId = message.getMessageProperties().getCorrelationId();
if (correlationId != null) {
savedCorrelation = new String(correlationId,
RabbitTemplate.this.encoding);
}
}
else {
savedCorrelation = (String) message.getMessageProperties()
.getHeaders().get(RabbitTemplate.this.correlationKey);
}
pendingReply.setSavedCorrelation(savedCorrelation);
if (RabbitTemplate.this.correlationKey == null) { // using standard correlationId property
message.getMessageProperties().setCorrelationId(messageTag
.getBytes(RabbitTemplate.this.encoding));
}
else {
message.getMessageProperties().setHeader(
RabbitTemplate.this.correlationKey, messageTag);
}
if (logger.isDebugEnabled()) {
logger.debug("Sending message with tag " + messageTag);
}
doSend(channel, exchange, routingKey, message, null);
LinkedBlockingQueue<Message> replyHandoff = pendingReply.getQueue();
Message reply = (replyTimeout < 0) ? replyHandoff.take() : replyHandoff.poll(replyTimeout,
TimeUnit.MILLISECONDS);
RabbitTemplate.this.replyHolder.remove(messageTag);
return reply;
}
});
}
這個方法並沒有申請臨時隊列,發送消息後直接再pendingReply中的隊列中取,那麼怎麼放到pendingReply的隊列中區的呢,可以看到,RabbitTemplate是實現了MessageLIstener,那麼看他實現的onMessage方法
public void onMessage(Message message) {try {String messageTag;if (this.correlationKey == null) { // using standard correlationId propertymessageTag = new String(message.getMessageProperties().getCorrelationId(), this.encoding);}else {messageTag = (String) message.getMessageProperties().getHeaders().get(this.correlationKey);}if (messageTag == null) {logger.error("No correlation header in reply");return;}PendingReply pendingReply = this.replyHolder.get(messageTag);if (pendingReply == null) {if (logger.isWarnEnabled()) {logger.warn("Reply received after timeout for " + messageTag);}}else {// Restore the inbound correlation dataString savedCorrelation = pendingReply.getSavedCorrelation();if (this.correlationKey == null) {if (savedCorrelation == null) {message.getMessageProperties().setCorrelationId(null);}else {message.getMessageProperties().setCorrelationId(savedCorrelation.getBytes(this.encoding));}}else {if (savedCorrelation != null) {message.getMessageProperties().setHeader(this.correlationKey,savedCorrelation);}else {message.getMessageProperties().getHeaders().remove(this.correlationKey);}}// Restore any inbound replyToString savedReplyTo = pendingReply.getSavedReplyTo();message.getMessageProperties().setReplyTo(savedReplyTo);LinkedBlockingQueue<Message> queue = pendingReply.getQueue();queue.add(message);if (logger.isDebugEnabled()) {logger.debug("Reply received for " + messageTag);if (savedReplyTo != null) {logger.debug("Restored replyTo to " + savedReplyTo);}}}}catch (UnsupportedEncodingException e) {throw new AmqpIllegalStateException("Invalid Character Set:" + this.encoding, e);}}
這裡就明白了,根據唯一id也就是前面說的correlationId找到消息的pendingReply,然後將返回的消息放到pendingReply的隊列中,這樣就實現了RPC的調用,