You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用Apache.NMS.ActiveMQ NuGet包指定Last Value Queue

问题解答

关于Apache.NMS.ActiveMQ的定位

Apache.NMS.ActiveMQ是针对经典ActiveMQ(5.x系列)的.NET客户端实现,它遵循Apache NMS(.NET Messaging Service)规范,底层通过OpenWire协议与ActiveMQ Broker通信,本质上是对Java版ActiveMQ客户端功能的.NET适配封装,二者API体系对应、功能一致。

编程创建Last Value Queue失败的解决方案

你遇到的问题核心是混淆了ActiveMQ Artemis与经典ActiveMQ的客户端API规范:你参考的是Artemis的文档(支持通过队列名URI参数配置Last Value Queue),但使用的是针对经典ActiveMQ的Apache.NMS.ActiveMQ客户端,该客户端不支持Artemis的参数格式,因此无法创建LVQ。

针对经典ActiveMQ(5.x)的正确实现方式

经典ActiveMQ支持三种编程创建LVQ的方式:

  1. 命名约定快速创建
    队列名以LVQ.前缀开头,Broker会自动将其识别为Last Value Queue:

    var queueName = "LVQ.my.destination.name";
    var destination = await session.GetQueueAsync(queueName).ConfigureAwait(false);
    
  2. 通过DestinationOptions配置属性
    显式设置队列的lastValue属性,还可指定lastValueKey(自定义去重键):

    var options = new DestinationOptions();
    // 启用Last Value特性
    options.SetProperty("lastValue", true);
    // 自定义去重键(可选)
    options.SetProperty("lastValueKey", "reuters_code");
    
    var queue = new ActiveMQQueue("my.destination.name", options);
    var destination = await session.GetQueueAsync(queue).ConfigureAwait(false);
    
  3. 通过Admin API创建带属性的队列
    适用于需要提前在Broker上预创建队列的场景:

    var brokerUri = "tcp://localhost:61616";
    using (var connection = new ActiveMQConnectionFactory(brokerUri).CreateConnection())
    {
        connection.Start();
        using (var session = connection.CreateSession())
        {
            var queueInfo = new QueueInfo("my.destination.name");
            queueInfo.SetProperty("lastValue", true);
            queueInfo.SetProperty("lastValueKey", "reuters_code");
            
            var adminView = session.GetAdminView();
            adminView.AddQueue(queueInfo);
        }
    }
    

如果你连接的是ActiveMQ Artemis

若你的Broker是ActiveMQ Artemis(下一代ActiveMQ),则应使用Apache.NMS.Artemis客户端而非Apache.NMS.ActiveMQ,此时你参考的Artemis文档中的URI参数格式才会生效,示例代码:

var queueName = "my.destination.name?last-value=true";
// 或指定自定义键:"my.destination.name?last-value-key=reuters_code"
var destination = await session.GetQueueAsync(queueName).ConfigureAwait(false);

内容的提问来源于stack exchange,提问作者ASP.Tom

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 02:37:44