自从EasyNetQ第一个版本开始,它就可以发布/订阅特定类型的消息。
bus.Subscribe<MyMessage>("subscriptionId",
x => Console.WriteLine(x.Text));
bus.Publish<MyMessage>(theMessage);
但是,在运行期间,你怎么去发现消息类型?例如:你可能有一些系统加载外部插件,希望能订阅他们自己的消息类型。EasyNetQ为了这个目标提供了非泛型的发布和订阅方法。
只要加上这个using语句:
using EasyNetQ.NonGeneric;
它将提供给你一些subscription扩展方法。
public static IDisposable Subscribe(
this IBus bus,
Type messageType,
string subscriptionId,
Action<object> onMessage)
public static IDisposable Subscribe(
this IBus bus,
Type messageType,
string subscriptionId,
Action<object> onMessage,
Action<ISubscriptionConfiguration> configure)
public static IDisposable SubscribeAsync(
this IBus bus,
Type messageType,
string subscriptionId,
Func<object, Task> onMessage)
public static IDisposable SubscribeAsync(
this IBus bus,
Type messageType,
string subscriptionId,
Func<object, Task> onMessage,
Action<ISubscriptionConfiguration> configure)
还包括发布扩展方法:
public static void Publish(
this IBus bus,
Type messageType,
object message)
public static void Publish(
this IBus bus,
Type messageType,
object message,
string topic)
public static Task PublishAsync(
this IBus bus,
Type messageType,
object message)
public static Task PublishAsync(
this IBus bus,
Type messageType,
object message,
string topic)
它们就像IBus上的Publish和Subscribe方法一样,除了提供一个Type参数,作为泛型参数的替代,消息处理器用Action替代了Action。
var messageType = typeof(MyMessage);
bus.Subscribe(messageType, "my_subscriptionId", x =>
{
var message = (MyMessage)x;
Console.Out.WriteLine("Got Message: {0}", x.Text);
});
这里有一个例子,使用了非泛型的Publish。
var messageType = typeof(MyMessage);
bus.Publish(messageType, theMessage);
英文地址:https://github.com/EasyNetQ/EasyNetQ/wiki/Non-generic-publish-%26-subscription-extension-methods
本文地址: http://www.cnblogs.com/HuangLiang/p/EasyNetQ-Non-generic-publish-subscription-extension-methods.html
我的微信订阅号:open_dotNET