// 对外提供网关/注册中心 public static IApplicationBuilder UseSimpleMSGateway(this IApplicationBuilder app, string prefix = "/api") { if (Singletons.Option.LocalPort == 0) { throw new ArgumentException("必须指定本地服务端口号"); } Singletons.EnableGateway = true; app.Use(async(_ctx, _next) => { string _path = _ctx.Request.Path.Value; bool _register = _path == "/_simplems_/register", _callmethod = _path.StartsWith(prefix); if (_register || _callmethod) { var _bytes = new byte [_ctx.Request.ContentLength ?? 0]; if (_register && _bytes.Length == 0) { await _ctx.Response.WriteAsync("网关注册中心已架设成功,可通过这个地址来注册微服务"); return; } if (_bytes.Length > 0) { await _ctx.Request.Body.ReadAsync(_bytes, 0, _bytes.Length); } string _resp = ""; if (_register) { JObject _obj = JObject.Parse(Encoding.UTF8.GetString(_bytes)); string _host = _ctx.Request.Host.Host; int _port = _obj ["port"].ToObject <int> (); var _local = _obj ["local"].ToObject <List <string> > (); var _remote = _obj ["remote"].ToObject <List <string> > (); var _ret = BackThread.AddService(_host, _port, _local, _remote); _resp = JsonConvert.SerializeObject(_ret); } else if (_callmethod) { string _module_name = _ctx.Request.Query ["module"].ToString(); if (!_module_name.Contains(':')) { _module_name = $"{_module_name}:"; } var _method_name = _ctx.Request.Query ["method"].ToString(); _resp = await _process_method_call(_module_name, _method_name, Encoding.UTF8.GetString(_bytes)); } await _ctx.Response.WriteAsync(_resp); } else { await _next(); } }); return(app); }
public static IServiceCollection AddSimpleMS(this IServiceCollection services, Action <ServiceUpdateOption> option = null) { if (Singletons.Option != null) { throw new NotSupportedException("请确保 services.AddSimpleMS () 只被调用一次"); } var _option = new ServiceUpdateOption(services); option?.Invoke(_option); Singletons.Option = _option; var(_local, _remote) = ImplTypeBuilder.InitInterfaces(); if (Singletons.Option.DiscoveryType == DiscoveryTypeEnum.RegCenter) { BackThread.Start(_local, _remote); } return(services); }