RPC集成使用
在该篇文章,我主要使用了中间件代理的方式处理了微服务内部的负载均衡请求,那么在RPC的层面基本上就不需要花多余的功夫进行集成与扩展。
下面以WebApiClient作为例子展示如何做微服务调用(按需可以使用gRPC,思路与实现方式差不多)
调用端
注册到IOC /// <summary> /// 注册消息服务内部api /// </summary> /// <param name="services"></param> /// <param name="configuration"></param> private static void AddMsgApi(this IServiceCollection services, IConfiguration configuration) { services.AddHttpApi<ITest>().ConfigureHttpApiConfig(c => { c.HttpHost = new Uri("http://192.168.88.143:9999/Msg/"); c.FormatOptions.DateTimeFormat = "yyyy-MM-dd HH:mm:ss"; }); } RPC API调用 private readonly IUser _iUser; private readonly ICode _iCode; private readonly IId _id; public UserController(IUser iUser, ICode iCode, IId id, IHttpContextAccessor httpContextAccessor) { _iUser = iUser; _iCode = iCode; _id = id; } #region 无登录验证请求 /// <summary> /// 注册 /// </summary> /// <param name="registerRequest"></param> /// <returns></returns> [HttpPost("Register")] [AllowAnonymous] public async Task<ApiResult<UserLogonResponse>> RegisterUser(UserRegisterRequest registerRequest) { //手机验证 var codeVaildResult = await _iCode.Vaild(registerRequest.CountryCode + registerRequest.Phone, registerRequest.Code); if (codeVaildResult.Failed) return codeVaildResult.ToApiResult<UserLogonResponse>(); registerRequest.UserNo = await _id.Create("D4"); var registerResult = await _iUser.RegisterUser(registerRequest.MapTo<RegisterUserRequest>()); if (registerResult.Failed) return ApiResult<UserLogonResponse>.IsFailed("注册成功"); var token = BuildJwt(registerResult.Data.MapTo<AdministratorData>()); var response = registerResult.Data.MapTo<UserLogonResponse>(); response.Token = token; return ApiResult<UserLogonResponse>.IsSuccess("注册成功", response); }
服务端
Api SDK提供 public interface ITest : IHttpApi { /// <returns></returns> [HttpGet("Test/Index")] ITask<ServiceResult> Test(); } Api逻辑 [Route("[controller]/[action]")] [ApiController] public class TestController : Controller { [HttpGet] public string Index() { var networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); string localIp = NetworkInterface.GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()) .SelectMany(p => p.UnicastAddresses) .FirstOrDefault(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address))?.Address.ToString(); var result = new List<string>(); var b = NetworkInterface.GetAllNetworkInterfaces() .Select(p => p.GetIPProperties()) .SelectMany(p => p.UnicastAddresses) .Where(p => p.Address.AddressFamily == AddressFamily.InterNetwork && !IPAddress.IsLoopback(p.Address)) .Select(a => { return new { Address = a.Address.ToStr() }; }).ToList(); return b.ToJson() + "------" + localIp; } }