public async Task <T> Send <T>(object message) { try { _logger.LogDebug("准备发送消息"); var microMessage = new MicroMessage(message); var callback = RegistCallbackAsync <T>(microMessage.Id); try { _logger.LogDebug($"{_sender.GetType()}:send :{JsonConvert.SerializeObject(microMessage)}"); //发送 await _sender.Send(microMessage); } catch (Exception exception) { _logger.LogError(exception, "与服务端通讯时发生了异常"); throw new SpearException("与服务端通讯时发生了异常"); } _logger.LogDebug("消息发送成功"); return(await callback); } catch (Exception ex) { _logger.LogError(ex, "消息发送失败。"); throw new SpearException("消息发送失败"); } }
public async Task <T> Send <T>(object message) { try { _logger.Debug("准备发送消息"); var microMessage = new MicroMessage(message); var callback = RegistCallbackAsync <T>(microMessage.Id); try { //发送 await _sender.Send(microMessage); } catch (Exception exception) { _logger.Error("与服务端通讯时发生了异常", exception); throw new BusiException("与服务端通讯时发生了异常"); } _logger.Debug("消息发送成功"); return(await callback); } catch (Exception ex) { _logger.Error("消息发送失败。", ex); throw new BusiException("消息发送失败"); } }
private void AppResolve(IApplicationBuilder app) { app.UseMvc(routes => { //routes.MapGet("micro", async ctx => await MicroServiceRunner.Methods(ctx)); routes.MapPost("micro", async(request, response, route) => { //route.Values.TryGetValue("contract", out var contract); //route.Values.TryGetValue("method", out var method); var sender = new HttpServerMessageSender(_codecFactory.GetEncoder(), response); try { await OnReceived(sender, request); } catch (Exception ex) { var result = new ResultMessage(); if (ex is SpearException busi) { result.Code = busi.Code; result.Message = busi.Message; } else { var logger = app.ApplicationServices.GetService <ILogger <HttpMicroListener> >(); logger.LogError(ex, ex.Message); result.Code = (int)HttpStatusCode.InternalServerError; result.Message = ex.Message; } await sender.Send(MicroMessage.CreateResultMessage(Guid.NewGuid().ToString("N"), result)); } }); }); }
private async Task MessageListenerReceived(IMessageSender sender, MicroMessage message) { _logger.Info($"receive:{JsonHelper.ToJson(message)}"); await _microExecutor.Execute(sender, message); //await MicroListener.OnReceived(sender, message); }
public async Task Send(MicroMessage message, bool flush = true) { if (!message.IsInvoke) { return; } var invoke = message.GetContent <InvokeMessage>(); var uri = new Uri(new Uri(_url), "micro/executor"); var client = _clientFactory.CreateClient(); var req = new HttpRequestMessage(HttpMethod.Post, uri.AbsoluteUri); if (invoke.Headers != null) { foreach (var header in invoke.Headers) { req.Headers.Add(header.Key, header.Value); } } var data = _codecFactory.GetEncoder().Encode(message); req.Content = new ByteArrayContent(data); var resp = await client.SendAsync(req); if (!resp.IsSuccessStatusCode) { throw new SpearException($"服务请求异常,状态码{(int)resp.StatusCode}"); } var content = await resp.Content.ReadAsByteArrayAsync(); var result = _codecFactory.GetDecoder().Decode(content); await _messageListener.OnReceived(this, result); }
public async Task Send(MicroMessage message, bool flush = true) { if (!message.IsInvoke) { return; } var invoke = message.GetContent <InvokeMessage>(); var uri = new Uri(new Uri(_url), "micro"); var client = _clientFactory.CreateClient(); var req = new HttpRequestMessage(HttpMethod.Post, uri.AbsoluteUri); if (invoke.Headers != null) { foreach (var header in invoke.Headers) { req.Headers.Add(header.Key, header.Value); } } var data = _codecFactory.GetEncoder().Encode(message); req.Content = new ByteArrayContent(data); //req.Content = new StringContent(data Encoding.UTF8, "application/json"); var resp = await client.SendAsync(req); var content = await resp.Content.ReadAsByteArrayAsync(); var result = _codecFactory.GetDecoder().Decode(content); await _messageListener.OnReceived(this, result); }
public async Task OnReceived(IMessageSender sender, MicroMessage message) { if (Received == null) { return; } await Received(sender, message); }
private async Task MessageListenerReceived(IMessageSender sender, MicroMessage message) { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"receive:{JsonConvert.SerializeObject(message)}"); } await _microExecutor.Execute(sender, message); }
/// <summary> 发送消息 </summary> /// <param name="message">消息内容</param> /// <param name="flush">清空缓冲池</param> /// <returns>一个任务。</returns> public async Task Send(MicroMessage message, bool flush = true) { var buffer = GetByteBuffer(message); if (flush) { await _context.WriteAndFlushAsync(buffer); } else { await _context.WriteAsync(buffer); } }
public async Task Send(MicroMessage message, bool flush = true) { if (!message.IsResult) { return; } var data = _encoder.Encode(message); var contentLength = data.Length; _response.Headers.Add("Content-Type", "application/json"); _response.Headers.Add("Content-Length", contentLength.ToString()); await _response.Body.WriteAsync(data, 0, data.Length); if (flush) { await _response.Body.FlushAsync(); } }
public async Task <T> Send <T>(object message) { var watch = Stopwatch.StartNew(); try { _logger.LogDebug("准备发送消息"); var microMessage = new MicroMessage(message); var callback = RegistCallbackAsync <T>(microMessage.Id); try { if (_logger.IsEnabled(LogLevel.Debug)) { _logger.LogDebug($"{_sender.GetType()}:send :{JsonConvert.SerializeObject(microMessage)}"); } //发送 await _sender.Send(microMessage); } catch (Exception exception) { if (exception is SpearException) { throw; } _logger.LogError(exception, "与服务端通讯时发生了异常"); throw new SpearException("与服务端通讯时发生了异常"); } _logger.LogDebug("消息发送成功"); return(await callback); } catch (Exception ex) { _logger.LogError(ex, "消息发送失败。"); throw new SpearException("消息发送失败"); } finally { watch.Stop(); _logger.LogDebug($"send message {watch.ElapsedMilliseconds} ms"); } }
private void AppResolve(IApplicationBuilder app) { app.UseMvc(routes => { routes.MapGet("micro", async ctx => { var services = _entryFactory.Services.ToDictionary(k => $"micro/{k.Key}", v => v.Value.Parameters.ToDictionary(pk => pk.Name, pv => pv.ParameterType.GetTypeInfo().Name)); ctx.Response.ContentType = "application/json"; await ctx.Response.WriteAsync(JsonConvert.SerializeObject(services), Encoding.UTF8); }); routes.MapPost("micro/executor", async(request, response, route) => { //route.Values.TryGetValue("serviceId", out var serviceId); var sender = new HttpServerMessageSender(_codecFactory.GetEncoder(), response); try { await OnReceived(sender, request); } catch (Exception ex) { var result = new ResultMessage(); if (ex is SpearException busi) { result.Code = busi.Code; result.Message = busi.Message; } else { _logger.LogError(ex, ex.Message); result.Code = (int)HttpStatusCode.InternalServerError; result.Message = ex.Message; } await sender.Send(MicroMessage.CreateResultMessage(Guid.NewGuid().ToString("N"), result)); } }); //routes.MapRoute("default", "{controller=Home}/{action=Index}/{Id?}"); }); }
private async Task ListenerOnReceived(IMessageSender sender, MicroMessage message) { if (!_resultDictionary.TryGetValue(message.Id, out var task)) { return; } if (message.IsResult) { var content = message.GetContent <ResultMessage>(); if (content.Code != 200) { task.TrySetException(new SpearException(content.Message, content.Code)); } else { task.SetResult(message); } } if (_executor != null && message.IsInvoke) { await _executor.Execute(sender, message); } }
public byte[] Encode(MicroMessage message) { var content = JsonConvert.SerializeObject(message); return(Encoding.UTF8.GetBytes(content)); }
protected void Page_Load(object sender, EventArgs e) { _CommonApi = new CommonApi(); _Common = new Common(); _ContentApi = new ContentAPI(); _PageTitle = ""; _PageUrl = ""; _PageDescription = ""; _MessageHelper = _ContentApi.EkMsgRef; _MaxDescriptionLength = 200; _MicroMessage = new MicroMessage(); _MicroMessageData = new MicroMessageData(); Utilities.ValidateUserLogin(); RegisterResources(); // if the user is already logged in, hide the login panel and reveal the share form if (_Common.UserId > 0) { // set panels to proper visibility loginControlPanel.Visible = false; shareFormPanel.Visible = true; // assign string values as appropriate shareHeader.Text = _MessageHelper.GetMessage("post to profile"); commentsLabel.Text = _MessageHelper.GetMessage("share this comments label"); sharePost.Text = _MessageHelper.GetMessage("share"); sharePost.ToolTip = sharePost.Text; cancelPost.Text = _MessageHelper.GetMessage("generic cancel"); cancelPost.ToolTip = cancelPost.Text; characterLimitExceededHeader.Text = _MessageHelper.GetMessage("generic max character"); characterLimitExceededBody.Text = _MessageHelper.GetMessage("micromessagingbookmarklet character limit exceeded"); maxLength.Text = _MaxDescriptionLength.ToString(); // page title if (!String.IsNullOrEmpty(Request.QueryString["t"])) { _PageTitle = Request.QueryString["t"]; if (_PageTitle.Length > 0) { pageTitle.Text = _PageTitle; pageTitleField.Text = _PageTitle; } } // page URL if (!String.IsNullOrEmpty(Request.QueryString["url"])) { _PageUrl = Request.QueryString["url"]; pageUrl.Text = _PageUrl; pageUrlField.Text = _PageUrl; } // page Description if (!String.IsNullOrEmpty(Request.QueryString["ds"])) { _PageDescription = TruncateString(Request.QueryString["ds"].ToString(), _MaxDescriptionLength, TruncateOptions.IncludeEllipsis | TruncateOptions.FinishWord); pageDescription.Text = _PageDescription; pageDescriptionField.Text = _PageDescription; } } }
protected IByteBuffer GetByteBuffer(MicroMessage message) { var data = _messageEncoder.Encode(message); return(Unpooled.WrappedBuffer(data)); }