/// <inheritdoc /> /// <summary> 创建客户端 </summary> /// <param name="serviceAddress">终结点。</param> /// <returns>传输客户端实例。</returns> public IMicroClient CreateClient(ServiceAddress serviceAddress) { //_logger.Debug($"准备为服务端地址:{endPoint}创建客户端。"); try { var lazyClient = _clients.GetOrAdd(serviceAddress.ToString(), k => new Lazy <IMicroClient>(() => { _logger.LogDebug($"创建客户端:{serviceAddress}创建客户端。"); var bootstrap = _bootstrap; var channel = bootstrap.ConnectAsync(serviceAddress.ToEndPoint(false)).Result; var listener = new MessageListener(); var sender = new DotNettyClientSender(_codecFactory.GetEncoder(), channel); channel.GetAttribute(ListenerKey).Set(listener); channel.GetAttribute(SenderKey).Set(sender); channel.GetAttribute(ServiceAddressKey).Set(serviceAddress); return(new MicroClient(_logger, sender, listener, _microExecutor)); } )); return(lazyClient.Value); } catch (Exception ex) { _logger.LogError(ex, "创建客户端失败"); _clients.TryRemove(serviceAddress.ToString(), out _); throw; } }
private async Task <ResultMessage> BaseInvoke(MethodInfo targetMethod, object[] args) { var services = (await _serviceFinder.Find(targetMethod.DeclaringType) ?? new List <ServiceAddress>()).ToList(); var invokeMessage = Create(targetMethod, args); ServiceAddress service = null; var builder = Policy .Handle <Exception>(ex => ex.GetBaseException() is SocketException) //服务器异常 .OrResult <ResultMessage>(r => r.Code != 200); //服务未找到 //熔断,3次异常,熔断5分钟 var breaker = builder.CircuitBreakerAsync(3, TimeSpan.FromMinutes(5)); //重试3次 var retry = builder.RetryAsync(3, (result, count) => { _logger.Warn(result.Exception != null ? $"{service}{targetMethod.Name}:retry,{count},{result.Exception.Format()}" : $"{service}{targetMethod.Name}:retry,{count},{result.Result.Code}"); services.Remove(service); }); var policy = Policy.WrapAsync(retry, breaker); return(await policy.ExecuteAsync(async() => { if (!services.Any()) { throw ErrorCodes.NoService.CodeException(); } service = services.RandomSort().First(); return await InvokeAsync(service.ToEndPoint(), invokeMessage); })); }
public override async Task Start(ServiceAddress serviceAddress) { _logger.Debug($"准备启动服务主机,监听地址:{serviceAddress}。"); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup();//Default eventLoopCount is Environment.ProcessorCount * 2 var bootstrap = new ServerBootstrap(); bootstrap .Group(bossGroup, workerGroup) .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 100) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new MicroMessageHandler(_coderFactory.GetDecoder())); pipeline.AddLast(new ServerHandler(async(contenxt, message) => { var sender = new DotNettyServerSender(_coderFactory.GetEncoder(), contenxt); await OnReceived(sender, message); })); })); var endPoint = serviceAddress.ToEndPoint(); _channel = await bootstrap.BindAsync(endPoint); _logger.Info($"服务主机启动成功,监听地址:{serviceAddress}。"); }
/// <inheritdoc /> /// <summary> 创建客户端 </summary> /// <param name="serviceAddress">终结点。</param> /// <returns>传输客户端实例。</returns> protected override async Task <IMicroClient> Create(ServiceAddress serviceAddress) { var bootstrap = CreateBootstrap(serviceAddress); var channel = await bootstrap.ConnectAsync(serviceAddress.ToEndPoint(false)); var listener = new MessageListener(); var codec = Provider.GetClientCodec(serviceAddress.Codec); var sender = new DotNettyClientSender(codec, channel, serviceAddress); channel.GetAttribute(ListenerKey).Set(listener); channel.GetAttribute(SenderKey).Set(sender); channel.GetAttribute(ServiceAddressKey).Set(serviceAddress); return(new MicroClient(sender, listener, MicroExecutor, LoggerFactory)); }
public override async Task Start(ServiceAddress serviceAddress) { var endpoint = serviceAddress.ToEndPoint() as IPEndPoint; _host = new WebHostBuilder() .UseContentRoot(Directory.GetCurrentDirectory()) .UseKestrel(options => { options.Listen(endpoint); }) .ConfigureServices(ConfigureServices) .Configure(AppResolve) .Build(); await _host.RunAsync(); }
public override async Task Start(ServiceAddress serviceAddress) { _logger.LogDebug($"准备启动服务主机,监听地址:{serviceAddress}。"); var bossGroup = new MultithreadEventLoopGroup(1); var workerGroup = new MultithreadEventLoopGroup(); var bootstrap = new ServerBootstrap(); bootstrap .Channel <TcpServerSocketChannel>() .Option(ChannelOption.SoBacklog, 8192) .ChildOption(ChannelOption.Allocator, PooledByteBufferAllocator.Default) .Group(bossGroup, workerGroup) .ChildHandler(new ActionChannelInitializer <ISocketChannel>(channel => { var pipeline = channel.Pipeline; pipeline.AddLast(new LengthFieldPrepender(4)); pipeline.AddLast(new LengthFieldBasedFrameDecoder(int.MaxValue, 0, 4, 0, 4)); pipeline.AddLast(new MicroMessageHandler <InvokeMessage>(_messageCodec, serviceAddress.Gzip)); pipeline.AddLast(new ServerHandler(async(contenxt, message) => { var sender = new DotNettyServerSender(_messageCodec, contenxt, serviceAddress); await OnReceived(sender, message); }, _loggerFactory)); })); try { var endPoint = serviceAddress.ToEndPoint(); _channel = await bootstrap.BindAsync(endPoint); _logger.LogInformation($"服务主机启动成功,监听地址:{serviceAddress}。"); } catch (Exception ex) { _logger.LogError(ex, $"服务主机启动失败,监听地址:{serviceAddress}。 "); } }