Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 RabbitMQ 實現 RPC:原理、範例與並發處理的坑

一開始我對「用 RabbitMQ 做 RPC」是存疑的。它的好處是能跨語言,整體流程也不複雜:靠 RabbitMQ 的事務確認訊息已被處理完畢,再透過 reply 佇列把結果送回。但總覺得哪裡不太對勁。兩個疑點:一是分散式事務該怎麼收斂(留待談 Spring 與 JPA 時再說);二是我當時沒想通的——如何做到多執行緒並發。

疑問來自 RabbitMQ 的投遞機制:訊息在未被 ack 之前不會繼續分發,同一時間只能處理一條,等於處理是線性的。而 Web 程式正好相反,Servlet 每次被呼叫都會開一條執行緒去跑 service 或 dao,是非線性的。總不能使用者 A 呼叫完,使用者 B 就卡在那裡排隊吧?

當時想到兩種解法:把 auto_ack 設為 open 後每次收到訊息就開新執行緒處理;或者多開幾個 channel 形成多個消費者。於是我決定動手驗證,並把過程記錄下來。

RPC 在 RabbitMQ 上的運作原理

與一般的生產/訂閱模式相比,RPC 只多了一件事:需要把處理結果送回。也就是讓 client 送出訊息後進入等待,直到結果返回才繼續後續流程。

官方流程圖把整個過程講得很清楚:

  1. client 送出訊息時帶上唯一的 correlation_id,並在 reply_to 中指定一個獨立佇列(官方通常建議使用匿名佇列)。
  2. 帶好這兩個屬性後發布訊息。
  3. server 取得訊息並處理。
  4. 結果透過 reply_to 指定的佇列返回,並沿用原訊息的 correlation_id。
  5. client 監聽 reply_to 佇列,比對 correlation_id 是否與自己發出的一致;一致才代表這是本次業務的結果,不一致就別亂動別人的東西。

官方 summary 的要點:

  1. Client 啟動時建立一個匿名、獨立的回呼佇列。
  2. Client 送出的訊息帶兩個屬性:replyTo 指向回呼佇列,correlationId 為每次請求唯一的識別值。
  3. 請求被送進 rpc_queue。
  4. RPC worker(即 server)在該佇列等待,收到請求後處理,並用 replyTo 中的佇列回傳結果。
  5. Client 在回呼佇列等待,收到訊息後檢查 correlationId,吻合才把結果交給應用程式。

實作程式碼

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 的結果,即使 correlationID 不符也會被誤吞,真正等結果的 channel 就永遠等不到。
  • channel && exclusive:exclusive 雖只供單一應用使用,但多個 channel 可以共用同一個獨立佇列,RabbitMQ 會輪流派發,多執行緒各自想拿到屬於自己的結果並不容易。

結果證明我想多了。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 就聊到這裡。

 

Copyright © Linux教程網 All Rights Reserved