如何使用NServiceBus向远程MSMQ发送消息?
如何通过NServiceBus向远程MSMQ发送消息
你已经搞定了本地MSMQ的消息发送,要切换到远程其实很简单,NServiceBus已经帮我们封装好了MSMQ的远程地址处理,不用手动写FormatName:Direct=TCP:...这种复杂字符串,下面给你两种常用的实现方式:
方式一:直接在发送时指定远程队列地址
修改你原来的发送逻辑,把SendLocal换成Send方法,同时传入远程队列的NServiceBus格式地址就可以了。比如你提到的远程队列100.100.100.12\private$\remoteTxn,对应的NServiceBus地址格式是remoteTxn@100.100.100.12(这里remoteTxn是私有队列的名称,@后面是远程机器的IP或主机名)。
完整代码示例:
var endpointConfiguration = new EndpointConfiguration("Samples.Msmq.Simple"); var transport = endpointConfiguration.UseTransport<MsmqTransport>(); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.EnableInstallers(); endpointConfiguration.UsePersistence<InMemoryPersistence>(); var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false); var myMessage = new MyMessage(); // 发送到远程MSMQ,替换成你的远程地址 await endpointInstance.Send("remoteTxn@100.100.100.12", myMessage).ConfigureAwait(false); await endpointInstance.Stop().ConfigureAwait(false);
方式二:配置默认发送地址(适合固定发送到某个远程端点的场景)
如果你的服务总是要发送到同一个远程队列,可以在Transport配置里指定默认的目标地址,这样后续发送时不用每次都写地址:
var endpointConfiguration = new EndpointConfiguration("Samples.Msmq.Simple"); var transport = endpointConfiguration.UseTransport<MsmqTransport>(); // 设置默认发送到远程队列 transport.DefaultSendToAddress("remoteTxn@100.100.100.12"); endpointConfiguration.SendFailedMessagesTo("error"); endpointConfiguration.EnableInstallers(); endpointConfiguration.UsePersistence<InMemoryPersistence>(); var endpointInstance = await Endpoint.Start(endpointConfiguration).ConfigureAwait(false); var myMessage = new MyMessage(); // 直接发送,会自动用配置好的远程地址 await endpointInstance.Send(myMessage).ConfigureAwait(false); await endpointInstance.Stop().ConfigureAwait(false);
注意事项
- 权限配置:运行NServiceBus进程的账号需要拥有远程MSMQ队列的发送权限,远程机器的MSMQ要允许该账号访问(或者开启匿名发送权限,不过生产环境不建议)。
- 网络与防火墙:确保远程机器的防火墙开放了MSMQ相关端口(默认是1801,还有TCP端口50000-50099用于RPC),两台机器能正常通信。
- 队列存在性:远程的
private$\remoteTxn队列需要提前创建好,或者开启EnableInstallers()让NServiceBus尝试自动创建(自动创建需要更高的权限)。
内容的提问来源于stack exchange,提问作者Sujit Singh
相关产品推荐
相关产品推荐

