forked from ServiceStack/ServiceStack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMessageHandler.cs
More file actions
210 lines (180 loc) · 7.91 KB
/
MessageHandler.cs
File metadata and controls
210 lines (180 loc) · 7.91 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
using System;
using System.Text;
using ServiceStack.Common;
using ServiceStack.Logging;
using ServiceStack.Service;
using ServiceStack.ServiceClient.Web;
using ServiceStack.Text;
using StringExtensions = ServiceStack.Common.StringExtensions;
namespace ServiceStack.Messaging
{
/// <summary>
/// Processes all messages in a Normal and Priority Queue.
/// Expects to be called in 1 thread. i.e. Non Thread-Safe.
/// </summary>
/// <typeparam name="T"></typeparam>
public class MessageHandler<T>
: IMessageHandler, IDisposable
{
private static readonly ILog Log = LogManager.GetLogger(typeof(MessageHandler<T>));
public const int DefaultRetryCount = 2; //Will be a total of 3 attempts
private readonly IMessageService messageService;
private readonly Func<IMessage<T>, object> processMessageFn;
private readonly Action<IMessage<T>, Exception> processInExceptionFn;
public Func<string, IOneWayClient> ReplyClientFactory { get; set; }
private readonly int retryCount;
public int TotalMessagesProcessed { get; private set; }
public int TotalMessagesFailed { get; private set; }
public int TotalRetries { get; private set; }
public int TotalNormalMessagesReceived { get; private set; }
public int TotalPriorityMessagesReceived { get; private set; }
public int TotalOutMessagesReceived { get; private set; }
public string[] ProcessQueueNames { get; set; }
public MessageHandler(IMessageService messageService,
Func<IMessage<T>, object> processMessageFn)
: this(messageService, processMessageFn, null, DefaultRetryCount) {}
private IMessageQueueClient MqClient { get; set; }
public MessageHandler(IMessageService messageService,
Func<IMessage<T>, object> processMessageFn,
Action<IMessage<T>, Exception> processInExceptionFn,
int retryCount)
{
if (messageService == null)
throw new ArgumentNullException("messageService");
if (processMessageFn == null)
throw new ArgumentNullException("processMessageFn");
this.messageService = messageService;
this.processMessageFn = processMessageFn;
this.processInExceptionFn = processInExceptionFn ?? DefaultInExceptionHandler;
this.retryCount = retryCount;
this.ReplyClientFactory = ClientFactory.Create;
this.ProcessQueueNames = new[] { QueueNames<T>.Priority, QueueNames<T>.In };
}
public Type MessageType
{
get { return typeof(T); }
}
public void Process(IMessageQueueClient mqClient)
{
foreach (var processQueueName in ProcessQueueNames)
{
ProcessQueue(mqClient, processQueueName);
}
}
public int ProcessQueue(IMessageQueueClient mqClient, string queueName, Func<bool> doNext = null)
{
var msgsProcessed = 0;
try
{
byte[] messageBytes;
while ((messageBytes = mqClient.GetAsync(queueName)) != null)
{
var message = messageBytes.ToMessage<T>();
ProcessMessage(mqClient, message);
this.TotalNormalMessagesReceived++;
msgsProcessed++;
if (doNext != null && !doNext()) return msgsProcessed;
}
}
catch (Exception ex)
{
var lastEx = ex;
Log.Error("Error serializing message from mq server: " + lastEx.Message, ex);
}
return msgsProcessed;
}
public IMessageHandlerStats GetStats()
{
return new MessageHandlerStats(typeof(T).Name,
TotalMessagesProcessed, TotalMessagesFailed, TotalRetries,
TotalNormalMessagesReceived, TotalPriorityMessagesReceived);
}
private void DefaultInExceptionHandler(IMessage<T> message, Exception ex)
{
Log.Error("Message exception handler threw an error", ex);
if (!(ex is UnRetryableMessagingException))
{
if (message.RetryAttempts < retryCount)
{
message.RetryAttempts++;
this.TotalRetries++;
message.Error = new MessagingException(ex.Message, ex).ToMessageError();
MqClient.Publish(QueueNames<T>.In, message.ToBytes());
return;
}
}
MqClient.Publish(QueueNames<T>.Dlq, message.ToBytes());
}
public void ProcessMessage(IMessageQueueClient mqClient, Message<T> message)
{
this.MqClient = mqClient;
try
{
var response = processMessageFn(message);
var responseEx = response as Exception;
if (responseEx != null)
throw responseEx;
this.TotalMessagesProcessed++;
//If there's no response publish the request message to its OutQ
if (response == null)
{
var messageOptions = (MessageOption)message.Options;
if (messageOptions.Has(MessageOption.NotifyOneWay))
{
mqClient.Notify(QueueNames<T>.Out, message.ToBytes());
}
}
else
{
//If there is a response send it to the typed response OutQ
var mqReplyTo = message.ReplyTo;
if (mqReplyTo == null)
{
var responseType = response.GetType();
if (!responseType.IsUserType()) return;
mqReplyTo = new QueueNames(responseType).In;
}
var replyClient = ReplyClientFactory(mqReplyTo);
if (replyClient != null)
{
try
{
replyClient.SendOneWay(mqReplyTo, response);
return;
}
catch (Exception ex)
{
Log.Error("Could not send response to '{0}' with client '{1}'"
.Fmt(mqReplyTo, replyClient.GetType().Name), ex);
var responseType = response.GetType();
if (!responseType.IsUserType()) return;
mqReplyTo = new QueueNames(responseType).In;
}
}
//Otherwise send to our trusty response Queue (inc if replyClient fails)
var responseMessage = MessageFactory.Create(response);
responseMessage.ReplyId = message.Id;
mqClient.Publish(mqReplyTo, responseMessage.ToBytes());
}
}
catch (Exception ex)
{
try
{
TotalMessagesFailed++;
processInExceptionFn(message, ex);
}
catch (Exception exHandlerEx)
{
Log.Error("Message exception handler threw an error", exHandlerEx);
}
}
}
public void Dispose()
{
var shouldDispose = messageService as IMessageHandlerDisposer;
if (shouldDispose != null)
shouldDispose.DisposeMessageHandler(this);
}
}
}