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) //失败后多久移除 } }); }
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(); } }
private void Init(String deploymentId, String dataConnectionString, Logger logger) { _logger = logger; _deploymentId = deploymentId; _connectionString = dataConnectionString; _consulClient = new ConsulClient( new ConsulClientConfiguration { Address = new Uri(dataConnectionString) }); }
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); } } }
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; }
/// <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; }
internal Semaphore(ConsulClient c) { _client = c; _cts = new CancellationTokenSource(); }
internal AutoSemaphore(ConsulClient c, SemaphoreOptions opts) : base(c) { Opts = opts; CancellationToken = Acquire(); }
internal DisposableLock(ConsulClient client, LockOptions opts, CancellationToken ct) : base(client) { Opts = opts; CancellationToken = Acquire(ct); }
internal Health(ConsulClient c) { _client = c; }
public GetRequest(ConsulClient client, string url) : this(client, url, null, null) { }
public string TestNamespace(string name) { var client = new ConsulClient(); var adapter = new ConsulAdapter(client, name); return adapter.Namespace; }
internal ACLReplication(ConsulClient c) { _client = c; }
public KV(ConsulClient c) { _client = c; }
internal Role(ConsulClient c) { _client = c; }
/// <summary> /// Operator can be used to perform low-level operator tasks for Consul. /// </summary> /// <param name="c"></param> internal Operator(ConsulClient c) { _client = c; }
internal Event(ConsulClient c) { _client = c; }
internal Token(ConsulClient c) { _client = c; }
internal AuthMethod(ConsulClient c) { _client = c; }
internal Raw(ConsulClient c) { _client = c; }
public GetRequest(ConsulClient client, string url, QueryOptions options) : this(client, url, options, null) { }
internal Coordinate(ConsulClient c) { _client = c; }
internal Lock(ConsulClient c) { _client = c; _cts = new CancellationTokenSource(); }
internal Catalog(ConsulClient c) { _client = c; }
internal Agent(ConsulClient c) { _client = c; _nodeNameLock = new AsyncLock(); }
internal PreparedQuery(ConsulClient c) { _client = c; }
internal Session(ConsulClient c) { _client = c; }
internal Status(ConsulClient c) { _client = c; }
internal ACL(ConsulClient c) { _client = c; }
internal Agent(ConsulClient c) { _client = c; }
internal Policy(ConsulClient c) { _client = c; }