环境:
NetMQ版本:4.0.0.1
操作系统:Windows Server 2014
.NET版本:.NET 4.7
问题:
我有一个Windows服务,该服务正在接受来自.NET Web API的请求。 该服务实例化一个RouterSocket,以便它可以从Web api层接收许多消息并将其转发到我们的内部系统。内部系统返回一个响应,该响应被发送回Web服务层,该Web服务层将响应转发给客户端。
代码如下:
private RouterSocket _socket;
public void StartServer() {
_socket = new RouterSocket();
_socket.Bind(_netmqConnStr);
while (_listening) {
var msg = _socket.ReceiveMultipartMessage();
var identity = msg.Pop().ConvertToString();
var x = msg.Pop().ConvertToString();
// empty frame
var data = msg.Pop().ConvertToString();
_logger.Debug($"Incoming Message - Identity: {identity}, Data: {data}");
// I see logs for a while then nothing!
ForwardMessage(identity, data);
}
}
public async Task SendMessage(string identity, int errorCode, string response) {
NetMQMessage message = new NetMQMessage();
message.Append(System.Text.Encoding.ASCII.GetBytes(identity));
message.AppendEmptyFrame();
message.Append(errorCode);
message.Append(response);
_socket.SendMultipartMessage(message);
_logger.Debug(String.Format("Send to WebAPI - Error code: {0}, Response: {1}", errorCode, response));
}
我使用以下代码从WebAPI连接到Windows服务(在同一服务器上运行):
public async Task<IHttpActionResult> Post(MyModel inputModel) {
using (var requestSocket = new RequestSocket()) {
requestSocket.Options.Identity = System.Text.Encoding.ASCII.GetBytes(GetUniqueID());
try {
requestSocket.Connect(Constants.BackEndAddress);
}
catch(Exception e) {
_logger.Error(e);
return InternalServerError();
}
NetMQMessage message = new NetMQMessage();
message.Append(JsonConvert.SerializeObject(inputModel));
try {
requestSocket.SendMultipartMessage(message);
}
catch(Exception e) {
_logger.Error($"Unable to submit message to Windows Service: {soupMsg}");
return InternalServerError(new Exception("Unable to foward your message."));
}
if (!requestSocket.TryReceiveMultipartMessage(TimeSpan.FromSeconds(5), ref message)) {
_logger.Error("Did not receive a response from the Windows Service in the time allotted.");
return InternalServerError(new Exception("Did not receive a response from the gateway in the time allotted."));
}
var errorCode = message.Pop().ConvertToInt32();
var result = message.Pop().ConvertToString();
var status = false;
_logger.Info(result);
switch (errorCode) {
case 0:
return BadRequest(result);
case 1:
return Ok();
default:
return InternalServerError(new Exception("Unknown error"));
}
}
}
我使用邮递员的Collection Runner(两个实例来模拟2位客户),我尝试每秒发送1000条消息。当我开始发送消息时,我看到传入消息已记录到数据库中。
过了一会儿,大约有430条消息(每位选手有1/2条消息),我不再看到“传入消息”日志条目。相反,我开始从Web API Did not receive a response from the Windows Service in the time allotted.
看到TryReceiveMultipartMessage(TimeSpan.FromSeconds(5)
错误。从API层调用SendMultipartMessage时不会出现异常。
为什么Windows服务不能接收API提交的消息? API为什么认为它已成功将消息发送到Windows服务?