You need to enable JavaScript to run this app. ASP.Net Core 3基于RabbitMQ RPC实现单请求多队列消息发送咨询
优惠活动
大模型
产品
解决方案
定价
更多

ASP.Net Core 3基于RabbitMQ RPC实现单请求多队列消息发送咨询

单次RPC请求实现多队列调用的实现方案

你可以根据业务场景选择以下两种实现方案:


方案1:客户端侧封装批量调用(无服务端改动)

上层业务只需调用1次方法,底层并行发起多个RPC请求,对业务逻辑透明,改造成本极低。

客户端改动

  1. 新增批量调用方法,并行请求所有指定队列,聚合结果返回:
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

// RpcClient类内新增方法
public async Task<Dictionary<string, string>> CallBatchAsync(string message, List<string> rpcQueueNames, CancellationToken cancellationToken = default)
{
    var taskList = new List<Task<KeyValuePair<string, string>>>();
    foreach (var queueName in rpcQueueNames)
    {
        taskList.Add(Task.Run(async () =>
        {
            var result = await CallAsync(message, queueName, cancellationToken);
            return new KeyValuePair<string, string>(queueName, result);
        }, cancellationToken));
    }
    // 等待所有请求返回
    var allResults = await Task.WhenAll(taskList);
    return allResults.ToDictionary(kv => kv.Key, kv => kv.Value);
}
  1. 业务侧调用示例:
var rpcClient = new RpcClient();
// 单次调用即可获取所有队列的结果
var batchResult = await rpcClient.CallBatchAsync("", new List<string>{"customerContactPersons", "projects"});
// 按队列名取对应返回值
var customerContactPersons = batchResult["customerContactPersons"];
var productInfo = batchResult["projects"];

方案2:服务端新增聚合队列(真正单次网络请求)

如果需要减少网络IO次数,可在服务端新增聚合RPC队列,客户端只发1次请求,服务端直接返回所有需要的结果。

服务端改动

  1. 先预存所有队列对应的返回消息:
// 服务端全局存储队列与返回值的映射关系
private static readonly Dictionary<string, string> _queueMessageMapping = new Dictionary<string, string>
{
    {"customerContactPersons", "customerContactPersonsList"},
    {"projects", "ProductInfoList"}
};
  1. 新增聚合RPC队列的消费逻辑:
using System.Text.Json;

public void StartAggregateRpcServer()
{
    var factory = new ConnectionFactory() { HostName = "localhost" };
    using var connection = factory.CreateConnection();
    using var channel = connection.CreateModel();
    
    // 声明聚合RPC队列
    channel.QueueDeclare(queue: "rpc_aggregate", durable: false, 
        exclusive: true, autoDelete: false, arguments: null);
    channel.BasicQos(0, 1, false);
    var consumer = new EventingBasicConsumer(channel);
    channel.BasicConsume(queue: "rpc_aggregate", autoAck: false, consumer: consumer);
    Console.WriteLine(" [x] 聚合RPC服务已启动,等待请求");

    consumer.Received += (model, ea) =>
    {
        var body = ea.Body.ToArray();
        var props = ea.BasicProperties;
        var replyProps = channel.CreateBasicProperties();
        replyProps.CorrelationId = props.CorrelationId;
        string response;

        try
        {
            // 解析客户端传入的待查询队列名列表
            var requestQueues = JsonSerializer.Deserialize<List<string>>(Encoding.UTF8.GetString(body));
            var resultDict = new Dictionary<string, string>();
            foreach (var queueName in requestQueues)
            {
                resultDict[queueName] = _queueMessageMapping.TryGetValue(queueName, out var msg) 
                    ? msg 
                    : "指定队列不存在";
            }
            // 序列化所有结果返回
            response = JsonSerializer.Serialize(resultDict);
        }
        catch (Exception e)
        {
            Console.WriteLine(" [.] 处理请求出错:" + e.Message);
            response = JsonSerializer.Serialize(new { error = "服务端处理请求失败" });
        }
        finally
        {
            var responseBytes = Encoding.UTF8.GetBytes(response);
            channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, 
                basicProperties: replyProps, body: responseBytes);
            channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
        }
    };
    Console.ReadLine();
}

客户端改动

仅需调用聚合队列,传入待查询的队列列表即可:

using System.Text.Json;

var rpcClient = new RpcClient();
// 构造请求参数:需要查询的队列名列表
var requestParam = JsonSerializer.Serialize(new List<string>{"customerContactPersons", "projects"});
// 单次RPC请求获取所有结果
var aggregateResponse = await rpcClient.CallAsync(requestParam, "rpc_aggregate");
// 解析返回结果
var resultDict = JsonSerializer.Deserialize<Dictionary<string, string>>(aggregateResponse);
var customerContactPersons = resultDict["customerContactPersons"];
var productInfo = resultDict["projects"];

原有代码优化建议

  • 服务端PublishMessage方法每次调用都会新建连接和通道,建议将连接、通道设为单例复用,减少资源开销
  • 客户端CallAsync方法中不要每次调用都执行channel.BasicConsume,消费逻辑只需在客户端初始化时注册一次即可,避免重复注册导致异常

内容的提问来源于stack exchange,提问作者Priyanka

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 03:45:05