public ActionResult <string> Get() { using (var consul = new Consul.ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); //Consul地址 })) { //取出全部的ConsulDemo服务 var services = consul.Agent.Services().Result.Response.Values.Where(p => p.Service.Equals("ConsulDemo", StringComparison.OrdinalIgnoreCase)); //客户端负载均衡,随机选出一台服务 Random rand = new Random(); var index = rand.Next(services.Count()); var s = services.ElementAt(index); Console.WriteLine($"Index={index},ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}"); //向服务发送请求 using (var httpClient = new HttpClient()) { var result = httpClient.GetAsync($"http://{s.Address}:{s.Port}/api/Values/1"); return($"调用{s.Service},状态:{result.Result.StatusCode},响应:{result.Result.Content.ReadAsStringAsync().Result}"); } } }
public static Consul.AgentService FindServiceEndpoint(string name) { Consul.ConsulClient _client = new Consul.ConsulClient(); var res = _client.Agent.Services().Result; if (res.StatusCode != HttpStatusCode.OK) { throw new ApplicationException($"Failed to query services"); } var rnd = new Random(); var now = DateTime.UtcNow; var targets = res.Response .Values .Where(x => x.Service == name) .ToList(); while (0 < targets.Count) { var choice = rnd.Next(targets.Count); var target = targets[choice]; return(target); } throw new ApplicationException($"Can't find service {name}"); }
static void Main(string[] args) { 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}"); //} //取出全部的DemoService服务 var services = consul.Agent.Services().Result.Response.Values.Where(p => p.Service.Equals("DemoService", StringComparison.OrdinalIgnoreCase)); //客户端负载均衡,随机选出一台服务 Random rand = new Random(); var index = rand.Next(services.Count()); var s = services.ElementAt(index); Console.WriteLine($"Index={index},ID={s.ID},Service={s.Service},Addr={s.Address},Port={s.Port}"); //向服务发送请求 using (var httpClient = new HttpClient()) using (var httpContent = new StringContent("{FirstName:'Alex',LastName:'Wang'}", Encoding.UTF8, "application/json")) { var result = httpClient.PostAsync($"http://{s.Address}:{s.Port}/api/Values", httpContent); Console.WriteLine($"调用{s.Service},状态:{result.Result.StatusCode}"); } } Console.ReadKey(); }
public async void RegisterService(IApplicationBuilder app, ILoggerFactory loggerFactory) { var logger = loggerFactory.CreateLogger("Consul"); try { logger.LogInformation("Registering service with Consul"); //Get the first IPv4 address var addrs = await Dns.GetHostAddressesAsync(Dns.GetHostName()); var uniqueAddrs = addrs.Where(addr => addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).Select(a => a.ToString()).Distinct().ToArray(); logger.LogInformation($"Unique IPv4 addresses: {string.Join(",", uniqueAddrs)}"); //Determine the IP address that this service advertises itself on //This is the first IP address which will be the overlay network if using that, otherwise it will be the bridge network string serviceIp = uniqueAddrs[0]; logger.LogInformation($"Container IP for service registration is {serviceIp}"); //Determine the IP address that Consul should call back to for health checks // This should be the bridge network, which will be the second entry if using an overlay network string healthCallbackIp = uniqueAddrs.Length > 1 ? uniqueAddrs[1] : uniqueAddrs[0]; logger.LogInformation($"Container IP for health check is {healthCallbackIp}"); var addresses = app.ServerFeatures.Get <IServerAddressesFeature>(); var serviceUri = new Uri(addresses.Addresses.Single()); logger.LogInformation($"Service URI is {serviceUri.ToString()}"); var checkAddress = $"{serviceUri.Scheme}://{healthCallbackIp}:{serviceUri.Port.ToString()}{HealthPath}"; logger.LogInformation($"Health check address is {checkAddress}"); string consulHost = Environment.GetEnvironmentVariable("CONSUL_HOST") ?? "localhost"; logger.LogInformation($"Consul host is {consulHost}"); using (var c = new Consul.ConsulClient(cnfg => cnfg.Address = new Uri($"http://{consulHost}:8500"))) { var writeResult = await c.Agent.ServiceRegister( new Consul.AgentServiceRegistration() { Name = "backend", Port = serviceUri.Port, Address = serviceIp, Check = new Consul.AgentServiceCheck { HTTP = checkAddress, Interval = TimeSpan.FromSeconds(2.0) } }); logger.LogInformation($"Completed registration with Consul with response code {writeResult.StatusCode.ToString()}"); } } catch (Exception ex) { logger.LogError($"Error registering service with Consul: {ex.ToString()}"); } }
// This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddConsul(); string connectString = "", redisConnectString = ""; //var connectString = Configuration.GetConnectionString("IdentityServerDB"); //var redisConnectString = Configuration.GetConnectionString("WisderMicroServiceRedis"); #region 从配置中心获取配置参数 var consulAddress = Environment.GetEnvironmentVariable("WisderRegistryAddress"); using (Consul.ConsulClient consulClient = new Consul.ConsulClient(config => { config.Address = new Uri(consulAddress); })) { connectString = Encoding.UTF8.GetString(consulClient.KV.Get("IdentityServerDB").Result.Response.Value); redisConnectString = Encoding.UTF8.GetString(consulClient.KV.Get("WisderMicroServiceRedis").Result.Response.Value); } #endregion services.AddSingleton <IFreeSql>((provider) => { var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connectString).Build(); return(fsql); }); services.AddDistributedRedisCache(redisConnectString); var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name; var basePath = PlatformServices.Default.Application.ApplicationBasePath; services.AddIdentityServer(option => { option.Caching.ClientStoreExpiration = TimeSpan.FromMinutes(5); option.Caching.ResourceStoreExpiration = TimeSpan.FromMinutes(5); option.Caching.CorsExpiration = TimeSpan.FromMinutes(5); }) .AddSigningCredential(new X509Certificate2(Path.Combine(basePath, Configuration["Certificates:CerPath"]), Configuration["Certificates:Password"])) .AddConfigurationStore(options => { options.ConfigureDbContext = dbBuilder => { dbBuilder.UseMySQL(connectString, sql => sql.MigrationsAssembly(migrationsAssembly)); }; }).AddOperationalStore(options => { options.ConfigureDbContext = dbBuilder => { dbBuilder.UseMySQL(connectString, sql => sql.MigrationsAssembly(migrationsAssembly)); }; }).AddConfigurationStoreCache() .AddResourceOwnerValidator <UserPasswordLoginValidator>(); }
public ActionResult <string> Value(string key) { using (var consul = new Consul.ConsulClient(c => { c.Address = new Uri("http://127.0.0.1:8500"); //Consul地址 })) { var response = consul.KV.Get(key).Result.Response; if (response != null) { return(Encoding.UTF8.GetString(response.Value)); } return(""); } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddConsul(); string connectString = "", redisConnectString = ""; //var connectString = Configuration.GetConnectionString("IdentityServerDB"); //var redisConnectString = Configuration.GetConnectionString("WisderMicroServiceRedis"); #region 从配置中心获取配置参数 var consulAddress = Environment.GetEnvironmentVariable("WisderRegistryAddress"); using (Consul.ConsulClient consulClient = new Consul.ConsulClient(config => { config.Address = new Uri(consulAddress); })) { connectString = Encoding.UTF8.GetString(consulClient.KV.Get("UserServiceDB").Result.Response.Value); redisConnectString = Encoding.UTF8.GetString(consulClient.KV.Get("WisderMicroServiceRedis").Result.Response.Value); } #endregion var dataCenterId = Configuration.GetValue <long>("DataCenterId"); var serverId = Configuration.GetValue <long>("ServerId"); services.AddSingleton <IdBuilder>(p => new IdBuilder(dataCenterId, serverId)); services.AddSingleton <IFreeSql>((provider) => { var fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(FreeSql.DataType.MySql, connectString).Build(); return(fsql); }); services.AddDistributedRedisCache(redisConnectString); services.AddScoped <UnitOfWorkManager>(); services.AddScoped <IUserRepository, UserRepository>(); services.AddScoped <IUserService, UserServiceImpl>(); services.AddControllers(option => { option.Filters.Add <BizExceptionFilter>(); }).AddNewtonsoftJson(options => { //忽略循环引用 options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; //不使用驼峰样式的key options.SerializerSettings.ContractResolver = new DefaultContractResolver(); //设置时间格式 options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; }); }
public async Task <string> GetGoods() { var httpClient = new HttpClient(); using (var consul = new Consul.ConsulClient(c => { c.Address = new Uri("http://192.168.1.104:8500"); })) { var services = consul.Agent.Services().Result.Response.Values.Where(p => p.Service.Equals("product-service", StringComparison.OrdinalIgnoreCase));; Random rand = new Random(); var index = rand.Next(services.Count()); var s = services.ElementAt(index); return(await httpClient.GetStringAsync($"http://{s.Address}:{s.Port}/healthCheck")); } }
static void Main(string[] args) { using (var consul = new Consul.ConsulClient(c => { c.Address = new Uri("http://118.89.39.14: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}"); } } Console.ReadKey(); }
public List <CatalogService> GetService(string serviceName, bool passingOnly) { if (!_ocelotGateway) { var client = new consul((cfg) => { var uriBuilder = new UriBuilder(ConsulHost); cfg.Address = uriBuilder.Uri; }); var result = client.Health.Service(serviceName, "", passingOnly).Result; if (result.StatusCode != HttpStatusCode.OK) { throw new Exception($"无法获取consul服务注册,{result.StatusCode }"); } return(result.Response.Select(b => new CatalogService { ServiceAddress = b.Service.Address, ServiceID = b.Service.ID, ServiceName = serviceName, ServicePort = b.Service.Port, ServiceMeta = b.Service.Meta, ServiceTags = b.Service.Tags }).ToList()); } var url = _ocelotGateway ? $"{ConsulHost}/consul/GetService?serviceName={serviceName}&passingOnly={passingOnly}" : $"{ConsulHost}/v1/catalog/service/{serviceName}"; try { var result = request.Get(url); var services = result.ToObject <List <CatalogService> >(); return(services); } catch (Exception ero) { throw new Exception($"无法获取consul服务注册,{ero}"); } }