コード例 #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            #region 注册Grpc
            //通过反射去拿
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(ITest).Assembly },   //如果实现的服务层在另一个程序集,需添加此项
                new MagicOnionOptions(true)
            {
                MagicOnionLogger = new MagicOnionLogToGrpcLogger()
            }
                );

            var    serverAddress = this.Configuration["Service:LocalIPAddress"];
            var    serverPort    = Convert.ToInt32(this.Configuration["Service:Port"]);
            Server server        = new Server
            {
                Services = { service },
                Ports    =
                {
                    new ServerPort(serverAddress, serverPort, ServerCredentials.Insecure)//读取配置文件
                }
            };
            server.Start();
            #endregion
        }
コード例 #2
0
        public override void OnApplicationInitialization(CafApplicationContext context)
        {
            var options = new MagicOnionOptions();

            options.IsReturnExceptionStackTraceInErrorDetail = true;
            options.ServiceLocator             = new MicrosoftExtensionsServiceLocator(context.ServiceProvider, options);//new ServiceLocatorBridge(factory);
            options.MagicOnionServiceActivator = new MicrosoftExtensionsMagicOnionServiceActivator();
            MagicOnionServiceDefinition serviceDefine = null;
            var config    = context.ServiceProvider.GetRequiredService <IGrpcServerConfiguration>();
            var generator = context.ServiceProvider.GetRequiredService <IGrpcServiceGenerator>();

            generator.GeneraterProxyService();//创建MagicOnion grpc 代理程序集
            config.GrpcAssemblies = config.GrpcAssemblies.Append(generator.DynamicAssembly).ToList();
            config.GrpcAssemblies = config.GrpcAssemblies.Append(generator.DynamicInterfaceAssembly).ToList();
            if (config.GrpcAssemblies != null)
            {
                serviceDefine = MagicOnionEngine.BuildServerServiceDefinition(config.GrpcAssemblies.ToArray(), options);
            }
            var packageMagicOnionServerService = new PackageMagicOnionServerService(serviceDefine, new[]
            {
                new ServerPort(config.GrpcBindAddress, config.GrpcBindPort, ServerCredentials.Insecure)
            }, null);

            packageMagicOnionServerService.StartAsync(CancellationToken.None);
        }
コード例 #3
0
ファイル: Startup.cs プロジェクト: akinama3/yugawara
        // Inject MagicOnionServiceDefinition from DIl
        public void Configure(IApplicationBuilder app, MagicOnionServiceDefinition magicOnion)
        {
            app.UseMagicOnionSwagger(magicOnion.MethodHandlers, new SwaggerOptions("MagicOnion.Server", "Swagger Integration Test", "/")
            {
                // XmlDocumentPath = xmlPath
            });

            app.UseMagicOnionHttpGateway(magicOnion.MethodHandlers, new Channel("0.0.0.0:12345", ChannelCredentials.Insecure));
        }
コード例 #4
0
 private static MagicOnionServerService CreateMagicOnionHostedService(
     ILogger logger,
     IEnumerable <ServerPort> ports,
     MagicOnionServiceDefinition serviceDefinition,
     IEnumerable <ChannelOption> channelOptions = null
     )
 {
     logger.LogInformation("MagicOnion is listening on: {ServerPorts}", String.Join(",", ports.Select(x => $"{(x.Credentials == ServerCredentials.Insecure ? "http" : "https")}://{x.Host}:{x.Port}")));
     return(new MagicOnionServerService(serviceDefinition, ports, channelOptions));
 }
コード例 #5
0
        public MagicOnionHostedServiceDefinition(string name, MagicOnionServiceDefinition serviceDefinition)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }
            if (serviceDefinition == null)
            {
                throw new ArgumentNullException(nameof(serviceDefinition));
            }

            Name = name;
            ServiceDefinition = serviceDefinition;
        }
コード例 #6
0
        // Inject MagicOnionServiceDefinition from DIl
        public void Configure(IApplicationBuilder app, MagicOnionServiceDefinition magicOnion)
        {
            // Optional:Summary to Swagger
            var xmlName = "Sandbox.NetCoreServer.xml";
            var xmlPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), xmlName);

            // HttpGateway has two middlewares.
            // One is SwaggerView(MagicOnionSwaggerMiddleware)
            // One is Http1-JSON to gRPC-MagicOnion gateway(MagicOnionHttpGateway)
            app.UseMagicOnionSwagger(magicOnion.MethodHandlers, new SwaggerOptions("MagicOnion.Server", "Swagger Integration Test", "/")
            {
                XmlDocumentPath = xmlPath
            });
            app.UseMagicOnionHttpGateway(magicOnion.MethodHandlers, new Channel("localhost:12345", ChannelCredentials.Insecure));
        }
コード例 #7
0
ファイル: Hosting.cs プロジェクト: petervyvey/Company.Grpc
        private static void RunHost()
        {
            MagicOnionServiceDefinition service = MagicOnionEngine.BuildServerServiceDefinition(
                new[] { typeof(UserAccessGrpc) },
                new MagicOnionOptions(isReturnExceptionStackTraceInErrorDetail: true));

            // SSL gRPC
            string caCrt          = File.ReadAllText(EnvVars.CaCrtPath());
            string serverCrt      = File.ReadAllText(EnvVars.ServerCrtPath());
            string serverKey      = File.ReadAllText(EnvVars.ServerKeyPath());
            var    keyPair        = new KeyCertificatePair(serverCrt, serverKey);
            var    sslCredentials = new SslServerCredentials(new List <KeyCertificatePair>()
            {
                keyPair
            }, caCrt, false);

            int localPort = EnvVars.LocalPort(@"UserAccessPort");

            var server = new global::Grpc.Core.Server
            {
                Services = { service },
                Ports    = { new ServerPort("0.0.0.0", localPort, sslCredentials) }
            };

            // launch gRPC Server.
            server.Start();

            Log.Information($"Server listening on port {localPort}");

            var cts = new CancellationTokenSource();

            var syncTask = new TaskCompletionSource <bool>();

            System.Runtime.Loader.AssemblyLoadContext.Default.Unloading += (context) =>
            {
                Log.Information("Greeter server received kill signal...");
                cts.Cancel();
                server.ShutdownAsync().Wait();
                syncTask.SetResult(true);
            };
            syncTask.Task.Wait(-1);
            Log.Information("Greeter server stopped");
        }
コード例 #8
0
 public MagicOnionServerService(MagicOnionServerServiceOptions options)
 {
     if (options.SearchAssemblies != null)
     {
         _ServiceDefinition = MagicOnionEngine.BuildServerServiceDefinition(options.SearchAssemblies, options.MagicOnionOptions);
     }
     else if (options.Types != null)
     {
         _ServiceDefinition = MagicOnionEngine.BuildServerServiceDefinition(options.Types, options.MagicOnionOptions);
     }
     else
     {
         if (options.MagicOnionOptions != null)
         {
             _ServiceDefinition = MagicOnionEngine.BuildServerServiceDefinition(options.MagicOnionOptions);
         }
         else
         {
             _ServiceDefinition = MagicOnionEngine.BuildServerServiceDefinition();
         }
     }
     _Ports          = options.Ports;
     _ChannelOptions = options.ChannelOptions;
 }
コード例 #9
0
 public PackageMagicOnionServerService(MagicOnionServiceDefinition serviceDefinition, IEnumerable <ServerPort> ports, IEnumerable <ChannelOption> channelOptions)
 {
     this.serviceDefinition = serviceDefinition;
     this.ports             = ports;
     this.channelOptions    = channelOptions;
 }
コード例 #10
0
ファイル: Startup.cs プロジェクト: artman5545/StudyCore
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env
                              , MagicOnionServiceDefinition magicOnion
                              , IHostApplicationLifetime lifetime
                              )
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseMagicOnionSwagger(magicOnion.MethodHandlers, new SwaggerOptions("MagicOnion.Server", "Swagger Integration Test", "/")
            {
                XmlDocumentPath = Path.Combine(PlatformServices.Default.Application.ApplicationBasePath, "RpcWebApi.xml")
            });
            app.UseMagicOnionHttpGateway(magicOnion.MethodHandlers, new Channel("127.0.0.1:19021", ChannelCredentials.Insecure));


            //app.UseAbp();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "defaultWithArea",
                    template: "{area}/{controller=Home}/{action=Index}/{id?}");

                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            #region 注册到consul
            ServiceEntity serviceEntity = new ServiceEntity
            {
                IP          = "127.0.0.1",
                Port        = 19021,
                ServiceName = "RpcWebApi",
                ConsulIP    = "127.0.0.1",
                ConsulPort  = 8500
            };
            var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
            var httpCheck    = new AgentServiceCheck()
            {
                DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5), //服务启动多久后注册
                Interval = TimeSpan.FromSeconds(10),                      //健康检查时间间隔,或者称为心跳间隔
                //HTTP = $"http://{serviceEntity.IP}:5000/api/values",//健康检查地址
                HTTP    = $"http://{serviceEntity.IP}:5000/health/check",
                Timeout = TimeSpan.FromSeconds(5)
            };
            var registration = new AgentServiceRegistration()
            {
                Checks  = new[] { httpCheck },
                ID      = Guid.NewGuid().ToString(), //集群中的单个服务名称
                Name    = serviceEntity.ServiceName, //集群取名称
                Address = serviceEntity.IP,
                Port    = serviceEntity.Port,
                Tags    = new[] { $"urlprefix-/{serviceEntity.ServiceName}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
            };
            consulClient.Agent.ServiceRegister(registration);//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)

            lifetime.ApplicationStopping.Register(() =>
            {
                consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
            });
            #endregion
        }
コード例 #11
0
 public MagicOnionServiceDefinitionGlueDescriptor(Type glueServiceType, MagicOnionServiceDefinition serviceDefinition)
 {
     GlueServiceType   = glueServiceType;
     ServiceDefinition = serviceDefinition;
 }
コード例 #12
0
 public MagicOnionResponseBodyDataTransformer(MagicOnionServiceDefinition serviceDefinition, IOptionsMonitor <MagicOnionOptions> magicOnionOptions)
 {
     _serviceDefinition = serviceDefinition;
     _serializerOptions = magicOnionOptions.CurrentValue.SerializerOptions;
 }
コード例 #13
0
 public MagicOnionGlueServiceMethodProvider(MagicOnionServiceDefinition magicOnionServerServiceDefinition)
 {
     _magicOnionServiceDefinition = magicOnionServerServiceDefinition ?? throw new ArgumentNullException(nameof(magicOnionServerServiceDefinition));
 }
コード例 #14
0
 public static IReadOnlyList <MethodHandler> WebApiHandlers(this MagicOnionServiceDefinition svc) =>
 svc?.MethodHandlers.Where(x => x.MethodType == Grpc.Core.MethodType.Unary &&
                           !x.AttributeLookup.Contains(typeof(WebApiIgnoreAttributeAttribute))).ToArray()
 ?? throw new ArgumentNullException("svc");