public static IServiceHostClientBuilder UseServiceProxy(this IServiceHostClientBuilder serviceHostBuilder, string[] assemblyNames) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <ServiceProxyGenerator>().As <IServiceProxyGenerator>().SingleInstance(); containerBuilder.RegisterType <ServiceProxy>().As <IServiceProxy>().SingleInstance(); containerBuilder.RegisterType <RemoteServiceCaller>().As <IRemoteServiceCaller>().SingleInstance(); }); var assemblies = new List <Assembly>(); foreach (var assemblyName in assemblyNames) { var assembly = AssemblyLoadContext.Default.LoadFromAssemblyName(new AssemblyName(assemblyName)); assemblies.Add(assembly); } var serviceTypes = assemblies.SelectMany(x => x.ExportedTypes).Where(x => x.GetMethods().Any(y => y.GetCustomAttribute <JimuServiceAttribute>() != null)).ToList(); serviceHostBuilder.AddInitializer(componentRegister => { var serviceProxyGenerator = componentRegister.Resolve <IServiceProxyGenerator>(); var serviceProxyTypes = serviceProxyGenerator.GenerateProxy(serviceTypes); var serviceProxy = componentRegister.Resolve <IServiceProxy>(); var logger = componentRegister.Resolve <ILogger>(); logger.Info($"[config]use service proxy"); }); return(serviceHostBuilder); }
/// <summary> /// 选择负载均衡 /// </summary> /// <param name="serviceHostBuilder"></param> /// <returns></returns> public static IServiceHostClientBuilder UsePollingAddressSelector(this IServiceHostClientBuilder serviceHostBuilder, BalanceType balanceType) { serviceHostBuilder.RegisterService(containerBuilder => { switch (balanceType) { case BalanceType.RoundRobin: containerBuilder.RegisterType <RoundRobin>().As <ILoadBalanceStrategy>().SingleInstance(); break; case BalanceType.WeightRandom: containerBuilder.RegisterType <WeightRandom>().As <ILoadBalanceStrategy>().SingleInstance(); break; default: containerBuilder.RegisterType <RoundRobin>().As <ILoadBalanceStrategy>().SingleInstance(); break; } containerBuilder.RegisterType <DefaultAddressSelector>().As <IAddressSelector>().WithParameter("balanceType", balanceType).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { ILogger logger = container.Resolve <ILogger>(); logger.Info($"采用默认的地址选择器"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseConsulForDiscovery(this IServiceHostClientBuilder serviceHostBuilder, RegisterServer registerServer, params ServerAddress[] address) { serviceHostBuilder.RegisterService(cb => { cb.RegisterType <ConsulClientDiscovery>().As <IClientServiceDiscovery>().WithParameter("registerServer", registerServer).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { IClientServiceDiscovery clientDiscovery = container.Resolve <IClientServiceDiscovery>(); foreach (ServerAddress addr in address) { clientDiscovery.AddRoutesGetter(() => { ServerDesc serverDesc = new ServerDesc { ServerAddress = addr }; return(Task.FromResult(serverDesc)); }); } }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseAutofacForMvc(this IServiceHostClientBuilder serviceHostBuilder, IServiceCollection services) { serviceHostBuilder.RegisterService(cb => { cb.Populate(services); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseConsulForDiscovery(this IServiceHostClientBuilder serviceHostBuilder, string ip, int port, string serviceCategory) { serviceHostBuilder.AddInitializer(container => { var logger = container.Resolve <ILogger>(); logger.Info($"[config]use consul for services discovery, consul ip: {ip}:{port}, service cateogry: {serviceCategory}"); var clientDiscovery = container.Resolve <IClientServiceDiscovery>(); var serializer = container.Resolve <ISerializer>(); clientDiscovery.AddRoutesGetter(async() => { var consul = new ConsulClient(config => { config.Address = new Uri($"http://{ip}:{port}"); }); var queryResult = await consul.KV.Keys(serviceCategory); var keys = queryResult.Response; if (keys == null) { return(null); } var routes = new List <JimuServiceRoute>(); foreach (var key in keys) { var data = (await consul.KV.Get(key)).Response?.Value; if (data == null) { continue; } var descriptors = serializer.Deserialize <byte[], List <JimuServiceRouteDesc> >(data); if (descriptors != null && descriptors.Any()) { foreach (var descriptor in descriptors) { List <JimuAddress> addresses = new List <JimuAddress>(descriptor.AddressDescriptors.ToArray().Count()); foreach (var addDesc in descriptor.AddressDescriptors) { var addrType = Type.GetType(addDesc.Type); addresses.Add(serializer.Deserialize(addDesc.Value, addrType) as JimuAddress); } routes.Add(new JimuServiceRoute { Address = addresses, ServiceDescriptor = descriptor.ServiceDescriptor }); } } } return(routes); }); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseRemoteCache(this IServiceHostClientBuilder serviceHostBuilder, int capacity) { serviceHostBuilder.RegisterService(cb => { cb.RegisterType <LRUCache <string, List <ServerAddress> > >().As <ICache <string, List <ServerAddress> > >().WithParameter("capacity", capacity).SingleInstance(); }); return(serviceHostBuilder); }
/// <summary> /// using polling load balancing to select server /// </summary> /// <param name="serviceHostBuilder"></param> /// <returns></returns> public static IServiceHostClientBuilder UsePollingAddressSelector( this IServiceHostClientBuilder serviceHostBuilder) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <PollingAddressSelector>().As <IAddressSelector>().SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { var logger = container.Resolve <ILogger>(); logger.Info($"[config]use polling address selector"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder SetRemoteCallerRetryTimes( this IServiceHostClientBuilder serviceHostBuilder, int retryTimes) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <RemoteServiceCaller>().As <IRemoteServiceCaller>().WithParameter("retryTimes", retryTimes).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { var logger = container.Resolve <ILogger>(); logger.Info($"[config]remote service call failure retry times: {retryTimes}"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder SetDiscoveryAutoUpdateJobInterval( this IServiceHostClientBuilder serviceHostBuilder, int updateJobIntervalMinute) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <ClientServiceDiscovery>().As <IClientServiceDiscovery>().WithParameter("updateJobIntervalMinute", updateJobIntervalMinute).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { ILogger logger = container.Resolve <ILogger>(); logger.Info($"[config]services discovery auto update job interval: {updateJobIntervalMinute} min"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseServerHealthCheck(this IServiceHostClientBuilder serviceHostBuilder, int intervalMinute) { serviceHostBuilder.RegisterService(container => { container.RegisterType <QuartzHealthCheck>().As <IHealthCheck>().WithParameter("intervalMinute", intervalMinute).SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { var healthCheck = container.Resolve <IHealthCheck>(); var logger = container.Resolve <ILogger>(); logger.Info($"[config]use server health check, checked job interval: {intervalMinute} min"); healthCheck.RunAsync(); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseSwaggerAndGateWay(this IServiceHostClientBuilder serviceHostBuilder, RpcSwaggerOptions options, IServiceCollection services) { serviceHostBuilder.AddInitializer(container => { //添加swagger services.UseRpcSwagger(options, container.Resolve <IClientServiceDiscovery>()); //添加网关 services.UseGateWay(); //重新刷新容器 var bulider = new ContainerBuilder(); bulider.Populate(services); bulider.Update(container); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseDotNettyForTransfer(this IServiceHostClientBuilder serviceHostBuilder) { serviceHostBuilder.AddInitializer(container => { var factory = container.Resolve <ITransportClientFactory>(); var logger = container.Resolve <ILogger>(); var serializer = container.Resolve <ISerializer>(); var bootstrap = new Bootstrap(); logger.Info($"[config]use dotnetty for transfer"); bootstrap .Group(new MultithreadEventLoopGroup()) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <IChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new ReadClientMessageChannelHandlerAdapter(serializer, logger)); pipeline.AddLast(new ClientHandlerChannelHandlerAdapter(factory, logger)); })); AttributeKey <IClientSender> clientSenderKey = AttributeKey <IClientSender> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientSender)); AttributeKey <IClientListener> clientListenerKey = AttributeKey <IClientListener> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientListener)); //AttributeKey<EndPoint> endPointKey = AttributeKey<EndPoint>.ValueOf(typeof(DefaultTransportClientFactory), nameof(EndPoint)); AttributeKey <string> endPointKey = AttributeKey <string> .ValueOf(typeof(DefaultTransportClientFactory), "addresscode"); factory.ClientCreatorDelegate += (JimuAddress address, ref ITransportClient client) => { //if (client == null && address.GetType().IsAssignableFrom(typeof(DotNettyAddress))) if (client == null && address.ServerFlag == "DotNetty") { var ep = address.CreateEndPoint(); var channel = bootstrap.ConnectAsync(ep).Result; var listener = new DotNettyClientListener(); channel.GetAttribute(clientListenerKey).Set(listener); var sender = new DotNettyClientSender(channel, serializer); channel.GetAttribute(clientSenderKey).Set(sender); channel.GetAttribute(endPointKey).Set($"{address.ServerFlag}-{address.Code}"); client = new DefaultTransportClient(listener, sender, logger); } }; }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseRpcForTransfer(this IServiceHostClientBuilder serviceHostBuilder) { serviceHostBuilder.AddInitializer(container => { ITransportClientFactory factory = container.Resolve <ITransportClientFactory>(); ILogger logger = container.Resolve <ILogger>(); ISerializer serializer = container.Resolve <ISerializer>(); Bootstrap bootstrap = new Bootstrap(); logger.Info($"启动rpc客户端"); bootstrap .Group(new MultithreadEventLoopGroup()) .Channel <TcpSocketChannel>() .Option(ChannelOption.TcpNodelay, true) .Handler(new ActionChannelInitializer <IChannel>(channel => { IChannelPipeline pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new ReadClientMessageChannelHandler(serializer)); pipeline.AddLast(new RpcClientHandler(factory)); })); AttributeKey <IClientSender> clientSenderKey = AttributeKey <IClientSender> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientSender)); AttributeKey <IClientListener> clientListenerKey = AttributeKey <IClientListener> .ValueOf(typeof(DefaultTransportClientFactory), nameof(IClientListener)); factory.ClientCreatorDelegate += (ServerAddress address, ref ITransportClient client) => { if (client == null && address.ServerFlag == ServerFlag.Rpc) { EndPoint ep = address.CreateEndPoint(); IChannel channel = bootstrap.ConnectAsync(ep).Result; RpcClientListener listener = new RpcClientListener(); channel.GetAttribute(clientListenerKey).Set(listener); RpcClientSender sender = new RpcClientSender(channel, serializer); channel.GetAttribute(clientSenderKey).Set(sender); client = new DefaultTransportClient(listener, sender, serializer, logger); } }; }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseIdentityServer(this IServiceHostClientBuilder serviceHostBuilder, Func <string, string, IDictionary <string, object> > getIdentityServerContext) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <AuthorizationHandler>().As <IAuthorizationHandler>().SingleInstance(); }); serviceHostBuilder.AddInitializer(componentRegister => { IAuthorizationHandler context = componentRegister.Resolve <IAuthorizationHandler>(); context.GetAuthorizationContext = getIdentityServerContext; ILogger logger = componentRegister.Resolve <ILogger>(); logger.Info($"[config]identityserverExtension is set"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseToken(this IServiceHostClientBuilder serviceHostBuilder, Func <string> getToken) { serviceHostBuilder.RegisterService(containerBuilder => { containerBuilder.RegisterType <ServiceTokenGetter>().As <IServiceTokenGetter>().SingleInstance(); }); serviceHostBuilder.AddInitializer(componentRegister => { IServiceTokenGetter tokenGetter = componentRegister.Resolve <IServiceTokenGetter>(); tokenGetter.GetToken = getToken; ILogger logger = componentRegister.Resolve <ILogger>(); logger.Info($"[config]get token has been set"); }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseHttpForTransfer(this IServiceHostClientBuilder serviceHostBuilder) { serviceHostBuilder.AddInitializer(container => { var factory = container.Resolve <ITransportClientFactory>(); var logger = container.Resolve <ILogger>(); logger.Info($"[config]use http for transfer"); factory.ClientCreatorDelegate += (JimuAddress address, ref ITransportClient client) => { //if (client == null && address.GetType() == typeof(HttpAddress)) if (client == null && address.ServerFlag == "Http") { var listener = new HttpClientListener(); var sender = new HttpClientSender(address, listener); client = new DefaultTransportClient(listener, sender, logger); } }; }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseInServerForDiscovery(this IServiceHostClientBuilder serviceHostBuilder, params JimuAddress[] address) { serviceHostBuilder.AddInitializer(container => { var clientDiscovery = container.Resolve <IClientServiceDiscovery>(); var remoteCaller = container.Resolve <IRemoteServiceCaller>(); var serializer = container.Resolve <ISerializer>(); var typeConverter = container.Resolve <ITypeConvertProvider>(); var logger = container.Resolve <ILogger>(); StringBuilder sb = new StringBuilder(); foreach (var addr in address) { sb.AppendFormat(addr.Code + ","); var service = new JimuServiceRoute { Address = new List <JimuAddress> { addr }, ServiceDescriptor = new JimuServiceDesc { Id = "Jimu.ServiceDiscovery.InServer.GetRoutesDescAsync" } }; clientDiscovery.AddRoutesGetter(async() => { var result = await remoteCaller.InvokeAsync(service, null, null); if (result == null || result.HasError) { return(null); } var routesDesc = (List <JimuServiceRouteDesc>)typeConverter.Convert(result.Result, typeof(List <JimuServiceRouteDesc>)); var routes = new List <JimuServiceRoute>(); foreach (var desc in routesDesc) { List <JimuAddress> addresses = new List <JimuAddress>(desc.AddressDescriptors.ToArray().Count()); foreach (var addDesc in desc.AddressDescriptors) { var addrType = Type.GetType(addDesc.Type); addresses.Add(serializer.Deserialize(addDesc.Value, addrType) as JimuAddress); } routes.Add(new JimuServiceRoute() { ServiceDescriptor = desc.ServiceDescriptor, Address = addresses }); } return(routes); }); } if (sb.Length > 0) { logger.Info($"[config]use in server for discovery, servers is {sb.ToString()}"); } }); return(serviceHostBuilder); }
public static IServiceHostClientBuilder UseInServerForDiscovery(this IServiceHostClientBuilder serviceHostBuilder, params ServerAddress[] address) { serviceHostBuilder.RegisterService(cb => { cb.RegisterType <ClientServiceDiscovery>().As <IClientServiceDiscovery>().SingleInstance(); }); serviceHostBuilder.AddInitializer(container => { IClientServiceDiscovery clientDiscovery = container.Resolve <IClientServiceDiscovery>(); IRemoteServiceExecutor remoteExecutor = container.Resolve <IRemoteServiceExecutor>(); ISerializer serializer = container.Resolve <ISerializer>(); ITypeConvertProvider typeConverter = container.Resolve <ITypeConvertProvider>(); ILogger logger = container.Resolve <ILogger>(); StringBuilder sb = new StringBuilder(); foreach (ServerAddress addr in address) { sb.AppendFormat(addr.Code + ","); clientDiscovery.AddRoutesGetter(async() => { RemoteCallBackData result = await remoteExecutor.InvokeAsync(new List <ServerAddress>() { addr }, "Lamp.ServiceDiscovery.InServer.GetRoutesDescAsync".ToLower(), null, null); if (result == null || result.HasError) { return(null); } List <ServiceRouteDesc> routesDesc = (List <ServiceRouteDesc>)typeConverter.Convert(result.Result, typeof(List <ServiceRouteDesc>)); ServerDesc server = new ServerDesc { ServerAddress = addr, ServiceDescriptor = new List <ServiceDesc>() }; server.ServerAddress.IsHealth = true; foreach (ServiceRouteDesc desc in routesDesc) { ServiceDesc item = (ServiceDesc)desc.ServiceDescriptor.Clone(); server.ServiceDescriptor.Add(item); } return(server); }); } if (sb.Length > 0) { logger.Info($"[config]用服务端发现服务 {sb.ToString()}"); } }); serviceHostBuilder.AddRunner(container => { ClientServiceDiscovery clientServiceDiscovery = (ClientServiceDiscovery)container.Resolve <IClientServiceDiscovery>(); clientServiceDiscovery?.RunInInit().Wait(); }); return(serviceHostBuilder); }