NBear.MQ是NBearFramework中新增的分布式消息隊列模塊,作為NBear Framework的新成員,NBear.MQ秉承NBear一貫的易於使用和零配置需要的特點,大大改善開發基於消息隊列的分布式系統的效率。本文通過介紹一個基於NBear.MQ的Sample - TestServiceMQ,演示基於NBear.MQ開發分布式系統的基本方法。
解析
1、TestRemotingServer
首先是我們的Server,對於Server,如果您使用NBear.MQ內置的MemoryServiceMQ,則幾乎不需要編碼,只需要運行並發布server實例為remoting service。
1 class Program
2 {
3 static void Main(string[] args)
4 {
5 MemoryServiceMQ mq = new MemoryServiceMQ();
6 mq.OnLog = new LogHandler(Console.WriteLine);
7 RemotingServiceHelper rh =
8 new RemotingServiceHelper(RemotingChannelType.TCP, "127.0.0.1", 8000, new LogHandler(Console.WriteLine));
9 rh.PublishServiceInstance("MMQ", typeof(IServiceMQ), mq, System.Runtime.Remoting.WellKnownObjectMode.Singleton);
10
11 while (Console.ReadLine() != "q")
12 {
13 }
14 }
15 }
注意,關鍵是第8-9行這裡,我們調用RemotingServiceHelper類發布MemoryServiceMQ的實例mq到tcp://127.0.0.1:8000/MMQ。
如果你不希望使用MemoryServiceMQ,而希望使用基於其它MQ如MSMQ或ActiveMQ系統的MQ控制,您可以自己實現IServiceMQ接口,用來代替這裡的mq。
2、TestServiceHost
Service host顧名思義就是服務的提供者,本示例的TestServiceHost定義了兩個service,MathService和HelloWorldService,如下:
1 public class MathService : BaseAutoService
2 {
3 public MathService(IServiceMQ mq)
4 : base("demo.math", mq)
5 {
6 }
7
8 private int getResult(char op, int x, int y)
9 {
10 int rt = 0;
11 switch (op)
12 {
13 case '+':
14 rt = x + y;
15 break;
16 case '-':
17 rt = x - y;
18 break;
19 case '*':
20 rt = x * y;
21 break;
22 case '/':
23 rt = x / y;
24 break;
25
26 }
27 return rt;
28 }
29
30 protected override ResponseMessage Run(RequestMessage msg)
31 {
32 Parameter[] parms = msg.Parameters;
33 int rt = getResult(parms[0].Value.ToString()[0], int.Parse(parms[1].Value.ToString()), int.Parse(parms[2].Value.ToString()));
34 ResponseMessage retMsg = new ResponseMessage();
35 retMsg.ServiceName = msg.ServiceName;
36 retMsg.Parameters = new Parameter[] { new Parameter("Result", rt) };
37 retMsg.MessageId = Guid.NewGuid();
38 retMsg.TransactionId = msg.TransactionId;
39 retMsg.RequestHeader = msg.Header;
40 retMsg.Timestamp = DateTime.Now;
41 retMsg.Expiration = DateTime.Now.AddDays(1);
42
43 return retMsg;
44 }
45 }
46
47 public class HelloWorldService : BaseAutoService
48 {
49 public HelloWorldService(IServiceMQ mq) : base("demo.helloworld", mq)
50 {
51 }
52
53 protected override ResponseMessage Run(RequestMessage msg)
54 {
55 Parameter[] parms = msg.Parameters;
56 ResponseMessage retMsg = new ResponseMessage();
57 retMsg.ServiceName = msg.ServiceName;
58 retMsg.MessageId = Guid.NewGuid();
59 retMsg.TransactionId = msg.TransactionId;
60 retMsg.RequestHeader = msg.Header;
61 retMsg.Timestamp = DateTime.Now;
62 retMsg.Expiration = DateTime.Now.AddDays(1);
63
64 retMsg.Text = "hello world";
65 retMsg.Bytes = System.Text.UTF8Encoding.UTF8.GetBytes(retMsg.Text);
66 retMsg.Data = new System.Data.DataSet("hello world data");
67
68 return retMsg;
69 }
70 }