Galosys.Foundation.Amqp 26.10.29.1

dotnet add package Galosys.Foundation.Amqp --version 26.10.29.1
                    
NuGet\Install-Package Galosys.Foundation.Amqp -Version 26.10.29.1
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Galosys.Foundation.Amqp" Version="26.10.29.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Galosys.Foundation.Amqp" Version="26.10.29.1" />
                    
Directory.Packages.props
<PackageReference Include="Galosys.Foundation.Amqp" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Galosys.Foundation.Amqp --version 26.10.29.1
                    
#r "nuget: Galosys.Foundation.Amqp, 26.10.29.1"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Galosys.Foundation.Amqp@26.10.29.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Galosys.Foundation.Amqp&version=26.10.29.1
                    
Install as a Cake Addin
#tool nuget:?package=Galosys.Foundation.Amqp&version=26.10.29.1
                    
Install as a Cake Tool

Galosys.Foundation.Amqp

成熟度: 🟢 稳定 — AMQP 抽象层,已被 RabbitMQ.Client 模块正式继承

AMQP 消息抽象层模块,定义统一的发送/消费抽象基类、配置模型、[AmqpHandler] 注解、Handler 自动扫描。用户代码仅依赖此模块的 API,切换底层实现只需改 PackageReference。

架构

Galosys.Foundation.Amqp                ← 本模块(抽象层)
  ├─ IAmqpPublisher                    ← 发布接口(仅 ConvertAndSendAsync)
  ├─ IAmqpConsumer                     ← 消费接口
  ├─ AmqpTemplate                      ← 密封门面,立即发送
  ├─ BatchingAmqpTemplate              ← 密封类,缓冲聚批发送
  ├─ PublishMessage / PublishOptions   ← 发送模型
  └─ PendingMessage                    ← 缓冲消息模型

Galosys.Foundation.RabbitMQ.Client     ← RabbitMQ 实现
  ├─ RabbitPublisher : IAmqpPublisher  ← 共享 IConnection + ConvertAndSendAsync
  └─ RabbitConsumer : IAmqpConsumer

功能特性

  • 统一发送 API — IAmqpPublisher.ConvertAndSendAsync 为框架唯一发送原语,支持批量、等待/不等待 confirm
  • 便利方法 — AmqpTemplate.SendAsync<T>/BroadcastAsync<T>/DelayAsync<T> 内部序列化后调 ConvertAndSendAsync
  • 缓冲聚批 — BatchingAmqpTemplate.SendAsync(PendingMessage) 缓冲消息,达批量条件后委托 IAmqpPublisher 发送,适合日志/指标等高吞吐场景
  • WaitForConfirm 控制 — 默认等待 broker ACK(PublishOptions.WaitForConfirm = true),核心业务可靠;非核心可配置 false 即发即走
  • 声明式消费 — [AmqpHandler("routingKey")] 方法级注解,启动时自动扫描注册
  • 广播消息 — BroadcastAsync fanout 发布
  • 延迟消息 — DelayAsync 支持 x-delayed-message 插件
  • 消息属性扩展 — AmqpProperties 流式 API:自定义 MessageId、Header、延迟、TTL
  • 生命周期管理 — AmqpBootstrapper(IHostedLifecycleService,自动扫描 Handler + 优雅关闭)
  • 每消息 DI Scope — 消费端自动创建独立 DI Scope,正确处理 Scoped 生命周期

安装

通常不直接安装此包,而是选择实现包:


<PackageReference Include="Galosys.Foundation.RabbitMQ.Client" Version="x.x.x" />

DI 注册

Amqp 模块提供两层注册:

// 1. 注册 AMQP 基础设施(AmqpTemplate、BatchingAmqpTemplate)
services.AddAmqp(configuration);

// 2. 注册 Outbox Transport(AmqpTransport,纯 Outbox 模式)
services.AddAmqpTransport();

快速开始

1. 最小配置

{
  "RabbitMQ": {
    "HostName": "localhost",
    "UserName": "guest",
    "Password": "guest",
    "VirtualHost": "/"
  }
}

AppName 默认取应用名称,通常无需显式配置。

2. 发送消息

// 立即发送(默认等 confirm)
await template.SendAsync("order.created", new[] { msg });

// 缓冲聚批发送(适合日志/指标)
await batchTemplate.SendAsync(new PendingMessage
{
    RoutingKey = "app.log",
    Body = Encoding.UTF8.GetBytes("..."),
    Properties = new AmqpProperties().Default()
});

2. 注册服务

// 方式一:模块自动发现(推荐)
await Host.CreateDefaultBuilder()
    .UseModularization()
    .Locate()
    .RunAsync();

// 方式二:手动注册(需同时注册实现包)
services.AddRabbitMQ(configuration);

3. 发送消息

using RabbitMQ.Client;

public class OrderCreatedMessage
{
    public string OrderNo { get; set; }
}

public class OrderService
{
    private readonly AmqpTemplate _amqp;

    public OrderService(AmqpTemplate amqp) => _amqp = amqp;

    // 单条发送
    public async Task SendAsync() =>
        await _amqp.SendAsync("order_created", new[] { new OrderCreatedMessage { OrderNo = "ORD001" } });

    // 批量发送
    public async Task SendBatchAsync() =>
        await _amqp.SendAsync("order_created", new[]
        {
            new OrderCreatedMessage { OrderNo = "ORD001" },
            new OrderCreatedMessage { OrderNo = "ORD002" }
        });

    // 广播消息(fanout)
    public async Task BroadcastAsync() =>
        await _amqp.BroadcastAsync("order_events", new[] { new OrderCreatedMessage { OrderNo = "ORD001" } });

    // 延迟消息(需 x-delayed-message 插件)
    public async Task DelayAsync() =>
        await _amqp.DelayAsync("order_created", new[] { new OrderCreatedMessage { OrderNo = "ORD001" } }, delayMillionSeconds: 5000);
}

4. 消费消息

using RabbitMQ.Client;

[Handler]
public class OrderHandler : IMessageHandler
{
    [AmqpHandler("order_created")]
    public async Task<bool> HandleAsync(IMessage msg)
    {
        // 处理消息
        return true; // true = ACK, false = Nack
    }

    // 广播消费
    [AmqpHandler("order_events", Broadcast = true, Durable = true)]
    public async Task<bool> OnBroadcastAsync(IMessage msg)
    {
        return true;
    }
}

注册机制: 类标注 [Handler] → DI 自动注册;方法标注 [AmqpHandler] → 启动时自动扫描订阅。类需实现 IMessageHandler 或 IMessageHandler<T>。

详细配置

完整配置示例

{
  "RabbitMQ": {
    "HostName": "localhost",
    "UserName": "guest",
    "Password": "guest",
    "VirtualHost": "/",
    "AutoCreateEnabled": true,
    "ConsumerDispatchConcurrency": 8,
    "NetworkRecoveryInterval": 10,
    "RequestedHeartbeat": 45,
    "ContinuationTimeout": 20,
    "Limit": {
      "ProducerMaxConnections": 4,
      "ConsumerMaxConnections": 4,
      "MaxMessageSize": 65536,
      "BatchSize": 100,
      "BatchTimeoutMs": 50,
      "PublishConfirmTimeoutMs": 3000,
      "PipelineCapacity": 5000
    },
    "Handlers": {
      "order_created": {
        "Concurrency": 4,
        "MaxRetryCount": 3,
        "RetryBaseDelayMs": 1000,
        "PrefetchMultiplier": 2,
        "DurableQueue": false,
        "QueueName": null
      }
    }
  }
}

根配置(AmqpOptions)

配置项 类型 默认值 说明
HostName string (必填) RabbitMQ 主机地址
Port int 5672 RabbitMQ 端口
UserName string? null 认证用户名
Password string? null 认证密码
VirtualHost string? "/" 虚拟主机
AppName string? 应用名 客户端连接名称
AutoCreateEnabled bool true 自动声明队列/交换器(阿里云限 TPS 场景可关闭)
Limit AmqpLimitOptions 见下表 连接池与限流配置
Handlers IDictionary<string, AmqpHandlerProperty> {} 按 RoutingKey 粒度的消费者配置
ConsumerDispatchConcurrency ushort CPU核心数*4 消费者调度并发数
NetworkRecoveryInterval int 10 自动重连间隔(秒)
RequestedHeartbeat int 45 心跳间隔(秒)
ContinuationTimeout int 20 RPC 续延超时(秒)

限流配置(AmqpLimitOptions)

配置项 类型 默认值 说明
ProducerMaxConnections int 4 生产者连接池大小
ProducerChannelMaxPerConnection int 10 每连接最大 Channel 数(生产者)
ConsumerMaxConnections int 4 消费者连接池大小
ConsumerChannelMaxPerConnection int 50 每连接最大 Channel 数(消费者)
MaxMessageSize int 65536 最大消息体字节数(64KB)
MaxTps int 0 最大 TPS(0=不限)
BatchSize int 100 批量发送大小
BatchTimeoutMs int 50 批量聚合等待时间(ms)
PublishConfirmTimeoutMs int 3000 Publisher Confirm 超时(ms)
RetryCount int 3 批量发送重试次数
RetryBaseDelayMs int 1000 重试退避基础延迟(ms)
PipelineCapacity int 5000 发送管道容量(有界 Channel)

Handler 配置(AmqpHandlerProperty)

配置项 类型 默认值 说明
Concurrency int 1 并发消费线程数
MaxRetryCount int 3 最大重试次数
RetryBaseDelayMs int 1000 指数退避基础延迟(ms)
PrefetchMultiplier int 2 实际 Prefetch = Concurrency × PrefetchMultiplier
DurableQueue bool false 队列是否持久化(广播模式)
QueueName string? null 自定义队列名(null=自动命名)

核心类

类名 说明
AmqpTemplate 消息操作模板(Facade),提供 SendAsync、BroadcastAsync、DelayAsync、HandleAsync
AmqpPublisher 消息发布器抽象基类
AmqpConsumer 消息消费者抽象基类
AmqpBootstrapper 启动引导器,自动扫描 Handler + 优雅关闭
AmqpOptions 配置选项类
AmqpLimitOptions 连接池限流配置
AmqpHandlerProperty 按 RoutingKey 的消费者配置
AmqpHandlerAttribute 消费者方法注解
AmqpProperties 消息属性,支持流式设置 Header/Delay/TTL
IAmqpProperties 消息属性接口

依赖

  • Galosys.Foundation.Core
  • Microsoft.Extensions.Hosting
  • Microsoft.Extensions.Options
Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on Galosys.Foundation.Amqp:

Package Downloads
Galosys.Foundation.EasyNetQ

Galosys.Foundation快速开发库

Galosys.Foundation.RabbitMQ.Client

Galosys.Foundation快速开发库

Galosys.Foundation.RabbitMQ.Benchmarks

Galosys.Foundation快速开发库

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
26.10.29.1 143 10/29/2026
26.10.20.1 128 10/20/2026
26.10.16.2 123 10/16/2026
26.10.16.1 119 10/16/2026
26.10.9.1 130 10/9/2026
26.10.8.1 140 10/8/2026
26.9.23.1 153 9/23/2026
26.9.16.1 141 9/16/2026
26.9.15.1 136 9/15/2026
26.9.14.1 140 9/14/2026
26.9.10.1 144 9/10/2026
26.9.3.1 144 9/3/2026
26.8.29.1 157 8/31/2026
26.8.26.1 145 8/26/2026
26.8.23.1 147 8/23/2026
26.8.21.1 156 8/21/2026
26.8.20.1 155 8/20/2026
26.8.18.1 151 8/18/2026
26.8.17.1 154 8/17/2026
26.8.13.2 155 8/13/2026
Loading failed