一開始我對「用 RabbitMQ 做 RPC」是存疑的。它的好處是能跨語言,整體流程也不複雜:靠 RabbitMQ 的事務確認訊息已被處理完畢,再透過 reply 佇列把結果送回。但總覺得哪裡不太對勁。兩個疑點:一是分散式事務該怎麼收斂(留待談 Spring 與 JPA 時再說);二是我當時沒想通的——如何做到多執行緒並發。
疑問來自 RabbitMQ 的投遞機制:訊息在未被 ack 之前不會繼續分發,同一時間只能處理一條,等於處理是線性的。而 Web 程式正好相反,Servlet 每次被呼叫都會開一條執行緒去跑 service 或 dao,是非線性的。總不能使用者 A 呼叫完,使用者 B 就卡在那裡排隊吧?
當時想到兩種解法:把 auto_ack 設為 open 後每次收到訊息就開新執行緒處理;或者多開幾個 channel 形成多個消費者。於是我決定動手驗證,並把過程記錄下來。
與一般的生產/訂閱模式相比,RPC 只多了一件事:需要把處理結果送回。也就是讓 client 送出訊息後進入等待,直到結果返回才繼續後續流程。
官方流程圖把整個過程講得很清楚:
官方 summary 的要點:
Client:
package com.maxfunner.rpc;
import com.rabbitmq.client.*;
import org.apache.commons.lang.SerializationUtils;
import java.io.IOException;
import java.util.UUID;
public class Client {
public String sayHelloToServer(String username) throws IOException, InterruptedException {
String exchangeName = "rpc_exchange"; // 交換器名稱
String queueName = "rpc_queue"; // 佇列名稱
String routingKey = "rpc_key"; // 路由鍵
ConnectionFactory factory = new ConnectionFactory();
factory.setVirtualHost("test");
factory.setHost("192.168.0.21");
factory.setPort(5673);
factory.setUsername("tony");
factory.setPassword("tonypwd");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchangeName, "direct", false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey, null);
String callbackQueue = channel.queueDeclare().getQueue(); // 匿名獨立佇列
String correlationId = UUID.randomUUID().toString(); // 關聯 ID
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(callbackQueue, true, consumer);
AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
.correlationId(correlationId)
.replyTo(callbackQueue).build();
channel.basicPublish(exchangeName, routingKey, basicProperties,
SerializationUtils.serialize(username));
String response = null;
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
if (correlationId.equals(delivery.getProperties().getCorrelationId())) {
response = (String) SerializationUtils.deserialize(delivery.getBody());
break;
}
}
channel.close();
connection.close();
return response;
}
public static void main(String[] args) throws IOException, InterruptedException {
Client client = new Client();
String response = client.sayHelloToServer("TONY");
System.out.println("server response : " + response);
}
}
Server:
package com.maxfunner.rpc;
import com.rabbitmq.client.*;
import org.apache.commons.lang.SerializationUtils;
import java.io.IOException;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
String exchangeName = "rpc_exchange";
String queueName = "rpc_queue";
String routingKey = "rpc_key";
ConnectionFactory factory = new ConnectionFactory();
factory.setVirtualHost("test");
factory.setHost("192.168.0.21");
factory.setPort(5673);
factory.setUsername("tony");
factory.setPassword("tonypwd");
Connection connection = factory.newConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare(exchangeName, "direct", false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String correlationID = delivery.getProperties().getCorrelationId();
String replyTo = delivery.getProperties().getReplyTo();
String body = (String) SerializationUtils.deserialize(delivery.getBody());
String responseMsg = "welcome " + body;
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
.correlationId(correlationID).build();
channel.basicPublish("", replyTo, properties,
SerializationUtils.serialize(responseMsg));
}
}
}
執行結果:
server response : welcome TONY
Process finished with exit code 0
我原先擔心兩個點:
結果證明我想多了。auto_ack 設 true 沒問題,關鍵在於每個 channel 呼叫 queueDeclare() 得到的匿名佇列 routingKey 都不一樣:
public class Client {
private static Connection connection = null;
private static ConnectionFactory factory = null;
public Connection getConnection() throws IOException {
if (connection == null) {
factory = new ConnectionFactory();
factory.setVirtualHost("test");
factory.setHost("192.168.0.21");
factory.setPort(5673);
factory.setUsername("tony");
factory.setPassword("tonypwd");
connection = factory.newConnection();
}
return connection;
}
public String sayHelloToServer(String username) throws IOException, InterruptedException {
String exchangeName = "rpc_exchange";
String queueName = "rpc_queue";
String routingKey = "rpc_key";
Channel channel = getConnection().createChannel();
channel.exchangeDeclare(exchangeName, "direct", false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey, null);
String callbackQueue = channel.queueDeclare().getQueue();
String correlationId = UUID.randomUUID().toString();
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(callbackQueue, true, consumer);
AMQP.BasicProperties basicProperties = new AMQP.BasicProperties.Builder()
.correlationId(correlationId)
.replyTo(callbackQueue).build();
channel.basicPublish(exchangeName, routingKey, basicProperties,
SerializationUtils.serialize(username));
String response = null;
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
System.out.println("delivery >>>>[user:" + username + "] >> routingKey : " + callbackQueue);
if (correlationId.equals(delivery.getProperties().getCorrelationId())) {
response = (String) SerializationUtils.deserialize(delivery.getBody());
break;
}
}
channel.close();
return response;
}
public static void main(String[] args) throws IOException, InterruptedException {
List<String> usernameList = new ArrayList<String>();
usernameList.add("TONY_A");
usernameList.add("TONY_B");
usernameList.add("TONY_C");
usernameList.add("TONY_D");
usernameList.add("TONY_E");
usernameList.add("TONY_F");
usernameList.add("TONY_G");
for (int i = 0; i < usernameList.size(); i++) {
final String username = usernameList.get(i);
new Thread(new Runnable() {
public void run() {
Client client = new Client();
String response = null;
try {
response = client.sayHelloToServer(username);
} catch (IOException e) {
e.printStackTrace();
response = "ERROR!!!";
} catch (InterruptedException e) {
e.printStackTrace();
response = "ERROR!!!";
}
System.out.println("server response : " + response);
}
}).start();
}
}
}
執行後可以看到每個 channel 拿到的匿名佇列 routingKey 都不同:
delivery >>>>[user:TONY_A] >> routingKey : amq.gen-8IIKmpbatOaxi4qpk2iq1g
server response : welcome TONY_A
delivery >>>>[user:TONY_F] >> routingKey : amq.gen-DoLdGmIjpyQ58rDM1S-0Bw
server response : welcome TONY_F
delivery >>>>[user:TONY_D] >> routingKey : amq.gen-Xa-fQW2uUXuwcp9PXI8gzg
server response : welcome TONY_D
所以並發沒有問題。若還想讓 server 端真正平行處理,把業務丟進新執行緒即可:
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
String exchangeName = "rpc_exchange";
String queueName = "rpc_queue";
String routingKey = "rpc_key";
ConnectionFactory factory = new ConnectionFactory();
factory.setVirtualHost("test");
factory.setHost("192.168.0.21");
factory.setPort(5673);
factory.setUsername("tony");
factory.setPassword("tonypwd");
final Connection connection = factory.newConnection();
final Channel channel = connection.createChannel();
channel.exchangeDeclare(exchangeName, "direct", false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey, null);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName, true, consumer);
while (true) {
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
final String correlationID = delivery.getProperties().getCorrelationId();
final String replyTo = delivery.getProperties().getReplyTo();
final String body = (String) SerializationUtils.deserialize(delivery.getBody());
new Thread(new Runnable() {
public void run() {
Channel channel = null;
try {
channel = connection.createChannel();
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
String responseMsg = "welcome " + body;
AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder()
.correlationId(correlationID).build();
try {
channel.basicPublish("", replyTo, properties,
SerializationUtils.serialize(responseMsg));
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
}
這裡只是最樸素的開執行緒寫法,實務上當然可以換成執行緒池來處理效能問題。RabbitMQ 的 RPC 就聊到這裡。