Esempio n. 1
0
        public static void ConsulRegist(this IConfiguration configuration)
        {
            Consul.ConsulClient consulClient = new Consul.ConsulClient(config => {
                config.Address    = new Uri("http://localhost:8500/");
                config.Datacenter = "DC1";
            });
            string ip   = configuration["ip"];
            int    port = int.Parse(configuration["port"]);//命令行参数必须传入

            consulClient.Agent.ServiceRegister(new Consul.AgentServiceRegistration()
            {
                ID      = "service" + Guid.NewGuid(), //唯一的---科比 奥尼尔
                Name    = "DemoService",              //组名称-Group
                Address = ip,                         //其实应该写ip地址
                Port    = port,                       //不同实例
                //Tags = new string[] { weight.ToString() },//标签
                Check = new AgentServiceCheck()
                {
                    Interval = TimeSpan.FromSeconds(12),                      //间隔12s一次
                    HTTP     = $"http://{ip}:{port}/api/Health/Index",
                    Timeout  = TimeSpan.FromSeconds(5),                       //检测等待时间
                    DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(60) //失败后多久移除
                }
            });
        }
Esempio n. 2
0
        public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app)
        {
            var lifeTime       = app.ApplicationServices.GetRequiredService <IHostApplicationLifetime>();
            var serviceOptions = app.ApplicationServices.GetRequiredService <IOptions <ConsulServiceOptions> >().Value;
            var consulAddress  = Environment.GetEnvironmentVariable("WisderRegistryAddress");
            var serviceAddress = Environment.GetEnvironmentVariable("WisderServiceAddress");
            //string consulAddress = serviceOptions.RegistryAddress;
            //string serviceAddress = serviceOptions.ServiceAddress;
            string serviceId = $"{serviceOptions.ServiceName}_{Guid.NewGuid():n}";

            using (Consul.ConsulClient consulClient = new Consul.ConsulClient(config =>
            {
                config.Address = new Uri(consulAddress);
            }))
            {
                //自动获取当前服务地址
                //var features = app.Properties["server.Features"] as FeatureCollection;
                //var address = features.Get<IServerAddressesFeature>().Addresses.First();
                //var serviceUri = new Uri(address);

                if (string.IsNullOrWhiteSpace(serviceOptions.HealthCheck))
                {
                    serviceOptions.HealthCheck = "/healthy";
                }
                app.UseHealthChecks(serviceOptions.HealthCheck);

                var registration = new AgentServiceRegistration()
                {
                    ID      = serviceId,
                    Name    = serviceOptions.ServiceName,
                    Address = serviceAddress,// serviceOptions.ServiceAddress,
                    Port    = serviceOptions.ServicePort,
                    Tags    = serviceOptions.ServiceTags,
                    Check   = new AgentServiceCheck()
                    {
                        //注册超时
                        Timeout = TimeSpan.FromSeconds(5),
                        //服务停止多久后注销服务
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                        //健康检查接口地址
                        HTTP = $"{serviceOptions.ServiceScheme}://{serviceAddress}:{serviceOptions.ServicePort}{serviceOptions.HealthCheck}",
                        //健康检查
                        Interval = TimeSpan.FromSeconds(5)
                    }
                };
                consulClient.Agent.ServiceRegister(registration).Wait();
            }

            lifeTime.ApplicationStopping.Register(() =>
            {
                using (Consul.ConsulClient consulClientDeregister = new Consul.ConsulClient(config =>
                {
                    config.Address = new Uri(consulAddress);
                }))
                {
                    consulClientDeregister.Agent.ServiceDeregister(serviceId).Wait();
                }
            });
            return(app);
        }
 public void SetUp()
 {
     var clientConfig = new ConsulClientConfiguration {Address = new Uri("http://127.0.0.1:9500")};
     var client = new ConsulClient(clientConfig);
     var adapter = new ConsulAdapter(client);
     var flipper = new Flipper(adapter);
     _feature = flipper.Feature("unobtanium");
 }
 public new void SetUp()
 {
     Client = new ConsulClient();
     Adapter = new ConsulAdapter(Client, Namespace);
     var pairs =  Client.KV.Keys("/","/").Result;
     foreach (var key in pairs.Response)
     {
          Client.KV.DeleteTree(key).Wait();
     }
 }
Esempio n. 5
0
        private void Init(String deploymentId, String dataConnectionString, Logger logger)
        {
            _logger = logger;
            _deploymentId = deploymentId;
            _connectionString = dataConnectionString;

            _consulClient =
                new ConsulClient(
                    new ConsulClientConfiguration
                    {
                        Address = new Uri(dataConnectionString)
                    });
        }
Esempio n. 6
0
        static void Main()
        {
            using (var consul = new Consul.ConsulClient(c =>
            {
                c.Address = new Uri("http://127.0.0.1:8500");
            }))
            {
                //获取在Consul注册的全部服务
                var services = consul.Agent.Services().Result.Response;

                foreach (var s in services.Values)
                {
                    Console.WriteLine($"ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}");
                }
                var service = consul.Agent.Services().Result.Response.Values.Where(
                    p => p.Service.Equals("test-server-rpc", StringComparison.OrdinalIgnoreCase)).First();


                /*
                 * thrift的使用中一般是一个Server对应一个Processor和一个Transport,如果有多个服务的话,那必须要启动多个Server,
                 * 占用多个端口,这种方式显然不是我们想要的,所以thrift为我们提供了复用端口的方式,
                 * 通过监听一个端口就可以提供多种服务,
                 * 这种方式需要用到两个类:TMultiplexedProcessor和TMultiplexedProtocol。
                 *
                 */
                IPAddress ip = IPAddress.Parse(service.Address);

                using (TcpClient tcpClient = new System.Net.Sockets.TcpClient())
                {
                    tcpClient.Connect(ip, service.Port);
                    using (TTransport transport = new TSocket(tcpClient))
                    {
                        TTransport frameTransport = new TFramedTransport(transport);

                        TProtocol protocol = new TCompactProtocol(frameTransport);
                        //如果服务端使用TMultiplexedProcessor接收处理,客户端必须用TMultiplexedProtocol并且指定serviceName和服务端的一致
                        TMultiplexedProtocol multiplexedProtocol = new TMultiplexedProtocol(protocol, service.Service + "$com.msunsoft.service.calculator$2.0");
                        Client client = new Client(multiplexedProtocol);
                        //transport.Open();
                        Console.WriteLine(client.add(1, 2));
                    }
                }
            }


            Console.ReadLine();
        }
        private void Clean(string serverUrl)
        {
            var client = new Consul.ConsulClient(configuration => { configuration.Address = new Uri(serverUrl); });

            var checks = client.Agent.Checks().Result.Response; // client.Agent.Services().Result.Response;

            foreach (var service in checks.Values)
            {
                if (service.Status != HealthStatus.Passing)
                {
                    // logger.info("unregister : {}", check.getServiceId());
                    Console.WriteLine($"unreginer:{service.ServiceID}");
                    OpenOperator.Log($"unreginer:{service.ServiceID}");
                    client.Agent.ServiceDeregister(service.ServiceID);
                }
            }
        }
Esempio n. 8
0
        static void Main(string[] args)
        {
            var builder = new HostBuilder()
                          .ConfigureServices((hostContext, services) =>
            {
                services.UseBeetlexHttp(o =>
                {
                    o.LogToConsole     = true;
                    o.ManageApiEnabled = false;
                    o.Port             = 8080;
                    o.SetDebug();
                    o.LogLevel = BeetleX.EventArgs.LogType.Warring;
                },
                                        s =>
                {
                    var client = new Consul.ConsulClient(c =>
                    {
                        c.Address = new Uri("http://192.168.2.19:8500");
                    });
                    Dictionary <string, string> meta = new Dictionary <string, string>();
                    meta.Add("path", "^/home.*;^/hello.*");
                    client.Agent.ServiceDeregister("api_test1").Wait();
                    client.Agent.ServiceDeregister("api_test2").Wait();
                    client.Agent.ServiceRegister(new AgentServiceRegistration
                    {
                        Tags    = new string[] { "Bumblebee" },
                        Address = "192.168.2.18",
                        Port    = 8080,
                        Name    = "bumblebee_services",
                        Meta    = meta,
                        ID      = "api_test"
                    }).Wait();
                },
                                        typeof(Program).Assembly);
            });

            builder.Build().Run();
        }
        //---------------------------------------------------------------------
        public async Task<Dictionary<string, string>> GetAppSettings(string dir)
        {
            Dictionary<string, string> settings = new Dictionary<string, string>();

            Action<ConsulClientConfiguration> action_cfg = (cfg) =>
            {
                cfg.Address = new Uri(ConsulUri);
                //cfg.Datacenter = "dc1";
                //cfg.Token = "yep";
            };

            using (var client = new ConsulClient(action_cfg))
            {
                //config.DisableServerCertificateValidation = false;
                //await client.KV.Put(new KVPair("kv/reuseconfig") { Flags = 2000 });

                var r = await client.KV.List(dir);

                if (r.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    foreach (var i in r.Response)
                    {
                        if (i.Value == null) continue;

                        string k = Path.GetFileName(i.Key);
                        string v = Encoding.UTF8.GetString(i.Value);
                        settings[k] = v;
                    }
                }
                else
                {
                    Console.WriteLine(r.StatusCode);
                }
            }

            return settings;
        }
Esempio n. 10
0
 /// <summary>
 /// Snapshot can be used to query the /v1/snapshot endpoint to take snapshots of
 /// Consul's internal state and restore snapshots for disaster recovery.
 /// </summary>
 /// <param name="c"></param>
 internal Snapshot(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 11
0
 internal Semaphore(ConsulClient c)
 {
     _client = c;
     _cts    = new CancellationTokenSource();
 }
Esempio n. 12
0
 internal AutoSemaphore(ConsulClient c, SemaphoreOptions opts)
     : base(c)
 {
     Opts = opts;
     CancellationToken = Acquire();
 }
Esempio n. 13
0
 internal DisposableLock(ConsulClient client, LockOptions opts, CancellationToken ct)
     : base(client)
 {
     Opts = opts;
     CancellationToken = Acquire(ct);
 }
Esempio n. 14
0
 internal Health(ConsulClient c)
 {
     _client = c;
 }
 public GetRequest(ConsulClient client, string url) :
     this(client, url, null, null)
 {
 }
Esempio n. 16
0
 internal DisposableLock(ConsulClient client, LockOptions opts, CancellationToken ct)
     : base(client)
 {
     Opts = opts;
     CancellationToken = Acquire(ct);
 }
 public string TestNamespace(string name)
 {
     var client = new ConsulClient();
     var adapter = new ConsulAdapter(client, name);
     return adapter.Namespace;
 }
Esempio n. 18
0
 internal ACLReplication(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 19
0
 public KV(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 20
0
 internal Role(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 21
0
 /// <summary>
 /// Operator can be used to perform low-level operator tasks for Consul.
 /// </summary>
 /// <param name="c"></param>
 internal Operator(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 22
0
 internal Event(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 23
0
 internal Token(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 24
0
 internal AuthMethod(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 25
0
 internal Semaphore(ConsulClient c)
 {
     _client = c;
     _cts = new CancellationTokenSource();
 }
Esempio n. 26
0
 internal AutoSemaphore(ConsulClient c, SemaphoreOptions opts)
     : base(c)
 {
     Opts = opts;
     CancellationToken = Acquire();
 }
Esempio n. 27
0
 internal Raw(ConsulClient c)
 {
     _client = c;
 }
 public GetRequest(ConsulClient client, string url, QueryOptions options) :
     this(client, url, options, null)
 {
 }
Esempio n. 29
0
 internal Coordinate(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 30
0
 internal Lock(ConsulClient c)
 {
     _client = c;
     _cts = new CancellationTokenSource();
 }
Esempio n. 31
0
 internal Coordinate(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 32
0
 internal Catalog(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 33
0
 internal Agent(ConsulClient c)
 {
     _client       = c;
     _nodeNameLock = new AsyncLock();
 }
Esempio n. 34
0
 internal PreparedQuery(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 35
0
 internal Session(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 36
0
 public KV(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 37
0
 internal Catalog(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 38
0
 internal Status(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 39
0
 internal Event(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 40
0
 internal ACL(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 41
0
 internal Agent(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 42
0
 internal Policy(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 43
0
 internal Raw(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 44
0
 internal Lock(ConsulClient c)
 {
     _client = c;
     _cts    = new CancellationTokenSource();
 }
Esempio n. 45
0
 internal PreparedQuery(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 46
0
 internal Health(ConsulClient c)
 {
     _client = c;
 }
Esempio n. 47
0
 internal Status(ConsulClient c)
 {
     _client = c;
 }