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

本文介绍了如何在ASP.NET Core中使用SignalR客户端库(5.0.17版)进行实时通信。首先,展示了如何在客户端引入SignalR.Client并配置自动重连功能。接着,通过依赖注入将SignalR客户端注册为单例,并在控制器中注入以使用。最后,给出了发送和接收消息的方法示例。
摘要由CSDN通过智能技术生成

一、首先在客户端进行引入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");
        }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值