Пример #1
0
 public static void AddSingletonOrleansClusterClient(this IServiceCollection services, OrleansConfig config)
 {
     services.AddSingleton <IClusterClient>(serviceProvider =>
     {
         var builder = new ClientBuilder();
         builder.AddOrleansClusterClient(config);
         IClusterClient client = builder.Build();
         client.Connect(CreateRetryFilter()).GetAwaiter().GetResult();
         return(client);
     });
 }
Пример #2
0
 private static void ConnectToServer(IClusterClient client)
 {
     try
     {
         client.Connect().GetAwaiter().GetResult();//just let it retry
     }
     catch (Exception ex)
     {
         Task.Delay(3000);//wait for server to start and retry agian
         ConnectToServer(client);
     }
 }
Пример #3
0
        //private static ILoggerFactory CreateLoggerFactory(IServiceProvider serviceProvider)
        //{

        //    OrleansConfig config = serviceProvider.GetService<OrleansConfig>();
        //    ILoggerFactory loggerFactory = new LoggerFactory();
        //    LogLevel logLevel = Enum.Parse<LogLevel>(config.LogLevel, true);
        //    string[] loggerTypes = config.LoggerTypes?.Split(";", StringSplitOptions.RemoveEmptyEntries);

        //    if(HasLoggerType(config, "console"))
        //    {
        //        loggerFactory.AddConsole(logLevel);
        //    }

        //    if (HasLoggerType(config, "debug"))
        //    {
        //        loggerFactory.AddDebug(logLevel);
        //    }

        //    if(HasLoggerType(config, "appinsights"))
        //    {
        //        AppInsightsOptions appOptions = new AppInsightsOptions()
        //        {
        //            DeveloperMode = false,
        //            InstrumentationKey = config.AppInsightsKey

        //        };

        //        loggerFactory.AddAppInsights(appOptions);
        //    }

        //    return loggerFactory;
        //}

        private static IClusterClient CreateClusterClient(IServiceProvider serviceProvider)
        {
            OrleansConfig config      = serviceProvider.GetService <OrleansConfig>();
            string        storageType = GetStorageType(config.DataConnectionString);

            TcpGatewayOptions options = serviceProvider.GetOptionsByName <TcpGatewayOptions>("TcpGatewayOptions");

            if (config.Dockerized)
            {
                var localClient = new ClientBuilder()
                                  .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPiSystem).Assembly))
                                  .UseLocalhostClustering()
                                  .Build();

                localClient.Connect(RetryFilter).GetAwaiter();
                return(localClient);
            }
            else
            {
                var client = new ClientBuilder()
                             .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPiSystem).Assembly))
                             .Configure <testME.ClusterOptions>(op =>
                {
                    op.ClusterId = config.ClusterId;
                    op.ServiceId = config.ServiceId;
                });



                if (HasLoggerType(config, "appinsights"))
                {
                    client.AddApplicationInsightsTelemetryConsumer(config.AppInsightsKey);
                }

                if (storageType == "Redis")
                {
                    ILoggerFactory loggerFactory = serviceProvider.GetService <ILoggerFactory>();
                    ILogger <RedisGatewayListProvider> logger = loggerFactory.CreateLogger <RedisGatewayListProvider>();
                    client.UseRedisGatewayListProvider(logger, op =>
                                                       op.ConnectionString = config.DataConnectionString
                                                       );
                }
                else if (storageType == "AzureStorage")
                {
                    client.UseAzureStorageClustering(op => op.ConnectionString = config.DataConnectionString);
                }

                IClusterClient clusterClient = client.Build();

                clusterClient.Connect(RetryFilter).GetAwaiter();
                return(clusterClient);
            }
        }
Пример #4
0
        static async Task InitializeOrleans()
        {
            //var config = new ClusterConfiguration();
            //config.Globals.DataConnectionString = "Server=tnwli-pc.dmtnprod.lan;Database=ApprovalSystem;User Id=QTIP;Password=QTIP; ";
            //config.Globals.ClusterId = "AprovalSiloID";
            //config.Globals.LivenessType = GlobalConfiguration.LivenessProviderType.SqlServer;
            //config.Globals.ReminderServiceType = GlobalConfiguration.ReminderServiceProviderType.SqlServer;
            //config.Defaults.PropagateActivityId = true;
            //config.Defaults.ProxyGatewayEndpoint = new System.Net.IPEndPoint(IPAddress.Any, 18000);


            var config = new ClientConfiguration();

            config.ClusterId           = "AprovalSiloID";
            config.PropagateActivityId = true;
            config.AdoInvariant        = "System.Data.SqlClient";

            config.DataConnectionString = "Server=tnwli-pc.dmtnprod.lan;Database=ApprovalSystem;User Id=QTIP;Password=QTIP; ";
            config.GatewayProvider      = ClientConfiguration.GatewayProviderType.SqlServer;
            Console.WriteLine("Initializing ... ");
            client = new ClientBuilder()
                     .ConfigureApplicationParts(p => p.AddFromAppDomain().AddFromApplicationBaseDirectory())
                     .UseConfiguration(config).Build();

            var builder = ClientBuilder.CreateDefault()
                          .UseConfiguration(config)
                          .ConfigureApplicationParts(parts => parts.AddFromAppDomain().AddFromApplicationBaseDirectory());

            client = builder.Build();

            try
            {
                await client.Connect();

                running = true;
                Console.WriteLine("Initialized.");
                var grain = client.GetGrain <IUser>(Guid.Empty);
                while (running)
                {
                    string proposal = "ACED Proposal";
                    //int num = 15;
                    var response = await grain.Approve(proposal);

                    Console.WriteLine($"{proposal} was Approved : { response}");
                    await Task.Delay(1000);
                }
                client.Dispose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Пример #5
0
        /// <summary>
        /// Connects the cluster client to the cluster.
        /// </summary>
        /// <returns>A <see cref="Task"/> representing any asynchronous operation.</returns>
        private async Task ConnectOrleansClient()
        {
            this.logger.Information("Connecting to Orleans cluster.");

            await Policy.Handle <Exception>().WaitAndRetryForeverAsync(
                i => TimeSpan.FromSeconds(3),
                (ex, ts) =>
            {
                if (ex.GetType() == typeof(SiloUnavailableException))
                {
                    this.logger.Error("Silo is not available...");
                }
                else
                {
                    this.logger.Error(ex, "Connection to Orleans cluster failed!");
                    clusterClient?.Dispose();
                }
            }).ExecuteAsync(
                async() =>
            {
                // TODO: check if db connection is needed here or static clustering is the better approach to connect to silo host
                clusterClient = new ClientBuilder().Configure <ClusterOptions>(
                    options =>
                {
                    var clusterOptions = this.clusterConfiguration.OrleansConfiguration.ClusterOptions;
                    options.ClusterId  = clusterOptions.ClusterId;
                    options.ServiceId  = clusterOptions.ServiceId;
                }).UseAdoNetClustering(
                    options =>
                {
                    options.Invariant        = "Npgsql";
                    options.ConnectionString = this.clusterConfiguration.DatabaseSettings.ToConnectionString();
                }).AddSimpleMessageStreamProvider("SMSProvider").ConfigureLogging(
                    logging =>
                {
                    logging.AddSerilog();
                }).Build();
                await clusterClient.Connect(
                    async ex =>
                {
                    await Task.Delay(500);
                    return(true);
                });

                this.logger.Information("Connection to Orleans cluster successful!");
            });

            while (!clusterClient.IsInitialized)
            {
                await Task.Delay(500);
            }
        }
Пример #6
0
        private static async Task <IClusterClient> StartClientWithRetries(int initializeAttemptsBeforeFailing = 5)
        {
            int            attempt = 0;
            IClusterClient client;

            while (true)
            {
                try
                {
                    var siloAddress = IPAddress.Loopback; // IPAddress.Parse("192.168.1.250"); //IPAddress.Loopback
                    var gatewayPort = 30020;
                    var uri         = (new IPEndPoint(siloAddress, gatewayPort)).ToGatewayUri();

                    client = new ClientBuilder()
                             .Configure <ClusterOptions>(opt =>
                    {
                        opt.ClusterId = "test1";
                        opt.ServiceId = "test1";
                    })
                             .ConfigureLogging(logging =>
                    {
                        logging.AddConsole();
                        logging.SetMinimumLevel(LogLevel.Information);
                    })
                                                                                        ////集群
                             .UseStaticClustering(options => options.Gateways.Add(uri)) //集群
                             .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ITest).Assembly).WithReferences())
                             .Build();

                    await client.Connect();

                    Console.WriteLine("Client successfully connect to silo host");
                    break;
                }
                catch (SiloUnavailableException ex)
                {
                    attempt++;
                    Console.WriteLine($"Attempt {attempt} of {initializeAttemptsBeforeFailing} failed to initialize the Orleans client.");
                    if (attempt > initializeAttemptsBeforeFailing)
                    {
                        throw;
                    }
                    await Task.Delay(TimeSpan.FromSeconds(4));
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

            return(client);
        }
Пример #7
0
        public GraphManager(string connectionString, LoggerType loggers, LogLevel logLevel,
                            string instrumentationKey = null)
        {
            ClientBuilder builder = new ClientBuilder();

            builder.ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPiSystem).Assembly));

            AddStorageProvider(builder, connectionString);
            AddAppInsighlts(builder, loggers, instrumentationKey);
            AddLoggers(builder, loggers, logLevel);
            client = builder.Build();
            client.Connect(CreateRetryFilter()).GetAwaiter().GetResult();
        }
Пример #8
0
        static async Task RunAsync(ISiloHost silo, IClusterClient client, string mapFileName)
        {
            await silo.StartAsync();

            await client.Connect();

            Console.WriteLine("Map file name is '{0}'.", mapFileName);
            Console.WriteLine("Setting up Adventure, please wait ...");
            Adventure adventure = new Adventure(client);

            adventure.Configure(mapFileName).Wait();
            Console.WriteLine("Adventure setup completed.");
        }
Пример #9
0
        /// <summary>
        /// Get Orleans ClusterClient
        /// </summary>
        /// <typeparam name="TGrainInterface"></typeparam>
        private IClusterClient GetClusterClient <TGrainInterface>(string serviceId)
        {
            IClusterClient client = null;
            string         name   = serviceId;

            if (string.IsNullOrEmpty(serviceId))
            {
                name = typeof(TGrainInterface).Namespace;
            }
            int attempt = 0;

            while (true)
            {
                try
                {
                    if (clients.ContainsKey(name))
                    {
                        client = clients[name];
                    }
                    else
                    {
                        lock (clients)
                        {
                            if (!clients.ContainsKey(name))
                            {
                                client = BuilderClient(name);
                                clients.Add(name, client);
                            }
                            else
                            {
                                client = clients[name];
                            }
                        }
                    }

                    if (!client.IsInitialized)
                    {
                        client.Connect().Wait();
                        Logger.LogDebug($"Connection {name} Sucess...");
                    }
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message);
                    attempt++;
                    Logger.LogError($"Connection {name} Faile...");
                    throw new Exception($"Connection {name} Faile...");
                }
                return(client);
            }
        }
Пример #10
0
        private static async Task Execute(IClusterClient client)
        {
            await client.Connect();

            var ra = new Random((int)DateTime.Now.Ticks);

            for (var i = 0; i < 1000; i++)
            {
                var id    = ra.Next(100);
                var grain = client.GetGrain <IDemoGrain>(id);

                var a = ra.Next(10);
                var b = ra.Next(10);

                try
                {
                    switch (ra.Next(3))
                    {
                    case 0:
                    {
                        var res = await grain.Sum(a, b);

                        Console.WriteLine($"{a}+{b}+id = {res}");
                        break;
                    }

                    case 1:
                    {
                        var res = await grain.Mul(a, b);

                        Console.WriteLine($"{a}*{b}+id = {res}");
                        break;
                    }

                    case 2:
                    {
                        var res = await grain.Div(a, b);

                        Console.WriteLine($"{a}/{b}+id = {res}");
                        break;
                    }
                    }

                    await Task.Delay(1000);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
Пример #11
0
 public IClusterClient CreateClient()
 {
     if (!_client.IsInitialized)
     {
         lock (connectLock)
         {
             if (!_client.IsInitialized)
             {
                 _client.Connect().GetAwaiter().GetResult();
             }
         }
     }
     return(_client);
 }
Пример #12
0
        static void Main(string[] args)
        {
            Console.CancelKeyPress += (sender, cancelArgs) =>
            {
                _tokenSource.Cancel();
            };

            _kernel = new StandardKernel()
                      .WithBsonIds()
                      .WithActorsClient();
            _cluster = _kernel.Get <IClusterClient>();
            _cluster.Connect().Wait();
            MainAsync(args).Wait();
        }
        public static IClusterClient GetInstance(TraceWriter log = null)
        {
            if (_instance == null)
            {
                log?.Info(@"Creating connection to Orleans silo...");
                Trace.WriteLine(@"t: Creating connection to Orleans silo...");
                //// Parse the IP Address out of app settings
                //var siloIpAddressString = Environment.GetEnvironmentVariable(@"SiloEndpointIP");
                //var siloIpAddressBytes = siloIpAddressString.Split('.').Select(i => byte.Parse(i)).ToArray();

                //// parse the port to uint to ensure the value is >=0
                //var siloPort = uint.Parse(Environment.GetEnvironmentVariable(@"SiloEndpointPort"));
                //log?.Info($@" @ {siloIpAddressString}:{siloPort}");
                //Trace.WriteLine($@"t:  @ {siloIpAddressString}:{siloPort}");

                var builder = new ClientBuilder()
                              .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = @"ForFunctions";
                    options.ServiceId = @"AzureFunctionsSample";
                })
                              .UseAzureStorageClustering(opt => opt.ConnectionString = Environment.GetEnvironmentVariable(@"ClusterStorageConnectionString"));

                _instance = builder.Build();
                log?.Info(@"Client successfully built with Azure Storage clustering...");
                Trace.WriteLine(@"t: Client successfully built with Azure Storage clustering...");

                const int maxRetries = 5;
                int       retryCount = 0;
                _instance.Connect(async ex =>
                {
                    log.Info(ex.Message);

                    if (++retryCount < maxRetries)
                    {
                        await Task.Delay(TimeSpan.FromSeconds(3));
                        return(true);
                    }
                    else
                    {
                        return(false);
                    }
                }).Wait();

                log?.Info(@"Connected.");
                Trace.WriteLine(@"t: Connected.");
            }

            return(_instance);
        }
 private IClusterClient ConnectClient(string serviceName, IClusterClient client)
 {
     try
     {
         client.Connect(RetryFilter).Wait();
         _logger.LogDebug($"Connection {serviceName} Sucess...");
         return(client);
     }
     catch (Exception ex)
     {
         _logger.LogError($"Connection {serviceName} Faile...", ex);
         throw new Exception($"Connection {serviceName} Faile...");
     }
 }
Пример #15
0
        public async Task StartClient()
        {
            _client = new ClientBuilder()
                      .UseLocalhostClustering()
                      .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "Maddalena";
                options.ServiceId = "Maddalena";
            })
                      .ConfigureLogging(logging => logging.AddConsole())
                      .Build();

            await _client.Connect();
        }
Пример #16
0
        public ClientService()
        {
            client = new ClientBuilder()
                     .UseLocalhostClustering()
                     .Configure <ClusterOptions>(options =>
            {
                options.ClusterId = "dev";
                options.ServiceId = "SmartCache";
            })
                     //.ConfigureLogging(logging => logging.AddConsole())
                     .Build();

            client.Connect(RetryFilter).Wait();
        }
        /// <summary>
        /// 获取Orleans ClusterClient
        /// </summary>
        /// <typeparam name="TGrainInterface"></typeparam>
        private IClusterClient GetClusterClient <TGrainInterface>()
        {
            IClusterClient client = null;
            string         name   = typeof(TGrainInterface).Assembly.Location;

            int attempt = 0;

            while (true)
            {
                try
                {
                    client = clientsCache.GetOrAdd(name, (key) =>
                    {
                        return(BuilderClient(name));
                    });
                    if (client.IsInitialized)
                    {
                        return(client);
                    }
                    else
                    {
                        lock (client)
                        {
                            //客户端未初始化,连接服务端
                            client.Connect().Wait();
                            logger.LogDebug($"Connection {name} Sucess...");
                        }
                    }
                }
                catch (Exception ex)
                {
                    logger.LogError(ex.Message);
                    attempt++;
                    if (attempt <= this.options.InitializeAttemptsBeforeFailing)
                    {
                        client = clientsCache.GetOrAdd(name, (key) =>
                        {
                            return(BuilderClient(name));
                        });

                        logger.LogDebug($"Attempt {attempt} of " + this.options.InitializeAttemptsBeforeFailing + " failed to initialize the Orleans client.");
                        Task.Delay(TimeSpan.FromSeconds(4)).Wait();
                        continue;
                    }
                    logger.LogError($"Connection {name} Faile...");
                    throw new Exception($"Connection {name} Faile...");
                }
                return(client);
            }
        }
Пример #18
0
        private static async Task StartClientWithRetries(IClusterClient client)
        {
            for (var i = 0; i < 5; i++)
            {
                try
                {
                    await client.Connect();

                    return;
                }
                catch (Exception)
                { }
                await Task.Delay(TimeSpan.FromSeconds(5));
            }
        }
Пример #19
0
        public static void AddSingletonOrleansClusterClient(this IServiceCollection services, OrleansConfig config)
        {
            services.AddSingleton(serviceProvider =>
            {
                var builder = new ClientBuilder();
                if (!string.IsNullOrEmpty(config.InstrumentationKey))
                {
                    builder.AddApplicationInsightsTelemetryConsumer(config.InstrumentationKey);
                }

                builder.AddOrleansClusterClient(config);
                IClusterClient client = builder.Build();
                client.Connect(CreateRetryFilter()).GetAwaiter().GetResult();
                return(client);
            });
        }
Пример #20
0
        public virtual async Task <IActionResult> Connect()
        {
            try
            {
                await _client.Connect();

                return(Json(new
                {
                    _client.IsInitialized
                }));
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
Пример #21
0
        private static async Task <IClusterClient> StartClientWithRetries2(int initializeAttemptsBeforeFailing = 5)
        {
            Uri            u       = (new IPEndPoint(IPAddress.Parse("127.0.0.1"), 30000)).ToGatewayUri();
            int            attempt = 0;
            IClusterClient client;

            while (true)
            {
                try
                {
                    client = new ClientBuilder()

                             .Configure <ClusterOptions>(options =>
                    {
                        options.ClusterId = "dev";
                        options.ServiceId = "HelloWorldAppClient";
                    })
                             .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(ITest).Assembly).WithReferences())

                             .UseStaticClustering(configureOptions => configureOptions.Gateways.Add(u))
                             .ConfigureLogging(logging =>
                    {
                        logging.AddConsole();
                        logging.SetMinimumLevel(LogLevel.Information);
                    })

                             .Build();

                    await client.Connect();

                    Console.WriteLine("Client successfully connect to silo host");
                    break;
                }
                catch (SiloUnavailableException)
                {
                    attempt++;
                    Console.WriteLine($"Attempt {attempt} of {initializeAttemptsBeforeFailing} failed to initialize the Orleans client.");
                    if (attempt > initializeAttemptsBeforeFailing)
                    {
                        throw;
                    }
                    await Task.Delay(TimeSpan.FromSeconds(4));
                }
            }

            return(client);
        }
Пример #22
0
        private async Task StartClientWithRetries(IClusterClient client)
        {
            for (var i = 0; i < 5; i++)
            {
                try
                {
                    await client.Connect();

                    return;
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex, "Error starting Orleans client");
                }
                await Task.Delay(TimeSpan.FromSeconds(2));
            }
        }
Пример #23
0
        private static async Task StartClientWithRetries(IClusterClient client)
        {
            for (var i = 0; i < 5; i++)
            {
                try
                {
                    await client.Connect();

                    return;
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error starting Orleans client" + ex.ToString());
                }
                await Task.Delay(TimeSpan.FromSeconds(2));
            }
        }
Пример #24
0
 private IClusterClient ConnectClient(string serviceName, IClusterClient client)
 {
     try
     {
         var res = client.Connect(RetryFilter).Wait(TimeSpan.FromSeconds(10));
         if (!res)
         {
             throw new Exception($"Connection {serviceName} timeout...");
         }
         _logger.LogDebug($"Connection {serviceName} Sucess...");
         return(client);
     }
     catch (Exception ex)
     {
         throw new Exception($"Connection {serviceName} Faile...", ex);
     }
 }
Пример #25
0
        public static IClusterClient ConnectWithRetry(this IClusterClient client)
        {
            int attempt = 0;

            if (client.IsInitialized)
            {
                return(client);
            }
            client.Connect(async e =>
            {
                ConsoleLogger.WriteStatus($"Attempt {attempt++} failed to initialize the Orleans client.");
                ConsoleLogger.WriteError(e.Message);
                await Task.Delay(3000);
                return(true);
            })
            .Wait();
            return(client);
        }
Пример #26
0
        public ChunklerClient(ChunklerClientOptions options, ILogger logger)
        {
            _options = options ?? throw new ArgumentNullException(nameof(options));
            _logger  = logger ?? throw new ArgumentNullException(nameof(logger));

            _clusterClient = new ClientBuilder()
                             .UseLocalhostClustering()
                             .Configure <ClusterOptions>(cfg =>
            {
                cfg.ClusterId = options.ClusterOptions.ClusterId;
                cfg.ServiceId = options.ClusterOptions.ServiceId;
            })
                             .AddSimpleMessageStreamProvider(ChunklerConstants.SimpleChunkStreamProvider)
                             .Build();

            _clusterClient.Connect().Wait();
            _streamProvider = _clusterClient.GetStreamProvider(ChunklerConstants.SimpleChunkStreamProvider);
        }
Пример #27
0
        private static async Task <IClusterClient> InitialiseClient()
        {
            int tryTimes = 10;

            while (tryTimes > 0)
            {
                try
                {
                    client = new ClientBuilder()
                             .UseAdoNetClustering(options =>
                    {
                        options.Invariant        = "MySql.Data.MySqlClient";
                        options.ConnectionString = "server=localhost;port=3306;database=orleans;user id=root;password=;SslMode=none;";
                    })
                             .Configure <ClusterOptions>(options =>
                    {
                        options.ClusterId = "dev";
                        options.ServiceId = "OrleansTest";
                    })
                             .ConfigureApplicationParts(parts => parts.AddApplicationPart(typeof(IPersonGrain).Assembly))
                             .ConfigureLogging(log => log.SetMinimumLevel(LogLevel.Warning).AddConsole())
                             .Build();

                    await client.Connect();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
                finally
                {
                    await Task.Delay(TimeSpan.FromSeconds(5));

                    if (client != null && !client.IsInitialized)
                    {
                        client.Dispose();
                        client = null;
                    }
                }
                tryTimes--;
            }

            return(client);
        }
Пример #28
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IClusterClient client)
        {
            app.UseResponseCompression();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseMigrationsEndPoint();
                app.UseWebAssemblyDebugging();
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseBlazorFrameworkFiles();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseIdentityServer();
            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapRazorPages();
                endpoints.MapControllers();
                endpoints.MapHub <ChatHub>("/hubs/chathub");
                endpoints.MapFallbackToFile("index.html");
            });

            var bundledMode = Configuration.GetValue <bool>("BundledMode");

            if (bundledMode)
            {
                BlazorSignalrOrleans.Silo.Program.RunMainAsync();
            }

            client.Connect();
        }
Пример #29
0
        public static async Task <OrleanService> GetInstance()
        {
            if (instance == null)
            {
                instance = new OrleanService();

                _client = new ClientBuilder()
                          .UseLocalhostClustering()
                          .Configure <ClusterOptions>(options =>
                {
                    options.ClusterId = "dev";
                    options.ServiceId = "TestCSharpApp";
                })
                          .ConfigureLogging(logging => logging.AddConsole())
                          .Build();
                await _client.Connect(CreateRetryFilter());
            }
            return(instance);
        }
        public static bool TryStart(string location, string hostname)
        {
            try
            {
                if (Orleans.GrainClient.IsInitialized)
                {
                    return(true);
                }

                var config = new Orleans.Runtime.Configuration.ClientConfiguration();
                config.DeploymentId        = "PiraeusDeployment";
                config.PropagateActivityId = true;

                var hostEntry = Dns.GetHostEntry(System.Environment.GetEnvironmentVariable("GATEWAY_ORLEANS_SILO_DNS_HOSTNAME"));
                var ip        = hostEntry.AddressList[0];
                Trace.TraceWarning("Host Entry IP Address {0}", ip.ToString());
                config.Gateways.Add(new IPEndPoint(ip, 30000));
                client = new ClientBuilder().UseConfiguration(config).Build();
                Task task = client.Connect();
                Task.WaitAll(task);

                //var ip = hostEntry.AddressList.Length > 1 ? hostEntry.AddressList[1] : hostEntry.AddressList[0];



                //var ip = hostEntry.AddressList[0];
                //config.Gateways.Add(new IPEndPoint(ip, 30000));

                //IPAddress ip = GetIP(hostname);
                //IPAddress ip = System.Net.Dns.GetHostAddresses(hostname)[0];
                //var config = new Orleans.Runtime.Configuration.ClientConfiguration();
                //config.Gateways.Add(new IPEndPoint(ip, 30000));
                //config.OpenConnectionTimeout = TimeSpan.FromMinutes(2);
                Orleans.GrainClient.Initialize(config);
            }
            catch (Exception ex)
            {
                Trace.TraceWarning("Failed to intiailize orleans client via hostname");
                Trace.TraceError(ex.Message);
            }

            return(Orleans.GrainClient.IsInitialized);
        }