Beispiel #1
0
        /// <summary>
        /// 启动并注册服务
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public static Server StartAndRegisterService(this Server server)
        {
            server.Start();
            var ipAndPort = server.Ports.FirstOrDefault();

            if (ipAndPort != null)
            {
                MetaModel.StartTime = DateTime.Now;
                MetaModel.Ip        = ipAndPort.Host;
                MetaModel.Port      = ipAndPort.BoundPort;
                Console.WriteLine($"server listening {MetaModel.Ip}:{MetaModel.Port}");

                //检查服务注册配制
                if (string.IsNullOrWhiteSpace(GrpcServerOptions.Instance.DiscoveryUrl))
                {
                    throw new ArgumentException("GrpcServer:DiscoveryUrl is null");
                }
                if (string.IsNullOrWhiteSpace(GrpcServerOptions.Instance.DiscoveryServiceName))
                {
                    throw new ArgumentException("GrpcServer:DiscoveryServiceName is null");
                }

                //服务注册
                var serviceRegister = ServiceProviderAccessor.GetService <IServiceRegister>();
                Console.WriteLine($"use {serviceRegister.GetType().Name} register");
                Console.WriteLine($"    DiscoveryUrl:{GrpcServerOptions.Instance.DiscoveryUrl}");
                Console.WriteLine($"    ServiceName:{GrpcServerOptions.Instance.DiscoveryServiceName}");
                var registerModel = GrpcServerOptions.Instance.ToJson().FromJson <ServiceRegisterModel>();
                registerModel.ServiceIp   = ipAndPort.Host;
                registerModel.ServicePort = ipAndPort.BoundPort;
                serviceRegister.RegisterService(registerModel);
            }
            return(server);
        }
Beispiel #2
0
        /// <summary>
        /// 注入Grpc,Discovery配制
        /// </summary>
        /// <param name="builder"></param>
        /// <param name="configureOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseGrpcOptions(this IApplicationBuilder builder, Action <GrpcServerOptions> configureOptions)
        {
            var options = ServiceProviderAccessor.GetService <IOptions <GrpcServerOptions> >().Value;

            configureOptions(options);

            return(builder);
        }
Beispiel #3
0
        /// <summary>
        /// GrpcClientApp
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="grpcClientOptions"></param>
        /// <param name="loggerFactory"></param>
        public GrpcClientApp(IServiceProvider serviceProvider, IOptions <GrpcClientOptions> grpcClientOptions, ILoggerFactory loggerFactory)
        {
            ServiceProviderAccessor.SetServiceProvider(serviceProvider);
            _grpcClientOptions = grpcClientOptions.Value;
            _loggerFactory     = loggerFactory;

            this.UseLoggerFactory()//使用LoggerFactory
            .UseJaeger();
        }
Beispiel #4
0
        /// <summary>
        /// 停止并反注册服务
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public static Server StopAndDeRegisterService(this Server server)
        {
            //服务反注册
            var serviceRegister = ServiceProviderAccessor.GetService <IServiceRegister>();

            serviceRegister.DeregisterService();
            server.ShutdownAsync().Wait();

            return(server);
        }
Beispiel #5
0
        /// <summary>
        /// 使用LoggerFactory
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        private static IApplicationBuilder UseLoggerFactory(this IApplicationBuilder builder)
        {
            var loggerFactory = ServiceProviderAccessor.GetService <ILoggerFactory>();
            var logger        = loggerFactory.CreateLogger <IApplicationBuilder>();
            var loggerAccess  = loggerFactory.CreateLogger("grpc.access");

            LoggerAccessor.Instance.LoggerError   += (ex, type) => logger.LogError(ex.ToString());
            LoggerAccessor.Instance.LoggerMonitor += (msg, type) => loggerAccess.LogInformation(msg);

            return(builder);
        }
Beispiel #6
0
 /// <summary>
 /// ServerBuilder
 /// </summary>
 /// <param name="serviceProvider"></param>
 /// <param name="grpcServerOptions"></param>
 /// <param name="serverInterceptors"></param>
 /// <param name="grpcServices"></param>
 /// <param name="loggerFactory"></param>
 public ServerBuilder(IServiceProvider serviceProvider,
                      IOptions <GrpcServerOptions> grpcServerOptions,
                      IEnumerable <ServerInterceptor> serverInterceptors,
                      IEnumerable <IGrpcService> grpcServices,
                      ILoggerFactory loggerFactory)
 {
     ServiceProviderAccessor.SetServiceProvider(serviceProvider);
     this._grpcServices.AddRange(grpcServices);
     this._grpcServerOptions  = grpcServerOptions.Value;
     this._serverInterceptors = serverInterceptors;
     this._loggerFactory      = loggerFactory;
 }
        /// <summary>
        /// 获取GrpcClient,用于批量调用
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetGrpcClient <T>() where T : ClientBase <T>
        {
            var channelManager  = ServiceProviderAccessor.GetService <ChannelPool>();
            var bindFlags       = BindingFlags.Static | BindingFlags.NonPublic;
            var grpcServiceName = typeof(T).DeclaringType.GetFieldValue <string>("__ServiceName", bindFlags);

            var channel     = channelManager.GetChannel(grpcServiceName);
            var callInvoker = channel.Intercept(_clientInterceptors.ToArray());
            var client      = Activator.CreateInstance(typeof(T), callInvoker);

            return(client as T);
        }
Beispiel #8
0
        /// <summary>
        /// 有Jaeger配制就使用Jaeger
        /// </summary>
        /// <returns></returns>
        private void UseJaeger()
        {
            var jaeger = _grpcServerOptions.Jaeger;

            if (jaeger?.CheckConfig() == true)
            {
                var tracer = ServiceProviderAccessor.GetService <ITracer>();
                if (tracer != null)
                {
                    GlobalTracer.Register(tracer);
                }
            }
        }
        /// <summary>
        /// 停止并反注册服务
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public static Server StopAndDeRegisterService(this Server server)
        {
            //服务反注册
            var grpcServerOptions = ServiceProviderAccessor.GetService <IOptions <GrpcServerOptions> >().Value;

            if (grpcServerOptions.EnableDiscovery)
            {
                var serviceRegister = ServiceProviderAccessor.GetService <IServiceRegister>();
                serviceRegister.DeregisterService().Wait();
            }
            //停止服务
            server.ShutdownAsync().Wait();

            return(server);
        }
        /// <summary>
        /// ServerBuilder
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="grpcServerOptions"></param>
        /// <param name="serverInterceptors"></param>
        /// <param name="grpcServices"></param>
        /// <param name="loggerFactory"></param>
        public ServerBuilder(IServiceProvider serviceProvider,
                             IOptions <GrpcServerOptions> grpcServerOptions,
                             IEnumerable <ServerInterceptor> serverInterceptors,
                             IEnumerable <IGrpcService> grpcServices,
                             ILoggerFactory loggerFactory)
        {
            ServiceProviderAccessor.SetServiceProvider(serviceProvider);
            this._grpcServices.AddRange(grpcServices);
            this._grpcServerOptions = grpcServerOptions.Value;

            this._loggerFactory = loggerFactory;

            //初始化配制,注入中间件,GrpcService
            this.InitGrpcOptions()              //初始化配制
            .UseInterceptor(serverInterceptors) //注入中间件
            .UseLoggerFactory()                 //使用LoggerFactory
            .UseJaeger();
        }
        /// <summary>
        /// 启动并注册服务
        /// </summary>
        /// <param name="server"></param>
        /// <returns></returns>
        public static Server StartAndRegisterService(this Server server)
        {
            //启动服务
            server.Start();
            var ipAndPort = server.Ports.FirstOrDefault();

            if (ipAndPort == null)
            {
                return(server);
            }
            //输出启动信息
            MetaModel.StartTime = DateTime.Now;
            MetaModel.Ip        = ipAndPort.Host;
            MetaModel.Port      = ipAndPort.BoundPort;
            Console.WriteLine($"server listening {MetaModel.Ip}:{MetaModel.Port}");

            //服务注册
            var grpcServerOptions = ServiceProviderAccessor.GetService <IOptions <GrpcServerOptions> >().Value;
            var registerIP        = NetHelper.GetIp(grpcServerOptions.ServiceAddress);

            if (grpcServerOptions.EnableDiscovery)
            {
                //检查服务注册配制
                if (string.IsNullOrWhiteSpace(grpcServerOptions.DiscoveryUrl))
                {
                    throw new ArgumentException("GrpcServer:DiscoveryUrl is null");
                }
                if (string.IsNullOrWhiteSpace(grpcServerOptions.DiscoveryServiceName))
                {
                    throw new ArgumentException("GrpcServer:DiscoveryServiceName is null");
                }

                //服务注册
                var serviceRegister = ServiceProviderAccessor.GetService <IServiceRegister>();
                Console.WriteLine($"use {serviceRegister.GetType().Name} register");
                Console.WriteLine($"    DiscoveryUrl:{grpcServerOptions.DiscoveryUrl}");
                Console.WriteLine($"    ServiceName:{grpcServerOptions.DiscoveryServiceName}");
                var registerModel = grpcServerOptions.ToJson().FromJson <ServiceRegisterModel>();
                registerModel.ServiceIp   = registerIP;
                registerModel.ServicePort = ipAndPort.BoundPort;
                serviceRegister.RegisterService(registerModel).Wait();
            }
            return(server);
        }
Beispiel #12
0
        /// <summary>
        /// 有Jaeger配制就使用Jaeger
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        private static IApplicationBuilder UseJaeger(this IApplicationBuilder builder)
        {
            var serverOptions = ServiceProviderAccessor.GetService <IOptions <GrpcServerOptions> >().Value;

            if (serverOptions.Jaeger != null && string.IsNullOrWhiteSpace(serverOptions.Jaeger.ServiceName))
            {
                serverOptions.Jaeger.ServiceName = serverOptions.DiscoveryServiceName;
            }

            if (serverOptions.Jaeger?.CheckConfig() == true)
            {
                var tracer = ServiceProviderAccessor.GetService <ITracer>();
                if (tracer != null)
                {
                    GlobalTracer.Register(tracer);
                }
            }
            return(builder);
        }
Beispiel #13
0
        /// <summary>
        /// 使用Grpc扩展
        /// </summary>
        /// <typeparam name="TStartup">实现IGrpcService的类所在程序集下的任意类</typeparam>
        /// <param name="builder"></param>
        /// <param name="configureOptions"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseGrpcExtensions <TStartup>(this IApplicationBuilder builder, Action <GrpcExtensionsOptions> configureOptions = null)
        {
            ServiceProviderAccessor.SetServiceProvider(builder.ApplicationServices);
            //注入基本配制
            configureOptions?.Invoke(GrpcExtensionsOptions.Instance);
            //使用基础服务
            builder.UseEndpoints(endpoints => {
                endpoints.MapIGrpcServices <TStartup>();
                //使用基础服务
                endpoints.MapGrpcService <CmdService>();
                endpoints.MapGrpcService <MetaServiceAspnetCore>();
            });
            //默认使用
            builder.InitGrpcOptions() //初始化配制
            .UseLoggerFactory()       //使用LoggerFactory
            .UseJaeger();             //使用Jaeger

            return(builder);
        }
Beispiel #14
0
        /// <summary>
        /// This method gets called by the runtime.
        /// Use this method to configure the HTTP request pipeline.
        /// </summary>
        /// <param name="app">Application builder.</param>
        /// <param name="env">Environment informations.</param>
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // Enable middleware to serve generated Swagger as a JSON endpoint.
            app.UseSwagger();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
            });

            ServiceProviderAccessor.SetProvider(app.ApplicationServices);
            app.UseMvc();
        }
Beispiel #15
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            var apiService = new WeGouService();

            var bs = ServiceProviderAccessor.ResolveService <Browser>();

            var rs = apiService.GetAccountInfoByIdAsync("bitsea").Result;

            var rss = apiService.GetAccountInfoByIdSerializedAsync("taosay").Result;

            Console.WriteLine(rss);
            //var ws = new WeGouService(logger,configuration,yunDaMa);

            //var rs = ws.GetOfficialAccountMessagesByName("gzhu");

            //var rs = ws.GetOfficialAccountMessagesByName("广州大学");

            Console.ReadKey();
        }
Beispiel #16
0
        /// <summary>
        /// 初始化配制
        /// </summary>
        private ServerBuilder InitGrpcOptions()
        {
            var serverOptions = _grpcServerOptions;

            //Jaeger配置
            if (serverOptions.Jaeger != null && string.IsNullOrWhiteSpace(serverOptions.Jaeger.ServiceName))
            {
                serverOptions.Jaeger.ServiceName = serverOptions.DiscoveryServiceName;
            }

            #region 默认的客户端配制

            var clientOptions = ServiceProviderAccessor.GetService <IOptions <GrpcClientOptions> >().Value;
            clientOptions.DiscoveryUrl     = serverOptions.DiscoveryUrl;
            clientOptions.DefaultErrorCode = serverOptions.DefaultErrorCode;
            clientOptions.Jaeger           = serverOptions.Jaeger;
            clientOptions.GrpcCallTimeOut  = serverOptions.GrpcCallTimeOut;

            #endregion

            return(this);
        }
Beispiel #17
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();

            ServiceProviderAccessor.SetProvider(app.ApplicationServices);
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 /// <summary>
 /// GrpcClient
 /// </summary>
 /// <param name="serviceProvider"></param>
 /// <param name="clientInterceptors"></param>
 public GrpcClientManager(IServiceProvider serviceProvider, IEnumerable <ClientInterceptor> clientInterceptors)
 {
     ServiceProviderAccessor.SetServiceProvider(serviceProvider);
     this._clientInterceptors = clientInterceptors;
 }