{
...
"ServiceDiscovery": { "ServiceName": "DataService", "Consul": { "HttpEndpoint": "http://127.0.0.1:8500", "DnsEndpoint": { "Address": "127.0.0.1", "Port": 8600 } } } }
public class ServiceDisvoveryOptions
{
public string ServiceName { get; set; } public ConsulOptions Consul { get; set; } } public class ConsulOptions { public string HttpEndpoint { get; set; } public DnsEndpoint DnsEndpoint { get; set; } } public class DnsEndpoint { public string Address { get; set; } public int Port { get; set; } public IPEndPoint ToIPEndPoint() { return new IPEndPoint(IPAddress.Parse(Address), Port); } }
public class Startup
{
public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddDbContext<UserContext>(options => { options.UseMySQL(Configuration.GetConnectionString("MysqlUser")); }); //從配置文件中獲取ServiceDiscovery services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery")); //單例註冊ConsulClient services.AddSingleton<IConsulClient>(p => new ConsulClient(cfg => { var serviceConfiguration = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value; if (!string.IsNullOrEmpty(serviceConfiguration.Consul.HttpEndpoint)) { // if not configured, the client will use the default value "127.0.0.1:8500" cfg.Address = new Uri(serviceConfiguration.Consul.HttpEndpoint); } })); services.AddMvc(); //添加受權相關代碼 services.AddAuthentication(options => { options.DefaultAuthenticateScheme = "Cookies"; options.DefaultChallengeScheme = "oidc"; }) .AddCookie("Cookies") .AddOpenIdConnect(//配置受權信息相關 "oidc", options => { options.SignInScheme = "Cookies"; options.Authority = "http://localhost:52619";//受權地址 options.RequireHttpsMetadata = false;//ssl證書 options.ResponseType = OpenIdConnectResponseType.CodeIdToken; options.ClientId = "MVC"; options.ClientSecret = "Secret"; options.SaveTokens = true; // options.GetClaimsFromUserInfoEndpoint = true;//發起另一個請求~52619/content/userInfo 獲取userinfo //options.ClaimActions.MapJsonKey("sub", "sub"); //options.ClaimActions.MapJsonKey("preferred_username", "preferred_username"); //options.ClaimActions.MapJsonKey("sub", "sub"); //options.ClaimActions.MapJsonKey("avatar", "avatar"); //options.ClaimActions.MapCustomJson("role", jobject => jobject["role"].ToString()); options.Scope.Add("geteway_api"); options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("offline_access"); //options.Scope.Add("email"); } );//添加 } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory LoggerFactory, IApplicationLifetime lifetime, IConsulClient consulClient, IOptions<ServiceDisvoveryOptions> DisvoveryOptions) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseMvc(); app.UseAuthentication(); lifetime.ApplicationStarted.Register(() => { RegisterService(app, DisvoveryOptions, consulClient); }); lifetime.ApplicationStopped.Register(() => { DeRegisterService(app, DisvoveryOptions, consulClient); }); UserContextSeed.SeedAsync(app, LoggerFactory).Wait(); //InitUserDataBase(app);//初始化數據庫腳本再建立數據庫以後取消註釋 } //註冊服務方法 private void RegisterService(IApplicationBuilder app, IOptions<ServiceDisvoveryOptions> serviceOptions, IConsulClient consul) { //從當前啓動的url中拿到url var features = app.Properties["server.Features"] as FeatureCollection; var addresses = features.Get<IServerAddressesFeature>() .Addresses .Select(p => new Uri(p)); foreach (var address in addresses) { var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}"; var httpCheck = new AgentServiceCheck() { DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1), Interval = TimeSpan.FromSeconds(30), HTTP = new Uri(address, "HealthCheck").OriginalString }; var registration = new AgentServiceRegistration() { Checks = new[] { httpCheck }, Address = address.Host, ID = serviceId, Name = serviceOptions.Value.ServiceName, Port = address.Port }; consul.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); } } //移除方法 private void DeRegisterService(IApplicationBuilder app, IOptions<ServiceDisvoveryOptions> serviceOptions, IConsulClient consul) { //從當前啓動的url中拿到url var features = app.Properties["server.Features"] as FeatureCollection; var addresses = features.Get<IServerAddressesFeature>() .Addresses .Select(p => new Uri(p)); foreach (var address in addresses) { var serviceId = $"{serviceOptions.Value.ServiceName}_{address.Host}:{address.Port}"; consul.Agent.ServiceDeregister(serviceId).GetAwaiter().GetResult(); } } }
{ ... "ServiceDiscovery": { "ServiceName": "DataService", "Consul": { "HttpEndpoint": "http://127.0.0.1:8500", "DnsEndpoint": { "Address": "127.0.0.1", "Port": 8600 } } } }
public class ServiceDisvoveryOptions { public string ServiceName { get; set; } public ConsulOptions Consul { get; set; } } public class ConsulOptions { public string HttpEndpoint { get; set; } public DnsEndpoint DnsEndpoint { get; set; } } public class DnsEndpoint { public string Address { get; set; } public int Port { get; set; } public IPEndPoint ToIPEndPoint() { return new IPEndPoint(IPAddress.Parse(Address), Port); } }
//從配置文件中獲取ServiceDiscovery services.Configure<ServiceDisvoveryOptions>(Configuration.GetSection("ServiceDiscovery")); services.AddSingleton<IDnsQuery>(p => { var serviceConfig = p.GetRequiredService<IOptions<ServiceDisvoveryOptions>>().Value;//從配置文件中獲取consul相關配置信息 return new LookupClient(serviceConfig.Consul.DnsEndpoint.ToIPEndPoint()); });
private readonly string userServiceUrl = "http://localhost:60907/"; public UserService( IOptions<ServiceDisvoveryOptions> option,IDnsQuery dnsQuery) { var addrs = dnsQuery.ResolveService("service.consul", option.Value.ServiceName); var addressList = addrs.First().AddressList; var host = addressList.Any() ? addressList.First().ToString() : addrs.First().HostName; var port = addrs.First().Port; userServiceUrl = $"http://{host}:{port}"; }