Asp.Net Core使用SignalR进行服务间调用(1)

  • Post author:
  • Post category:其他

一、首先在客户端进行引入Microsoft.AspNetCore.SignalR.Client(5.0.17)netcore3.1环境

并对SignalR.Client相关封装操作(必须使用5.0.17否则部署iis会报错);

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;

namespace SignalRClient
{
    /// <summary>
    /// 
    /// </summary>
    public class SignalRClient
    {
        private readonly HubConnection connection;
        private readonly IHttpContextAccessor _httpContextAccessor;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="httpContextAccessor"></param>
        public SignalRClient(IHttpContextAccessor httpContextAccessor)
        {
            var Uri = "http://127.0.0.1:12345/signalr/pushHub?access_token=";
            if (!string.IsNullOrEmpty(Uri))
            {
                try
                {
                    _httpContextAccessor = httpContextAccessor;
                    var Authorization = _httpContextAccessor ?.HttpContext?.Request?.Headers["Authorization"];
                    var token = Authorization.GetValueOrDefault().ToString().Replace("Bearer ", "");
                    connection = new HubConnectionBuilder()
                       .WithUrl(new Uri($"{Uri}{token}"))
                      .WithAutomaticReconnect()//自动重新连接
                      .Build();
                    connection.ServerTimeout = TimeSpan.FromSeconds(30);
                    //心跳检查
                    connection.KeepAliveInterval = TimeSpan.FromSeconds(15);
                    #region 等待3s后重新创建连接
                    //connection.Closed += async (error) =>
                    //{
                    //    await Task.Delay(new Random().Next(0, 5) * 1000);
                    //    await connection.StartAsync();
                    //};
                    #endregion
                    InitOnMethod();
                    connection.StartAsync();
                }
                catch (Exception ex)
                {
                    throw new BusinessException(ex.ToString());
                }
            }
            else
            {
                throw new BusinessException("请配置SignalR:Uri.");
            }
        }

        /// <summary>
        /// 服务方回调的监听事件,最好不使用
        /// </summary>
        private void InitOnMethod()
        {
            connection.On<string>("Callback", (msg) =>
            {
                Console.WriteLine($"------------{msg}----------");
            });
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public async Task<string> SendWithResult(string methodName = "ReceiveWithResult", string msg = "")
        {
            if (!string.IsNullOrEmpty(msg))
            {
                var result = await connection.InvokeAsync<string>(methodName, msg);
                return result;
            }
            else
            {
                return null;
            }
        }


        /// <summary>
        /// 发送后无返回值
        /// </summary>
        /// <returns></returns>
        public async Task SendWithoutResult(string methodName = "ReceiveWithoutResult", string msg = "")
        {
            if (!string.IsNullOrEmpty(msg))
            {
                await connection.SendAsync(methodName, msg);
            }
        }
    }
}

二、将SignalRClient以单例形式注册依赖注入services.AddSingleton<SignalRClient>();

三、构造函数注入并使用

      

    /// <summary>
    /// 应用检查程序管理
    /// </summary>
    [Route("api/[controller]")]
    public class HealthCheckAppController : Controller
    {
        private readonly ILogger _logger;
        private readonly IHealthCheckAppService _healthCheckAppService;
        private readonly SignalRClient _signalRClient;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="healthCheckAppService"></param>
        /// <param name="signalRClient"></param>
        public HealthCheckAppController(
           ILogger logger,
         IHealthCheckAppService healthCheckAppService,
         SignalRClient signalRClient
           )
        {
            _logger = logger;
            _healthCheckAppService = healthCheckAppService;
            _signalRClient = signalRClient;
        }


        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Route("GetListAsync")]
        [HttpGet]
        public async Task<IActionResult> GetListAsync()
        {
            await _signalRClient.SendWithResult("ReceiveWithResult", "msg");
        }
}


版权声明:本文为qq165285727原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。