public async Task SimpleFilter() { for (int i = 1; i <= 20; i++) { var filters = Enumerable.Range(0, i).Select(_ => new CountFilter(i)).ToArray(); var client = MagicOnionClient.Create <IClientFilterTestService>(channel, filters); var r0 = await client.Unary1(1000, 2000); r0.Should().Be(3000 + 10 * i); foreach (var item in filters) { item.CalledCount.Should().Be(1); } } }
public async Task <TService> GetGRPCService <TService>(string serviceName) where TService : IService <TService> { if (serviceName.IsNullOrEmpty()) { return(default(TService)); } var services = await _serviceFinder.GetServicesAsync(serviceName); var service = _balancer.Balance(services); var channel = new Channel(service.Host, service.Port, ChannelCredentials.Insecure); var result = MagicOnionClient.Create <TService>(channel); return(result); }
public async Task <AuthRes> LoginCheck(string email, string password) { if (userService == null) { userService = MagicOnionClient.Create <IUserService>(baseNetworkManager.ConnectChannel()); } accessToken = await userService.LoginCheck(sendAES.Encrypt(email) , sendAES.Encrypt(password), (int)CheckMode.Email); if (accessToken == "") { return(AuthRes.Failed); } return(AuthRes.Success); }
/// <summary> /// 使用缓存的指定服务 Channel 访问 Grpc 接口,出现异常时会抛出错误信息 /// </summary> /// <typeparam name="TService">远程接口服务类型</typeparam> /// <param name="serviceName">远程服务名称</param> public TService GetRemoteServiceForDirectConnection <TService>(string serviceName) where TService : IService <TService> { var nodeInfo = GrpcClientConfiguration.GrpcDirectConnectionConfiguration[serviceName]; if (nodeInfo == null) { throw new AbpException("Grpc 服务没有在启动时定义,或者初始化内部 Channel 失败."); } if (nodeInfo.InternalChannel != null) { return(MagicOnionClient.Create <TService>(nodeInfo.InternalChannel)); } throw new AbpException("无法创建 Grpc 服务."); }
public async Task HeaderEcho() { var res = MagicOnionClient.Create <IClientFilterTestService>(channel, new IClientFilter[] { new AppendHeaderFilter(), new RetryFilter() }).HeaderEcho(); await res; var meta1 = res.GetTrailers()[0]; meta1.Key.Should().Be("x-foo"); meta1.Value.Should().Be("abcdefg"); var meta2 = res.GetTrailers()[1]; meta2.Key.Should().Be("x-bar"); meta2.Value.Should().Be("hijklmn"); }
/// <inheritdoc /> public TService GetRemoteService <TService>(string serviceName) where TService : IService <TService> { if (!_clientConfiguration.GrpcServers.ContainsKey(serviceName)) { throw new UserFriendlyException("你所选择的服务不存在,无法获取服务."); } // TODO: 此处的节点应该做负载均衡和可用检测 var serviceChannel = _clientConfiguration.GrpcServers[serviceName].FirstOrDefault(); if (serviceChannel == null) { throw new UserFriendlyException("对应的服务下面没有可用的服务节点。"); } return(MagicOnionClient.Create <TService>(serviceChannel)); }
static void Main(string[] args) { try { Console.WriteLine("Client:::"); //UnaryCSharpSevenTest().GetAwaiter().GetResult(); //return; //GrpcEnvironment.SetThreadPoolSize(1000); //GrpcEnvironment.SetCompletionQueueCount(1000); //Environment.SetEnvironmentVariable("GRPC_TRACE", "all"); GrpcEnvironment.SetLogger(new ConsoleLogger()); var channel = new Channel("localhost", 12345, ChannelCredentials.Insecure); //channel.ConnectAsync().Wait(); var c = MagicOnionClient.Create <IMyFirstService>(channel); var c2 = MagicOnionClient.Create <IArgumentPattern>(channel); var c3 = MagicOnionClient.Create <Sandbox.ConsoleServer.IChatRoomService>(channel); var c4 = MagicOnionClient.Create <Sandbox.ConsoleServer.IStandard>(channel); // TestHeartbeat(channel).GetAwaiter().GetResult(); UnaryRun(c).GetAwaiter().GetResult(); ClientStreamRun(c).GetAwaiter().GetResult(); DuplexStreamRun(c).GetAwaiter().GetResult(); ServerStreamRun(c).GetAwaiter().GetResult(); // many run //UnaryLoadTest(c).GetAwaiter().GetResult(); // HearbeatClient.Test(channel).GetAwaiter().GetResult(); Console.ReadLine(); // ChatClient.Run(channel).GetAwaiter().GetResult(); //TestHeartbeat(channel).GetAwaiter().GetResult(); } finally { var asm = AssemblyHolder.Save(); Verify(asm); Console.WriteLine("end"); } }
/// <summary> /// Main /// </summary> /// <param name="args">参数</param> static void Main(string[] args) { GrpcEnvironment.SetLogger(new ConsoleLogger()); var channel = new Channel("192.168.1.106", 5001, ChannelCredentials.Insecure); var service = MagicOnionClient.Create <ICalculateService>(channel); var result = service.SumAsync(100, 200).GetAwaiter().GetResult(); Console.WriteLine($"100+200={result.GetAwaiter().GetResult()}"); var result1 = service.SumAsync2(200, 500); Console.WriteLine($"200+500={result1.GetAwaiter().GetResult()}"); Console.ReadKey(); }
public ITestService GetClient <T>() { if (Client == null) { string ipStr = Appsettings.GetSettingNode(new string[] { "Grpc", "Ip" }); int port = Appsettings.GetSettingNodeValue <int>(Convert.ToInt32, 0, new string[] { "Grpc", "Port" }); if (string.IsNullOrEmpty(ipStr) || port == 0) { throw new Exception("appsettings 中没有对 grpc的ip或端口没有进行相关的配置!"); } var channel = new Channel("localhost", port, ChannelCredentials.Insecure); Client = MagicOnionClient.Create <ITestService>(channel); } return(Client); }
static async Task RunAsync(string endpoint, string prefix) { var channel = GrpcChannel.ForAddress(endpoint, new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan, // grpc.keepalive_time_ms KeepAlivePingDelay = TimeSpan.FromSeconds(10), // grpc.keepalive_timeout_ms KeepAlivePingTimeout = TimeSpan.FromSeconds(10), // grpc.keepalive_permit_without_calls: 1 = Always KeepAlivePingPolicy = HttpKeepAlivePingPolicy.Always, EnableMultipleHttp2Connections = true }, }); var client = MagicOnionClient.Create <IEchoService>(channel); var reply = await client.EchoAsync("hogemoge"); Console.WriteLine("Echo: " + reply); // duplex var receiver = new MyHubReceiver(); var hubClient = await StreamingHubClient.ConnectAsync <IMyHub, IMyHubReceiver>(channel, receiver); var roomPlayers = await hubClient.JoinAsync($"room {prefix}", "hoge"); foreach (var player in roomPlayers) { receiver.OnJoin(player); } var i = 0; while (i++ < 100) { await hubClient.SendAsync($"{prefix} {i}"); await Task.Delay(TimeSpan.FromSeconds(60)); } await hubClient.LeaveAsync(); await hubClient.DisposeAsync(); await channel.ShutdownAsync(); }
public static async Task Client1() { //var channelCredentials = new SslCredentials(File.ReadAllText("roots.pem")); //var channelCredentials = await GoogleGrpcCredentials.GetApplicationDefaultAsync(); //标准gRPC通道 Channel channel = new Channel("192.168.126.1", 5031, ChannelCredentials.Insecure); var service1 = MagicOnionClient.Create <IUserService>(channel); UserDto user = new UserDto(); user.Id = 1; user.Account = "bacon"; user.RealName = "高培根"; user.NickName = "培根"; user.Gender = true; user.MobilePhone = "123456789"; await service1.AddUser(user); }
public async Task ScopedCreateInstancePerUnaryCall() { var client = MagicOnionClient.Create <IServiceLocatorTestScopedService>(channel); await client.HelloAsync(); await client.HelloAsync(); await client.HelloAsync(); await client.HelloAsync(); await client.HelloAsync(); var serviceLocator = ((ServiceLocatorTestServerFixture.DummyServiceLocator)options.ServiceLocator); Assert.Empty(serviceLocator.StackedScopes); Assert.Equal(5, serviceLocator.PoppedScopes.Count); }
public async Task <TService> GetRemoteService <TService>(string serviceName) where TService : IService <TService> { var serviceSubscriber = _subscriberFactory.CreateSubscriber(serviceName); await serviceSubscriber.StartSubscription(); serviceSubscriber.EndpointsChanged += async(sender, eventArgs) => { var endpoints = await serviceSubscriber.Endpoints(); var servicesInfo = string.Join(",", endpoints); }; ILoadBalancer balancer = new RoundRobinLoadBalancer(serviceSubscriber); var endPoint = await balancer.Endpoint(); var channel = _rpcChannelFactory.Get(endPoint.Address, endPoint.Port); return(MagicOnionClient.Create <TService>(channel)); }
public async void Connect(string url, ChannelCredentials channelCredentials) { try { Channel = new Channel(url, channelCredentials); RoomService = MagicOnionClient.Create <IGetRoomService>(Channel); IsConnect = true; ConnectServerUI.alpha = 0; Others.ForEach(x => x.alpha = 1); } catch (Exception e) { } RefreshRoomList(); }
public async void Open() { if (IsConnected) { return; } try { this.channel = new Channel(_target, ChannelCredentials.Insecure); this.multiplayService = MagicOnionClient.Create <IMultiplayService>(channel); this.multiplayHub = StreamingHubClient.Connect <IMultiplayHub, IMultiplayHubReceiver>(this.channel, this); IsConnected = true; } catch (Exception ex) { Debug.LogError(ex.Message); IsConnected = false; } }
static async Task Main(string[] args) { //GrpcEnvironment.SetLogger(new ConsoleLogger()); var hostTask = MagicOnionHost.CreateDefaultBuilder() //.UseMagicOnion() .UseMagicOnion(types: new[] { typeof(MyService) }) .UseMagicOnion(configurationName: "MagicOnion-Management", types: new[] { typeof(ManagementService) }) .ConfigureServices((hostContext, services) => { services.Configure <MagicOnionHostingOptions>(options => { if (hostContext.HostingEnvironment.IsDevelopment()) { options.Service.GlobalStreamingHubFilters.Add <MyStreamingHubFilterAttribute>(); // options.Service.GlobalStreamingHubFilters.Add(new MyStreamingHubFilterAttribute(logger)); options.Service.GlobalFilters.Add <MyFilterAttribute>(); // options.Service.GlobalFilters.Add(new MyFilterAttribute(logger)); // options.ServerPorts = new[]{ new MagicOnionHostingServerPortOptions(){ Port = opti } options.ChannelOptions.MaxReceiveMessageLength = 1024 * 1024 * 10; options.ChannelOptions.Add(new ChannelOption("grpc.keepalive_time_ms", 10000)); }); services.Configure <MagicOnionHostingOptions>("MagicOnion-Management", options => { }); }) .RunConsoleAsync(); var isDevelopment = Environment.GetEnvironmentVariable("NETCORE_ENVIRONMENT") == "Development"; var creds = isDevelopment ? ChannelCredentials.Insecure : new SslCredentials(File.ReadAllText("./server.crt")); var clientMyService = MagicOnionClient.Create <IMyService>(new Channel("localhost", 12345, creds)); var clientManagementService = MagicOnionClient.Create <IManagementService>(new Channel("localhost", 23456, creds)); var result = await clientMyService.HelloAsync(); var result2 = await clientManagementService.FooBarAsync(); await hostTask; }
/// <summary> /// <see cref="AsyncDispatcherRemoteNode{TInput,TOutput}"/> /// </summary> /// <param name="host"><see cref="Host"/></param> /// <param name="cts"><see cref="CancellationTokenSource"/></param> /// <param name="circuitBreakerOptions"><see cref="CircuitBreakerOptions"/></param> /// <param name="clusterOptions"><see cref="ClusterOptions"/></param> /// <param name="logger"><see cref="ILogger"/></param> public AsyncDispatcherRemoteNode( Host host, CancellationTokenSource cts, CircuitBreakerOptions circuitBreakerOptions, ClusterOptions clusterOptions, ILogger logger) : base( Policy.Handle <Exception>() .AdvancedCircuitBreakerAsync(circuitBreakerOptions.CircuitBreakerFailureThreshold, circuitBreakerOptions.CircuitBreakerSamplingDuration, circuitBreakerOptions.CircuitBreakerMinimumThroughput, circuitBreakerOptions.CircuitBreakerDurationOfBreak, onBreak: (ex, timespan, context) => { logger.LogError( $"Batch processor breaker: Breaking the circuit for {timespan.TotalMilliseconds}ms due to {ex.Message}."); }, onReset: context => { logger.LogInformation( "Batch processor breaker: Succeeded, closed the circuit."); }, onHalfOpen: () => { logger.LogWarning( "Batch processor breaker: Half-open, next call is a trial."); }), clusterOptions, cts, logger) { _logger = logger; _clusterOptions = clusterOptions; _channel = new Channel(host.MachineName, host.Port, ChannelCredentials.Insecure); _remoteContract = MagicOnionClient.Create <IOutputRemoteContract <TInput, TOutput> >(_channel); IRemoteNodeSubject nodeReceiver = new NodeReceiver(_logger); _remoteNodeHealthSubscription = nodeReceiver.RemoteNodeHealthSubject.Subscribe(remoteNodeHealth => { NodeMetrics.RemoteNodeHealth = remoteNodeHealth; }); _nodeHub = StreamingHubClient.Connect <INodeHub, INodeReceiver>(_channel, (INodeReceiver)nodeReceiver); NodeMetrics = new NodeMetrics(Guid.NewGuid()); }
public async Task Unary1() { { var client = MagicOnionClient.Create <IArgumentPattern>(channel); var result = await client.Unary1(10, 20, "hogehoge"); result.Id.Should().Be(30); result.Data.Should().Be("hogehoge"); } { var client = new ArgumentPatternManualClient(channel); var result = await client.Unary1(10, 20, "__omit_last_argument__"); result.Id.Should().Be(30); result.Data.Should().Be("unknown"); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); services.AddCors(options => options.AddPolicy( "AllowAllOrigins", builder => builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader())); var rpcServerHost = this.Configuration.GetValue <string>("rpcServerHost"); var rpcServerPort = this.Configuration.GetValue <int>("rpcServerPort"); var channel = new Channel(rpcServerHost, rpcServerPort, ChannelCredentials.Insecure); var client = MagicOnionClient.Create <IBlockChainService>(channel); services.AddSingleton(client); }
public async Task ServerStreaming() { var client = MagicOnionClient.Create <ISimpleTest>(channel); { var r = await client.ServerStreaming1Task(10, 20, 3); await r.ResponseStream.MoveNext(); r.ResponseStream.Current.Is("30"); await r.ResponseStream.MoveNext(); r.ResponseStream.Current.Is("60"); await r.ResponseStream.MoveNext(); r.ResponseStream.Current.Is("90"); } { var r = client.Serverstreaming1(100, 200, 3); (await r.ResponseStream.MoveNext()).IsFalse(); } }
static void Main(string[] args) { Console.WriteLine("Hello World!"); var channel = new Channel("202.135.136.193", 8080, ChannelCredentials.Insecure); var testClient = MagicOnionClient.Create <ITest>(channel); var helloClient = MagicOnionClient.Create <IHello>(channel); var worldClient = MagicOnionClient.Create <IWorld>(channel); var result = testClient.Sum(100, 200).ResponseAsync.Result; Console.WriteLine("Test调用结果:" + result); Console.WriteLine($"Hello调用结果:{helloClient.Hello("李四").ResponseAsync.Result}"); Console.WriteLine($"World调用结果:{worldClient.World("李四").ResponseAsync.Result}"); //var channel2 = new Channel("202.135.136.193", 8081, ChannelCredentials.Insecure); //var client2 = MagicOnionClient.Create<ITest>(channel2); //var result2 = client2.SumAsync(100, 200).ResponseAsync.Result; //Console.WriteLine("客户端接收:" + result2); }
async Task ExecuteLoadItemsCommand() { var channel = new Channel("10.0.2.2", 12345, ChannelCredentials.Insecure); var DataStore = MagicOnionClient.Create <IServerDB>(channel); IsBusy = true; var location = Geolocation.GetLastKnownLocationAsync().Result; Item item_1 = new Item { Id = Guid.NewGuid().ToString(), Name = "First person", }; Item item_2 = new Item { Id = Guid.NewGuid().ToString(), Name = "Second person", }; await DataStore.Add(item_1); await DataStore.Add(item_2); try { Items.Clear(); var items = await DataStore.GetAll(); foreach (var item in items) { Items.Add(item); } } catch (Exception ex) { Debug.WriteLine(ex); } finally { IsBusy = false; } }
public async Task <AuthRes> AccountRegister(string userName, string email, string password) { if (userService == null) { userService = MagicOnionClient.Create <IUserService>(baseNetworkManager.ConnectChannel()); } string encUserId = await userService.AccountRegister(sendAES.Encrypt(userName), sendAES.Encrypt(email), sendAES.Encrypt(password)); if (encUserId == "") { return(AuthRes.Failed); } string userId = sendAES.Decrypt(encUserId); //送信とは別のキーで暗号化して保管 PlayerPrefs.SetString(PREF_AUTH_USERID, saveAES.Encrypt(userId)); PlayerPrefs.SetString(PREF_AUTH_PASSWORD, saveAES.Encrypt(password)); return(AuthRes.Success); }
public static async Task <ClientConnectionLifetimeManager> Connect(Channel channel, Metadata metadata = null) { var connectionId = Guid.NewGuid().ToString(); metadata = metadata ?? new Metadata(); metadata.Add(HeaderKey, connectionId); var source = new CancellationTokenSource(); var method = await MagicOnionClient.Create <IHeartbeat>(channel) .WithHeaders(metadata) .Connect(); // var task = method.ResponseStream.MoveNext() .ContinueWith((x, state) => { // both okay for success or failer ((CancellationTokenSource)state).Cancel(); }, source); return(new ClientConnectionLifetimeManager(task, source, connectionId, method)); }
public async Task <TService> GetRemoteService <TService>(string serviceName) where TService : IService <TService> { var serviceSubscriber = _subscriberFactory.CreateSubscriber(serviceName, ConsulSubscriberOptions.Default, new NanoFabric.Router.Throttle.ThrottleSubscriberOptions() { MaxUpdatesPeriod = TimeSpan.FromSeconds(30), MaxUpdatesPerPeriod = 20 }); await serviceSubscriber.StartSubscription(); serviceSubscriber.EndpointsChanged += async(sender, eventArgs) => { var endpoints = await serviceSubscriber.Endpoints(); var servicesInfo = string.Join(",", endpoints); }; ILoadBalancer loadBalancer = new RoundRobinLoadBalancer(serviceSubscriber); var endPoint = await loadBalancer.Endpoint(); var serviceChannel = _grpcChannelFactory.Get(endPoint.Address, endPoint.Port); return(MagicOnionClient.Create <TService>(serviceChannel)); }
/// <summary> /// 1111 /// </summary> /// <param name="id"></param> /// <returns></returns> public static async Task <MUserInfo> GetUserInfoAsync(int id, string url, int port) { try { var channel = new Channel(url, port, ChannelCredentials.Insecure); Console.WriteLine("开始连接服务器..."); await channel.ConnectAsync(); Console.WriteLine("连接成功!开始获取数据"); var client = MagicOnionClient.Create <IMyService>(channel); var result = client.GetUserInfo(id).ResponseAsync.Result; await channel.ShutdownAsync(); return(result); } catch (Exception ex) { return(new MUserInfo { UserName = ex.Message }); } }
public async Task ClientStreaming() { var client = MagicOnionClient.Create <ISimpleTest>(channel); { var r = await client.ClientStreaming1Task(); await r.RequestStream.WriteAsync(10); await r.RequestStream.WriteAsync(20); await r.RequestStream.WriteAsync(30); await r.RequestStream.CompleteAsync(); var result = await r.ResponseAsync; result.Is("finished:10, 20, 30"); } { var r = client.ClientStreaming1(); var result = await r.ResponseAsync; result.Is("finished:"); } }
public IEnumerator Pomu() { var channel = UnitTestClient.GetChannel(); var client = MagicOnionClient.Create <ISendMetadata>(channel); var pongpong = client.PangPong(); var res = pongpong.ResponseAsync.ToYieldInstruction(); yield return(res); if (res.HasError) { Debug.Log("Error:" + res.Error.ToString()); } else { Debug.Log("No Error"); } channel.ShutdownAsync().Subscribe(); }
public T CreateClient <T>() where T : IService <T> { return(MagicOnionClient.Create <T>(DefaultChannel)); }
public WorkflowController(IConfiguration configuration) { _workflowGrpcService = MagicOnionClient.Create <IWorkflowGrpcService>(CreateAuthenticatedChannel(configuration["AppSettings:UrlCpnucleoGrpcWorkflow"])); }