-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMsgRouter.cs
More file actions
288 lines (244 loc) · 9.21 KB
/
MsgRouter.cs
File metadata and controls
288 lines (244 loc) · 9.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Collections;
using DigitalPlatform;
using DigitalPlatform.MessageClient;
using DigitalPlatform.Message;
namespace dp2Command.Service
{
public class MsgRouter : ThreadBase
{
public event SendMessageEventHandler SendMessageEvent = null;
// 这里是引用外部的对象,不负责创建和销毁
public MessageConnectionCollection Channels = null;
public string Url { get; set; }
public string GroupName { get; set; }
// 存储从 AddMessage() 得到的消息
List<MessageRecord> _messageList = new List<MessageRecord>();
private static readonly Object _syncRoot_messageList = new Object();
// 记忆已经发送过的消息,避免重复发送
Hashtable _sendedTable = new Hashtable();
public MsgRouter()
{
this.PerTime = 60 * 1000; // 60 * 1000
}
public void Start(MessageConnectionCollection channels,
string url,
string groupName)
{
this.Url = url;
this.GroupName = groupName;
this.Channels = channels;
//Channels.Login += _channels_Login;
Channels.AddMessage -= _channels_AddMessage;
Channels.AddMessage += _channels_AddMessage;
Channels.ConnectionStateChange -= _channels_ConnectionStateChange;
Channels.ConnectionStateChange += _channels_ConnectionStateChange;
this.BeginThread();
}
public void Stop()
{
Channels.AddMessage -= _channels_AddMessage;
Channels.ConnectionStateChange -= _channels_ConnectionStateChange;
this.StopThread(false);
}
void _channels_ConnectionStateChange(object sender, ConnectionEventArgs e)
{
if (e.Action == "Reconnected"
|| e.Action == "Connected")
{
this.Activate();//激活线程
}
}
void _channels_AddMessage(object sender, AddMessageEventArgs e)
{
if (e.Action != "create")
return;
lock (_syncRoot_messageList)
{
// 累积太多了就不送入 list 了,只是激活线程等 GetMessage() 慢慢一百条地处理
if (this._messageList.Count < 10000)
this._messageList.AddRange(e.Records);
}
this.Activate();
}
// 工作线程每一轮循环的实质性工作
public override void Worker()
{
//this.WriteLog("走到worker1");
List<MessageRecord> records = GetMessage();
if (records.Count > 0)
{
lock (_syncRoot_messageList)
{
this._messageList.AddRange(records);
}
}
//this.WriteErrorLog("走到worker2:" +records.Count);
if (this._messageList.Count > 0)
{
// 取出前面 100 个加以处理
// 这样锁定的时间很短
List<MessageRecord> temp_records = new List<MessageRecord>();
lock (_syncRoot_messageList)
{
int i = 0;
foreach(MessageRecord record in this._messageList)
{
if (i >= 100)
break;
temp_records.Add(record);
i++;
}
this._messageList.RemoveRange(0, temp_records.Count);
}
//this.WriteErrorLog("走到worker3:" + temp_records.Count);
// 发送消息给下游模块
SendMessage(temp_records);
//this.WriteErrorLog("走到worker4:");
// 从 dp2mserver 中删除这些消息
DeleteMessage(temp_records, this.GroupName);
//this.WriteErrorLog("走到worker5:");
}
// 如果本轮主动获得过消息,就要连续激活线程,让线程下次继续处理。只有本轮发现没有新消息了,才会进入休眠期
if (records.Count > 0)
this.Activate();
CleanSendedTable(); // TODO: 可以改进为判断间隔至少 5 分钟才做一次
}
// 将消息发送给下游模块
void SendMessage(List<MessageRecord> records)
{
SendMessageEventHandler handler = this.SendMessageEvent;
foreach (MessageRecord record in records)
{
if (this._sendedTable.ContainsKey(record.id))
continue;
this.WriteLog("开始处理:" + record.id);
// 发送
if (handler != null)
{
SendMessageEventArgs e = new SendMessageEventArgs();
e.Message = record;
handler(this, e);
}
this.WriteLog("处理结束:" + record.id);
this._sendedTable[record.id] = DateTime.Now;
}
}
// 清理超过一定时间的“已发送”记忆事项
void CleanSendedTable()
{
DateTime now = DateTime.Now;
TimeSpan delta = new TimeSpan(0, 30, 0);
List<string> delete_keys = new List<string>();
foreach (string key in this._sendedTable.Keys)
{
var time = (DateTime)this._sendedTable[key];
if (time - now > delta)
delete_keys.Add(key);
}
foreach (string key in delete_keys)
{
this._sendedTable.Remove(key);
}
}
void WriteLog(string strText)
{
dp2CmdService2.Instance.WriteLog(strText);
//MessageRecord record = new MessageRecord();
//record.data = "*** error *** " + strText;
//SendMessageEventArgs e = new SendMessageEventArgs();
//e.Message = record;
//this.SendMessageEvent(this, e);
}
// 从 dp2mserver 获得消息
// 每次最多获得 100 条
List<MessageRecord> GetMessage()
{
string strError = "";
CancellationToken cancel_token = new CancellationToken();
string id = Guid.NewGuid().ToString();
GetMessageRequest request = new GetMessageRequest(id,
"",
this.GroupName, // "" 表示默认群组
"",
"", // strTimeRange,
0,
100);
try
{
MessageConnection connection = this.Channels.GetConnectionAsync(
this.Url,
"").Result;
GetMessageResult result = connection.GetMessageAsync(
request,
new TimeSpan(0, 1, 0),
cancel_token).Result;
if (result.Value == -1)
goto ERROR1;
return result.Results;
}
catch (AggregateException ex)
{
strError = MessageConnection.GetExceptionText(ex);
goto ERROR1;
}
catch (Exception ex)
{
strError = ex.Message;
goto ERROR1;
}
ERROR1:
this.WriteLog("GetMessage() error: " + strError);
return new List<MessageRecord>();
}
void DeleteMessage(List<MessageRecord> records,
string strGroupName)
{
List<MessageRecord> delete_records = new List<MessageRecord>();
foreach (MessageRecord source in records)
{
MessageRecord record = new MessageRecord();
record.groups = strGroupName.Split(new char[] { ',' });
record.id = source.id;
delete_records.Add(record);
}
string strError = "";
// CancellationToken cancel_token = new CancellationToken();
try
{
MessageConnection connection = this.Channels.GetConnectionAsync(
this.Url,
"").Result;
SetMessageRequest param = new SetMessageRequest("expire",
"dontNotifyMe",
records);
SetMessageResult result = connection.SetMessageAsync(param).Result;
if (result.Value == -1)
goto ERROR1;
}
catch (AggregateException ex)
{
strError = MessageConnection.GetExceptionText(ex);
goto ERROR1;
}
catch (Exception ex)
{
strError = ex.Message;
goto ERROR1;
}
return;
ERROR1:
this.WriteLog("DeleteMessage() error : " + strError);
}
}
public delegate void SendMessageEventHandler(object sender,
SendMessageEventArgs e);
public class SendMessageEventArgs : EventArgs
{
public MessageRecord Message = null;
}
}