rabbitmq
Messaging code on RabbitMQ 4.3 and 4.4 with RabbitMQ.Client 7, and the messaging principles that all message flows share (at-least-once delivery, idempotent consumers, outbox, contracts, names, dead letters). Use when code or a review touches a broker, an exchange, a queue, a routing key, a publisher or a consumer, IChannel, ConnectionFactory, BasicPublishAsync, BasicConsumeAsync, acks, prefetch, publisher confirms, quorum queues, dead-letter exchanges, an outbox table with a background publisher, EasyNetQ, or a RabbitMQ test container. Not for Wolverine handlers, its outbox, or its transport settings (dev-stack:wolverine), Kafka or Azure Service Bus, or broker users, vhosts and TLS (dev-stack:secure-coding).
- License 许可
- MIT
- 最近更新
- 2026-11-13
- Stars
- ★ 0
- Forks
- 0
01 前言 Front Matter
- name
- rabbitmq
- metadata
- { "verified": "2026-10-27", "versions": "RabbitMQ 4.4.0 and 4.3.7, RabbitMQ.Client 7.2.2, EasyNetQ 8.1.11, Testcontainers.RabbitMq 4.16.0, .NET 10.0.14" }
- description
- Messaging code on RabbitMQ 4.3 and 4.4 with RabbitMQ.Client 7, and the messaging principles that all message flows share (at-least-once delivery, idempotent consumers, outbox, contracts, names, dead letters). Use when code or a review touches a broker, an exchange, a queue, a routing key, a publisher or a consumer, IChannel, ConnectionFactory, BasicPublishAsync, BasicConsumeAsync, acks, prefetch, publisher confirms, quorum queues, dead-letter exchanges, an outbox table with a background publisher, EasyNetQ, or a RabbitMQ test container. Not for Wolverine handlers, its outbox, or its transport settings (dev-stack:wolverine), Kafka or Azure Service Bus, or broker users, vhosts and TLS (dev-stack:secure-coding).
02 资源文件 15
- 参考文档references/broker.md9.1 KB
- 参考文档references/client.md11.2 KB
- 参考文档references/decisions.md10.2 KB
- 参考文档references/easynetq.md2.5 KB
- 参考文档references/language.md4.7 KB
- 参考文档references/messaging-principles.md6.3 KB
- 参考文档references/outbox.md7.7 KB
- 参考文档references/review-checklist.md5.6 KB
- 参考文档references/sources.md7.9 KB
- 参考文档references/stack-rules.md7.6 KB
- 参考文档references/testing.md4.0 KB
- 参考文档rules.json7.6 KB
- 脚本scripts/convert.py2.9 KB
- 脚本scripts/doccheck.py28.8 KB
- 脚本scripts/stackcheck.py11.9 KB
03 SKILL.md 正文
RabbitMQ
The messaging principles, the RabbitMQ 4.3 and 4.4 broker, and the raw RabbitMQ.Client 7 API. Wolverine handlers and the Wolverine RabbitMQ transport are in dev-stack:wolverine. Broker users, vhosts, and TLS are in dev-stack:secure-coding. Test containers in general are in dev-stack:dotnet-testing.
First
- Read
references/stack-rules.mdandreferences/messaging-principles.md. - Find the versions:
- Client: the
RabbitMQ.ClientorEasyNetQpackage in*.csprojorDirectory.Packages.props.- RabbitMQ.Client 7: use this file.
- RabbitMQ.Client 6 (
IModel,CreateModel): readreferences/client.md, section "Version 6 to 7". Do not upgrade unless the task asks for it. - EasyNetQ 8: read
references/easynetq.md. Do not adopt EasyNetQ 9 (alpha).
- Broker: the image tag in
compose*.yml, the Helm values, or the test container. RabbitMQ 3.13 and older: readreferences/broker.md, section "From 3.13 to 4.x".
- Client: the
- Check
docs/dev-team/decisions.mdfor MSG-01 (in process or broker) and MSG-04 (library). When the service uses Wolverine, switch todev-stack:wolverine.
Done when you can name the client version, the broker version, and the library decision.
Defaults for new code
Ask the human before you apply a default that has no accepted decision (stack rule 4). The full entries are in references/decisions.md.
| Area | Default | ID |
|---|---|---|
| In process or broker | In process inside one deployable. A broker only between services, or for work that must survive a restart. | MSG-01 |
| Broker | RabbitMQ 4.4 with quorum queues for a new broker. An existing broker keeps its minor version. | MSG-03 |
| Library | Wolverine 6. Raw RabbitMQ.Client 7 only for interop or infrastructure code. EasyNetQ 8 only where it exists. | MSG-04 |
| Contracts | <Service>.Contracts, records, pinned wire names, additive changes, JSON sample tests. |
MSG-05 |
| Names | Exchange {publisher}.events (topic). Routing key {entity}.{event}.v{n}. Queue {consumer}.{purpose}. Dead letters {service}.dlq. |
MSG-06 |
| Queue type | Quorum, declared in code, plus default_queue_type = quorum on each vhost. |
MSG-07 |
| Failures | Dead-letter policy on each work queue, delivery-limit 20, alert when a dead-letter queue is not empty. Exception: a quorum queue that a Wolverine durable inbox reads gets delivery-limit -1. |
MSG-08 |
| Outbox | Without Wolverine: own outbox table in the same SaveChangesAsync, background publisher with confirms. |
MSG-09 |
| Idempotency | Natural key or upsert. Message ID table only for effects that cannot be idempotent. | MSG-10 |
| Wire format | System.Text.Json, application/json, camelCase, wire name in the AMQP type property. |
MSG-11 |
| Tracing | Built-in ActivitySources RabbitMQ.Client.*, MessageId and CorrelationId on each message. |
MSG-12 |
Existing code keeps its style (stack rule 3).
Rules
Delivery
- Expect each message more than one time. Make each consumer idempotent with a unique business key or an upsert (MSG-10). The
redeliveredflag only says "maybe". - A database write and a publish must both happen or both fail. Write an outbox row in the same
SaveChangesAsync, and publish from aBackgroundService(MSG-09). No transaction spans the database and the broker. A publish afterSaveChangesAsyncloses the event when the broker is down or the process stops. The code is inreferences/outbox.md.
Topology
- Declare each durable work queue with
x-queue-type: quorum, and setdefault_queue_type = quorumon the vhost as a safety net (MSG-07). A classic queue lives on one node, so it does not survive the loss of that node. - Do not send
x-queue-mode(any value),x-queue-version: 1, orha-*policies: RabbitMQ 4.3 rejects them (x-queue-version: 2is valid). Do not sendx-queue-master-locator, and do not declare a queue that is not durable and not exclusive. From 4.3, both are deprecated features that the broker denies by default. - Put dead-lettering,
delivery-limit, and length limits in a policy when operations owns the broker. Queue arguments cannot change after the declaration, and a second declaration with other arguments fails withPRECONDITION_FAILED. Detail:references/broker.md.
Publishing
- Create the publish channel with
new CreateChannelOptions(publisherConfirmationsEnabled: true, publisherConfirmationTrackingEnabled: true), await each publish, and catchPublishReturnExceptionandPublishException. Without confirms, a publish during a connection failure is lost without an error. - Publish with
mandatory: truewhen an unroutable message is a bug. Without it, the broker drops a message that no queue binds. - Keep one long-lived
IConnectionper process role, withClientProvidedName. Give each concurrent publisher its ownIChannel. A shared channel mixes frames of concurrent publishes. - Set
Persistent,MessageId,CorrelationId,ContentType,Type(the pinned wire name), andTimestampon each message (MSG-11, MSG-12). A consumer in another language reads the type and the ID from these properties.
await using var channel = await connection.CreateChannelAsync(
new CreateChannelOptions(publisherConfirmationsEnabled: true, publisherConfirmationTrackingEnabled: true), ct);
var properties = new BasicProperties
{
Persistent = true,
MessageId = messageId.ToString(),
CorrelationId = correlationId,
ContentType = "application/json",
Type = "order.placed.v1", // the pinned wire name, not the CLR type name
Timestamp = new AmqpTimestamp(DateTimeOffset.UtcNow.ToUnixTimeSeconds()),
};
var body = JsonSerializer.SerializeToUtf8Bytes(evt, s_json); // JsonSerializerDefaults.Web: camelCase
// With confirmation tracking, the await ends when the broker confirms the message.
// It throws PublishException on a nack and PublishReturnException when no queue binds the key.
await channel.BasicPublishAsync("orders.events", "order.placed.v1", mandatory: true, properties, body, ct);
Consuming
- Consume with
autoAck: false. Ack after the work and the database commit. An early ack turns a crash into data loss. - Set a prefetch per consumer:
BasicQosAsync(0, n, global: false). Start between 10 and 100 and measure. Without aBasicQosAsynccall, the prefetch is 0 (no limit), and one consumer can hold the full backlog unacked. Global QoS is a deprecated feature (global_qos), and quorum queues do not support it. Do not depend on an error: on 4.3.6 the call withglobal: truedid not fail. - Deserialize or copy
ea.BodyinsideReceivedAsync. The client reuses that memory after the handler returns. - Classify failures (principle 7). Permanent (validation, unknown type):
BasicNackAsync(requeue: false), so that the dead-letter exchange takes it. Transient: retry with a delay (DLX plus TTL, or the quorum delayed retry of 4.3). Keepdelivery-limitat 20. On 4.3 and later,BasicNackAsync(requeue: true)does not count toward it: requeue withBasicRejectAsync(requeue: true). Usedead-letter-strategy=at-least-oncewithoverflow=reject-publishfor a queue whose dead letters must not get lost (MSG-08). - Expect no global order. For order with failover, use
x-single-active-consumer. RaiseConsumerDispatchConcurrencyabove 1 (the default) only when order does not matter. Keep a handler shorter than the consumer timeout (30 minutes, enforced on quorum queues). On 4.3 and later, the broker then cancels the consumer. RabbitMQ.Client 7 does not consume again by itself: handleUnregisteredAsync. The timeout does not count toward thedelivery-limit. Send a reference instead of a body above 16 MiB. - Do not wait with
Task.DelayinsideReceivedAsyncbefore a retry. WithConsumerDispatchConcurrency1, the client awaits each handler, so the wait stops all other deliveries of the channel. Let the broker delay the message (rule 13,references/broker.md, section "Delayed retry").
The full consumer and the topology code are in references/client.md.
Existing consumers
- Before a new consumer uses an existing consumer base class, check it for these defects. Each one loses or blocks messages without an error:
BasicNackAsync(requeue: true)for each error: on 4.3 and later, a failing message loops forever (rule 13).- No
BasicQosAsync: prefetch 0 (rule 11). - Deserialization outside the
try: when the JSON is not valid, the exception leavesReceivedAsync, and the message stays unacked until the channel closes. - Default
JsonSerializerOptions(case-sensitive): a camelCase producer gives empty fields, without an error.JsonSerializerDefaults.Webreads both. - A domain rule violation (for example an
ArgumentExceptionof the entity) treated as transient: the message waits through 20 retries before the dead-letter queue. It is permanent. - Shared queue arguments that the change extends: the redeclaration of an existing queue fails with
PRECONDITION_FAILED(rule 5).
EasyNetQ
- EasyNetQ 8: register with
services.AddEasyNetQ("host=...;publisherConfirms=true;consumerDispatcherConcurrency=1"). Set both values. By default, the dispatch concurrency followsprefetchCount(50). Then 50 messages run in parallel and out of order. UseWithQueueType(QueueType.Quorum). EasyNetQ has no built-in retry. Detail:references/easynetq.md.
Tests
- Test against a real broker of the production minor version, for example
new RabbitMqBuilder("rabbitmq:4.3-management-alpine"). Wait for a message with aTaskCompletionSourceand a timeout, not withTask.Delay. Do not mockIChannel. Test the broker-down path: stop the container, act, start it again, and assert that the event arrives. Detail:references/testing.md.
Never write
| Wrong | Correct |
|---|---|
IModel, CreateModel(), CreateBasicProperties(), EventingBasicConsumer, ConfirmSelect() |
IChannel, CreateChannelAsync(options), new BasicProperties { ... }, AsyncEventingBasicConsumer, CreateChannelOptions(true, true) |
factory.CreateConnection() |
await factory.CreateConnectionAsync(ct) |
services.AddSingleton(await connection.CreateChannelAsync()) for all publishers |
One channel per publisher, or the outbox publisher that owns its channel |
_ = channel.BasicPublishAsync(...) |
await channel.BasicPublishAsync(...) on a channel with confirms |
await db.SaveChangesAsync(ct); await channel.BasicPublishAsync(...); |
An outbox row in the same SaveChangesAsync and a background publisher |
["x-queue-mode"] = "lazy", ha-mode policy |
["x-queue-type"] = "quorum" |
BasicQosAsync(0, 20, global: true) |
BasicQosAsync(0, 20, global: false) |
BasicConsumeAsync(queue, autoAck: true, ...) |
autoAck: false and BasicAckAsync after the commit |
catch { await ch.BasicNackAsync(tag, false, requeue: true); } for each error |
Classify. requeue: false for permanent errors, plus a dead-letter policy. On 4.3 and later this nack never reaches the delivery-limit |
RabbitHutch.CreateBus("host=...") |
services.AddEasyNetQ("host=...;publisherConfirms=true") |
UseDelayedExchangeScheduler(), "x-delayed-type" |
The default DLX plus TTL scheduler, or the quorum delayed retry |
new RabbitMqBuilder().Build() |
new RabbitMqBuilder("rabbitmq:4.3-management-alpine").Build() |
Check
-
Build with the analyzers as errors. The compiler rejects the 6.x API. CS0618 flags the old Testcontainers constructor. CA2012 flags a
ValueTaskthat is not awaited.dotnet build -warnaserrorPass:
Build succeededwith 0 warnings. -
Check the packages:
dotnet list package --vulnerable --include-transitivePass: no vulnerable package.
-
Run the rules of this skill:
python3 <skill folder>/scripts/stackcheck.py --root <repo>Pass: 0 errors. For each warning, fix it or add
// stackcheck: ignore <RULE-ID> <reason>. -
On a running broker:
rabbitmqctl list_queues name type durable argumentsPass: each work queue has the type
quorum.
Review checklist
The full list is in references/review-checklist.md.
- No
x-queue-mode,x-queue-version: 1,x-queue-master-locator, orha-*policy. tool (RMQ-REMOVED-ARGS) - Each durable work queue is a quorum queue. tool (
rabbitmqctl), judge - No global QoS. tool (RMQ-GLOBAL-QOS)
- Consumers use
autoAck: falseand ack after the commit. tool (RMQ-AUTOACK), judge - A database write and a publish go through an outbox. No publish after
SaveChangesAsync. judge - The publish channel has confirms and tracking. Each publish is awaited, and a failure is not swallowed. tool (CA2012), judge
- No channel shared by concurrent publishers. tool (RMQ-SINGLETON-CHANNEL), judge
- Each message has
Persistent,MessageId,CorrelationId,ContentType,Type, andTimestamp. judge ea.Bodyis read inside the handler. judge- Permanent errors go to a dead-letter exchange. No
requeue: truefor each error. Each work queue has a dead-letter policy and a delivery limit. judge - Consumers are idempotent on a business key. judge
- Contracts have pinned wire names and change only by addition. judge
- Tests use a pinned 4.x broker image and wait with a signal, not
Task.Delay. tool (RMQ-TC-OLD-IMAGE, CS0618), judge - No delayed message exchange plugin. tool (RMQ-DELAYED-PLUGIN)
- No
BasicNackAsyncwithrequeue: true: on 4.3 and later it does not count toward thedelivery-limit. tool (RMQ-NACK-REQUEUE) - The existing consumer code that the change uses has none of the defects of rule 16. judge
Do not flag these correct patterns (detail in references/review-checklist.md):
ea.Body.ToArray()before the firstawait.BasicNackAsync(requeue: false)for JSON that is not valid.- One channel that a
SemaphoreSlimguards. - A unique index on a nullable business key on PostgreSQL.
Report
End with the report of stack rule 8 (references/stack-rules.md): the same headings in the same order on each run.
In the open points, name the owner of each dead-letter queue (this service, or a named team) and the replay step.
References
references/messaging-principles.md: read first. The principles that each message flow follows.references/decisions.md: read before new code needs an MSG decision. It has the question, the options, and the recommendation.references/client.md: read when you write a connection, a channel, a publisher, or a consumer, or move code from version 6 to 7.references/outbox.md: read when a database write and a publish must both happen in a service without Wolverine.references/broker.md: read when you declare a queue, an exchange, a policy, or a dead-letter route, or upgrade the broker from 3.x.references/easynetq.md: read only when the project uses EasyNetQ.references/testing.md: read before you write a test against the broker.references/review-checklist.md: read for a full review.references/sources.md: the primary sources and the credits.references/stack-rules.mdandreferences/language.md: the common rules and the output language.scripts/stackcheck.py: the rule check of this skill.
04 同仓库更多 Skills
web-accessibility
Web accessibility to WCAG 2.2 AA - a checklist for the design, the tool checks (axe-core, the Tab walk, reduced motion), and the manual checks that no tool does (screen reader, zoom, status messages) - with the EAA and EN 301 549 status. Use when a design, mockup, or built feature must be checked for accessibility, when a review must cover keyboard and screen reader use, when the user asks about focus, a focus trap, contrast, or a screen reader on a page, or when the user asks which accessibility rules apply.
ux-states
State inventory for each screen - default, empty, loading, partial, error, success, disabled, overflow, offline, and the business states (no permission, stale data, locked by another user, waiting on an external system, bulk result with failures, read only) - with what the user sees, can do, and how the user recovers. Use when a screen or flow needs its states designed or checked, or when a design shows only the happy path.
ux-setup
Set up a project for UX work - finds the design tools, the design-system source, the brand files, the languages, and the run command, asks the human one round of questions, and writes the "## Design" section of .claude/rules/delivery.md that the ux-design commands and the ux-designer agent read. Moves an older "## Design" section out of CLAUDE.md. Use when /setup, /ux-design, or /ux-review needs the design facts, when the ux-designer agent returns NEEDS_HUMAN because the "## Design" section is missing, or when the user wants to set up or change the design tools of a project.
ux-review
UX review of a built feature against its approved design - Playwright walks each flow and state at 390, 820, and 1440 px, axe-core and the tell checks run on each state, and each heuristic gets a verdict - with findings by owner, severity, and origin, and a verdict in ux-review.md in the work folder of the item. Use when a built feature or screen must be checked against its design, mockups, or prototype, in each state or at each screen size, when built screens need findings by severity, when the build of an item with a UX design is done, or when existing screens need a UX audit.
ux-prototype
Clickable prototype of a designed story in the proto-shell standard, with variants for an A/B test, all states in scope, three sizes, and a test plan with tasks. Use when a design or mockups exist and the team must test the flow or compare variants with users before the build.
ux-practice
The method of the ux-designer agent for the UX design of a story, a feature, or a screen - Double Diamond phases, a design spec with a source for each decision, the UX decision log, evidence tags, severity, and the modes light, full, and new-direction. Preloaded by the ux-designer agent. Use when the ux-designer agent or another UX skill names this method. For the design of an item, a person starts ux-design:ux-design.