当传出 header 是静态的时,NServiceBus 如何保持一致性?
这是否意味着如果我要为特定消息设置传出 header ,它会影响所有其他传出消息,因为它是一个单例?
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;
.
.
.
}
但是,传入 header 似乎被正确标记为 [ThreadStatic]
。
解释。
========================编辑==================== ========
我想我正在尝试理解,因为许多示例显示了以下代码:
Bus.OutgoingHeaders["Test"] = g.ToString("N");
追踪到:
IDictionary<string, string> IBus.OutgoingHeaders
{
get
{
return ExtensionMethods.GetStaticOutgoingHeadersAction();
}
}
设置为:
内部类 Bootstrapper:INeedInitialization、IWantToRunWhenConfigurationIsComplete { 公共(public) 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 转到静态字段。
我正在尝试弄清楚如何为下一条 消息设置 header 。但是,如果我按照示例进行操作,我最终会为所有消息设置 header 。
最佳答案
[Udi 更新] 如果您想在发送的特定消息上设置 header ,只需调用 .SetHeader(key, value);
消息对象上的方法。静态传出 header 对于进程范围的数据很有用,例如桌面应用程序中的登录用户是谁。[结束更新]
MessageHeaderManager
是一个 IMutateOutgoingTransportMessages
,这意味着它只关心消息的输出。此处没有显示传入消息 header 。
messageHeaders
与为每条消息设置的 header 有关,例如发送时间,或您从消息处理程序手动设置的任何内容。
staticOutgoingHeaders
是一个缓存所有 header 的地方,这些 header 对于来自端点的每条消息都是相同的,这样就不需要重新计算它们的值。这将包括诸如源计算机名称之类的内容。
如果仔细研究 MutateOutgoing 方法,您会发现 messageHeaders
和 staticOutgoingHeaders
中的所有键/值对都添加到 transportMessage.Headers
集合。此外,静态的是通过 Headers.Add(key, value)
添加的,而线程静态的 header 是通过 Headers[key] = value
添加的,这样一个项目来自线程静态集合将覆盖同名的静态 header 。
这是一个 link to the full source for this class on GitHub ,由 V4.0.3 的标签链接(在撰写本文时为当前版本),希望该链接不会过期。
关于c# - 为什么 NServiceBus OutgoingHeaders 是静态的而不是 ThreadStatic?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18411371/