【问题标题】:Why NServiceBus OutgoingHeaders is static and not ThreadStatic?为什么 NServiceBus OutgoingHeaders 是静态的而不是 ThreadStatic?
【发布时间】:2013-08-27 00:13:20
【问题描述】:

当传出标头是静态的时,NServiceBus 如何保持一致性?

这是否意味着如果我为特定消息设置传出标头,它会影响所有其他传出消息,因为它是单例?

namespace NServiceBus.MessageHeaders
{
  [ComVisible(false)]
  public class MessageHeaderManager : IMutateOutgoingTransportMessages
  {
    private static IDictionary<string, string> staticOutgoingHeaders = (IDictionary<string, string>) new Dictionary<string, string>();
    private IUnicastBus bus;
    [ThreadStatic]
    private static IDictionary<object, IDictionary<string, string>> messageHeaders;
   .
   .
   .
 }

然而,传入的标头似乎被正确标记为[ThreadStatic]

解释一下。

=========================编辑====================== ========

我想我正在尝试理解,因为许多示例都显示了以下代码:

Bus.OutgoingHeaders["Test"] = g.ToString("N");

追溯至:

IDictionary<string, string> IBus.OutgoingHeaders
{
  get
  {
    return ExtensionMethods.GetStaticOutgoingHeadersAction();
  }
}

设置在:

内部类引导程序:INeedInitialization、IWantToRunWhenConfigurationIsComplete { 公共 MessageHeaderManager 管理器 { 获取;放; }

void INeedInitialization.Init()
{
  Configure.Instance.Configurer.ConfigureComponent<MessageHeaderManager>(DependencyLifecycle.SingleInstance);
}

public void Run()
{
  ExtensionMethods.GetHeaderAction = (Func<object, string, string>) ((msg, key) => this.Manager.GetHeader(msg, key));
  ExtensionMethods.SetHeaderAction = (Action<object, string, string>) ((msg, key, val) => this.Manager.SetHeader(msg, key, val));
  ExtensionMethods.GetStaticOutgoingHeadersAction = (Func<IDictionary<string, string>>) (() => this.Manager.GetStaticOutgoingHeaders());
}

}

当然,上面最后一行中的 GetStaticOutgoingHeaders 转到静态字段。

我正在尝试弄清楚如何为 下一个 消息设置标题。但是,如果我按照示例进行操作,我最终会为所有消息设置标题。

【问题讨论】:

    标签: c# message-queue nservicebus soa


    【解决方案1】:

    [Udi 更新] 如果您想在发送的特定消息上设置标头,只需在消息对象上调用 .SetHeader(key, value); 方法即可。静态传出标头对于进程范围的数据很有用,例如登录用户在桌面应用程序中的身份。[结束更新]

    MessageHeaderManager 是一个IMutateOutgoingTransportMessages,这意味着它只关注消息的出路。这里没有显示传入的消息标题。

    messageHeaders 关注的是为每个消息设置的标头,例如发送时间,或者您可以从消息处理程序手动设置的任何内容。

    staticOutgoingHeaders 是一个缓存端点外每条消息的所有相同标头的地方,这样就不需要重新计算它们的值。这将包括诸如源机器名称之类的内容。

    如果您仔细研究 MutateOutgoing 方法的内容,您会发现 messageHeadersstaticOutgoingHeaders 中的所有键/值对都已添加到 transportMessage.Headers 集合中。此外,静态标题使用Headers.Add(key, value) 添加,而线程静态标题通过Headers[key] = value 添加,因此线程静态集合中的项目将覆盖同名的静态标题。

    这是一个link to the full source for this class on GitHub,由 V4.0.3 的标签链接(在撰写本文时为当前版本),因此希望该链接不会过期。

    【讨论】:

    • 大卫,请看我上面的更新。我关注 IBus.OutgoingHeaders 并找到了我最初发布的代码,这是一个静态代码。所有示例都表明这是您设置标头的方式,但随后我将设置为全局标头表,而不是当前上下文的表。
    • 经过更多研究后,我会回答这个问题。同样是 Udi,这种范围规范可以使用更完整的文档。我喜欢这个产品,但我发现自己查看源代码的次数比我关心的要多。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2011-02-27
    • 1970-01-01
    • 1970-01-01
    • 2012-03-15
    相关资源
    最近更新 更多