public static IServiceHostServerBuilder UseInServerForDiscovery(this IServiceHostServerBuilder serviceHostBuilder)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterType <InServerServiceDiscovery>().As <IServiceDiscovery>().SingleInstance();
                containerBuilder.RegisterType <InServerServiceDiscovery>().SingleInstance();
            });

            serviceHostBuilder.AddInitializer(async container =>
                                              //serviceHostBuilder.AddRunner(async container =>
            {
                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use in server for discovery");
                while (!container.IsRegistered <IServer>())
                {
                    default(SpinWait).SpinOnce();
                }
                IServer server = container.Resolve <IServer>();
                IServiceEntryContainer entryContainer = container.Resolve <IServiceEntryContainer>();
                // register the method of GetRoutesAsync as microservice so that the client can call it from remote
                entryContainer.AddServices(new[] { typeof(InServerServiceDiscovery) });

                var routes    = server.GetServiceRoutes();
                var discovery = container.Resolve <IServiceDiscovery>();
                await discovery.ClearAsync();
                await discovery.SetRoutesAsync(routes);
            });
            return(serviceHostBuilder);
        }
Beispiel #2
0
        public static IServiceHostServerBuilder UseInServerForDiscovery(this IServiceHostServerBuilder serviceHostBuilder)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterType <InServerServiceDiscovery>().As <IServiceDiscovery>().SingleInstance();
                containerBuilder.RegisterType <InServerServiceDiscovery>().AsSelf().AsImplementedInterfaces().InstancePerDependency();
            });

            serviceHostBuilder.AddInitializer(async container =>
            {
                ILogger logger = container.Resolve <ILogger>();
                logger.Info($"本地服务器为注册服务器");
                while (!container.IsRegistered <IServer>())
                {
                    default(SpinWait).SpinOnce();
                }
                IServer server = container.Resolve <IServer>();
                IServiceEntryContainer entryContainer = container.Resolve <IServiceEntryContainer>();
                // 添加一个获取所有服务路径的服务
                entryContainer.AddServices(new[] { typeof(InServerServiceDiscovery) });

                List <ServiceRoute> routes  = server.GetServiceRoutes();
                IServiceDiscovery discovery = container.Resolve <IServiceDiscovery>();
                await discovery.ClearAsync();
                await discovery.SetRoutesAsync(routes);
            });
            return(serviceHostBuilder);
        }
        public static IServiceHostServerBuilder UseConsulCheckHealth(this IServiceHostServerBuilder serviceHostBuilder, RegisterServer registerServer)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                List <NamedParameter> ListNamedParameter = new List <NamedParameter>()
                {
                    new NamedParameter("registerServer", registerServer),
                    new NamedParameter("address", serviceHostBuilder.Address),
                };
                containerBuilder.RegisterType <ConsulDiscovery>().As <IServiceDiscovery>().As <IHealthCheck>().WithParameters(ListNamedParameter).SingleInstance();
            });

            serviceHostBuilder.AddInitializer(container =>
            {
                while (!container.IsRegistered <IServer>())
                {
                    //default(SpinWait).SpinOnce();
                    Thread.Sleep(200);
                }


                ILogger logger = container.Resolve <ILogger>();
                logger.Info($"[config]use consul for services discovery, consul ip: {registerServer.Ip}:{registerServer.Port}");

                IServer server             = container.Resolve <IServer>();
                List <ServiceRoute> routes = server.GetServiceRoutes();
                logger.Debug("running consul found routes count: " + routes.Count);

                try
                {
                    IServiceDiscovery discovery = container.Resolve <IServiceDiscovery>();
                    discovery.ClearAsync().Wait();
                    discovery.SetRoutesAsync(routes).Wait();
                }
                catch (Exception ex)
                {
                    logger.Error($"error occurred while connecting with consul, ensure consul is running.\r\n", ex);
                }
            });
            serviceHostBuilder.AddRunner(container =>
            {
                IServer server     = container.Resolve <IServer>();
                IHealthCheck check = container.Resolve <IHealthCheck>();
                check.RunAsync();
            });
            return(serviceHostBuilder);
        }
Beispiel #4
0
        /// <summary>
        /// use consul for discovery server
        /// </summary>
        /// <param name="serviceHostBuilder"></param>
        /// <param name="consulIp">server ip</param>
        /// <param name="consulPort">server port</param>
        /// <param name="serviceCategory">server category name</param>
        /// <param name="serverAddress">server address</param>
        /// <returns></returns>
        public static IServiceHostServerBuilder UseConsulForDiscovery(this IServiceHostServerBuilder serviceHostBuilder, string consulIp, int consulPort, string serviceCategory, string serverAddress)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterType <ConsulServiceDiscovery>().As <IServiceDiscovery>()
                .WithParameter("ip", consulIp)
                .WithParameter("port", consulPort)
                .WithParameter("serviceCategory", serviceCategory)
                .WithParameter("serverAddress", serverAddress)
                .SingleInstance();
            });

            //serviceHostBuilder.AddRunner(async container =>
            serviceHostBuilder.AddInitializer(async container =>
            {
                while (!container.IsRegistered <IServer>())
                {
                    //default(SpinWait).SpinOnce();
                    Thread.Sleep(200);
                }

                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use consul for services discovery, consul ip: {consulIp}:{consulPort}, service cateogry: {serviceCategory}, server address: {serverAddress} ");

                IServer server = container.Resolve <IServer>();
                var routes     = server.GetServiceRoutes();
                logger.Debug("running consul found routes count: " + routes.Count);

                try
                {
                    var discovery = container.Resolve <IServiceDiscovery>();
                    //if (!string.IsNullOrEmpty(serverAddress))
                    //{
                    //    await discovery.ClearAsync(serverAddress);
                    //}

                    await discovery.ClearAsync();
                    await discovery.SetRoutesAsync(routes);
                }
                catch (Exception ex)
                {
                    logger.Error($"error occurred while connecting with consul, ensure consul is running.\r\n", ex);
                }
            });
            return(serviceHostBuilder);
        }
Beispiel #5
0
        public static IServiceHostServerBuilder UseDotNettyForTransfer(this IServiceHostServerBuilder serviceHostBuilder, string ip, int port, Action <IServer> action = null)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterType <DotNettyServer>().As <IServer>().WithParameter("address", new DotNettyAddress(ip, port)).SingleInstance();
            });

            serviceHostBuilder.AddInitializer(container =>
            {
                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use dotnetty for transfer");
                var server = container.Resolve <IServer>();
                server.StartAsync();
                action?.Invoke(server);
            });

            return(serviceHostBuilder);
        }
        public static IServiceHostServerBuilder UseJoseJwtForOAuth <T>(this IServiceHostServerBuilder serviceHostBuilder, JwtAuthorizationOptions options) where T : JimuAddress, new()
        {
            serviceHostBuilder.AddInitializer(container =>
            {
                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use jose.jwt for OAuth");

                while (!container.IsRegistered <IServer>() || !container.IsRegistered <IServiceDiscovery>())
                {
                    Thread.Sleep(200);
                }
                var server     = container.Resolve <IServer>();
                var serializer = container.Resolve <ISerializer>();
                server.UseMiddleware <JwtAuthorizationMiddleware>(options, serializer);

                if (string.IsNullOrEmpty(options.TokenEndpointPath))
                {
                    return;
                }
                var discovery = container.Resolve <IServiceDiscovery>();
                var addr      = new T
                {
                    Ip   = options.ServerIp,
                    Port = options.ServerPort
                };
                var tokenRoute = new List <JimuServiceRoute> {
                    new JimuServiceRoute
                    {
                        Address = new List <JimuAddress> {
                            addr
                        },
                        ServiceDescriptor = new JimuServiceDesc
                        {
                            Id        = options.GetServiceId(),
                            RoutePath = options.TokenEndpointPath
                        }
                    }
                };
                discovery.ClearServiceAsync(tokenRoute.First().ServiceDescriptor.Id).Wait();
                //discovery.SetRoutesAsync(tokenRoute);
                discovery.AddRouteAsync(tokenRoute).Wait();
            });
            return(serviceHostBuilder);
        }
        /// <summary>
        ///     load service(which must inherit from IServiceKey, and load Module of autofac
        /// </summary>
        /// <param name="serviceHostBuilder"></param>
        /// <param name="assemblyNames">the dll to load (trim the ".dll"), like: "IServices,Services"</param>
        /// <returns></returns>
        public static IServiceHostServerBuilder LoadServices(this IServiceHostServerBuilder serviceHostBuilder,
                                                             params string[] assemblyNames)
        {
            var assemblies = new List <Assembly>();

            foreach (var assemblyName in assemblyNames)
            {
                var name = assemblyName;
                if (name.EndsWith(".dll"))
                {
                    name = name.Substring(0, name.Length - 4);
                }
                var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name));
                assemblies.Add(assembly);
            }

            var serviceTypes = assemblies.SelectMany(x => x.ExportedTypes)
                               .Where(x => typeof(IJimuService).GetTypeInfo().IsAssignableFrom(x)).ToList();

            //var serviceTypes = assemblies.SelectMany(x => x.ExportedTypes)
            //    .Where(x => x.GetMethods().Any(y => y.GetCustomAttribute<JimuServiceAttribute>() != null)).ToList();


            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterTypes(serviceTypes.ToArray()).AsSelf().AsImplementedInterfaces()
                .InstancePerDependency();
                containerBuilder.RegisterType <ServiceEntryContainer>().As <IServiceEntryContainer>().SingleInstance();
                containerBuilder.RegisterType <ServiceIdGenerator>().As <IServiceIdGenerator>().SingleInstance();
                // register module
                assemblies.ForEach(x => { containerBuilder.RegisterAssemblyModules(x); });
            });
            serviceHostBuilder.AddInitializer(container =>
            {
                var serviceEntryContainer = container.Resolve <IServiceEntryContainer>();
                serviceEntryContainer.AddServices(serviceTypes.ToArray());

                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]loaded services: {string.Join(",", assemblies)}");
            });
            return(serviceHostBuilder);
        }
        public static IServiceHostServerBuilder UseRpcForTransfer(this IServiceHostServerBuilder serviceHostBuilder, int port, bool isDebug = true)
        {
            string ip = string.Empty;

            if (isDebug)
            {
                ip = "127.0.0.1";
            }
            else
            {
                string      hostName = Dns.GetHostName();
                IPHostEntry IpEntry  = Dns.GetHostEntry(hostName);

                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        ip = IpEntry.AddressList[i].ToString();
                    }
                }
            }

            serviceHostBuilder.Address = new ServerAddress(ip, port);

            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterType <RpcServer>().As <IServer>().WithParameter("address", serviceHostBuilder.Address).SingleInstance();
            });

            serviceHostBuilder.AddInitializer(container =>
            {
                ILogger logger = container.Resolve <ILogger>();
                logger.Info($"Rpc服务器开始启动");
                IServer server = container.Resolve <IServer>();
                server.StartAsync();
                //action?.Invoke(server);
            });

            return(serviceHostBuilder);
        }
        public static IServiceHostServerBuilder UseMasstransit(this IServiceHostServerBuilder serviceHostBuilder, MassTransitOptions options, Action <IRabbitMqBusFactoryConfigurator> action = null)
        {
            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.Register(x => options).SingleInstance();
                containerBuilder.Register(context =>
                {
                    var bc = Bus.Factory.CreateUsingRabbitMq(cfg =>
                    {
                        var host = cfg.Host(options.HostAddress, h =>
                        {
                            h.Username(options.Username);
                            h.Password(options.Password);
                        });

                        cfg.ReceiveEndpoint(options.QueueName, ec =>
                        {
                            ec.LoadFrom(context);
                        });

                        action?.Invoke(cfg);
                    });
                    return(bc);
                }).SingleInstance().As <IBusControl>().As <IBus>();
            });

            serviceHostBuilder.AddInitializer(container =>
            {
                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use Masstransit for EventBus, options.HostAddress {options.HostAddress.ToString()}, options.SendEndPointUrl {options.SendEndPointUri.ToString()}");
                var bus = container.Resolve <IBusControl>();
                bus.StartAsync();
                IServiceHost host = container.Resolve <IServiceHost>();
                host.DisposeAction(c =>
                {
                    bus.Stop();
                });
            });
            return(serviceHostBuilder);
        }
Beispiel #10
0
        public static IServiceHostServerBuilder LoadServices(this IServiceHostServerBuilder serviceHostBuilder,
                                                             params string[] assemblyNames)
        {
            List <Assembly> assemblies = new List <Assembly>();

            foreach (string assemblyName in assemblyNames)
            {
                string name = assemblyName;
                if (name.EndsWith(".dll"))
                {
                    name = name.Substring(0, name.Length - 4);
                }

                Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(name));
                assemblies.Add(assembly);
            }

            List <Type> serviceTypes = assemblies.SelectMany(x => x.ExportedTypes)
                                       .Where(x => x.GetMethods().Any(y => y.GetCustomAttribute <ServiceAttribute>() != null)).ToList();

            serviceHostBuilder.RegisterService(containerBuilder =>
            {
                containerBuilder.RegisterTypes(serviceTypes.ToArray()).AsSelf().AsImplementedInterfaces()
                .InstancePerDependency();

                // 注册模块
                assemblies.ForEach(x => { containerBuilder.RegisterAssemblyModules(x); });
            });
            serviceHostBuilder.AddInitializer(container =>
            {
                IServiceEntryContainer serviceEntryContainer = container.Resolve <IServiceEntryContainer>();
                serviceEntryContainer.AddServices(serviceTypes.ToArray());

                ILogger logger = container.Resolve <ILogger>();
                logger.Info($"已经注册的服务: {string.Join(",", assemblies)}");
            });
            return(serviceHostBuilder);
        }
Beispiel #11
0
        public static IServiceHostServerBuilder UseJoseJwtForOAuth <T>(this IServiceHostServerBuilder serviceHostBuilder, JwtAuthorizationOptions options) where T : JimuAddress, new()
        {
            serviceHostBuilder.AddInitializer(container =>
            {
                var logger = container.Resolve <ILogger>();
                logger.Info($"[config]use jose.jwt for OAuth");

                while (!container.IsRegistered <IServer>() || !container.IsRegistered <IServiceDiscovery>())
                {
                    Thread.Sleep(200);
                }
                var server     = container.Resolve <IServer>();
                var serializer = container.Resolve <ISerializer>();
                server.UseMiddleware <JwtAuthorizationMiddleware>(options, serializer);

                if (string.IsNullOrEmpty(options.TokenEndpointPath))
                {
                    return;
                }
                var discovery = container.Resolve <IServiceDiscovery>();
                var addr      = new T
                {
                    Ip   = options.ServerIp,
                    Port = options.ServerPort
                };
                var tokenRoute = new List <JimuServiceRoute> {
                    new JimuServiceRoute
                    {
                        Address = new List <JimuAddress> {
                            addr
                        },
                        ServiceDescriptor = new JimuServiceDesc
                        {
                            Id         = options.GetServiceId(),
                            RoutePath  = options.TokenEndpointPath,
                            Parameters = serializer.Serialize <string>(new List <JimuServiceParameterDesc> {
                                new JimuServiceParameterDesc
                                {
                                    Comment = "username",
                                    Format  = "System.String",
                                    Name    = "username",
                                    Type    = "object"
                                },
                                new JimuServiceParameterDesc
                                {
                                    Comment = "password",
                                    Format  = "System.String",
                                    Name    = "password",
                                    Type    = "object"
                                },
                            }),
                            ReturnDesc = serializer.Serialize <string>(new JimuServiceReturnDesc {
                                Comment      = "Token",
                                ReturnType   = "object",
                                ReturnFormat = "{\"access_token\":\"System.String | token\", \"expired_in\":\"System.Int32 | expired timestamp which is the number of seconds between 1970-01-01 and expired datetime\"}"
                            })
                        }
                    }
                };
                discovery.ClearServiceAsync(tokenRoute.First().ServiceDescriptor.Id).Wait();
                //discovery.SetRoutesAsync(tokenRoute);
                discovery.AddRouteAsync(tokenRoute).Wait();
            });
            return(serviceHostBuilder);
        }