分类

链接

2019 年 6 月
 12
3456789
10111213141516
17181920212223
24252627282930

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET, DevOps, 微服务 > 正文
共享办公室出租
Ocelot+Consul+.netcore高可用&动态伸缩
.NET, DevOps, 微服务 暂无评论 阅读(344)

Ocelot 网关:

  1. publicclassStartup
  2. {
  3. publicStartup(IConfiguration configuration)
  4. {
  5. Configuration= configuration;
  6. }
  7. publicIConfigurationConfiguration{ get;}
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. publicvoidConfigureServices(IServiceCollection services)
  10. {
  11.             var config =newConfigurationBuilder()
  12. .AddJsonFile("Ocelot.json",false,true)
  13. .Build();
  14.             services.AddOcelot(config).AddConsul();
  15.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  16. //services.AddMvc(); -- no need MVC
  17. // Ocelot
  18. }
  19. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  20. publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env)
  21. {
  22. if(env.IsDevelopment())
  23. {
  24.                 app.UseDeveloperExceptionPage();
  25. }
  26. // Ocelot
  27.             app.UseOcelot().Wait();
  28.             app.UseMvc();//-- no need MVC
  29. }
  30. }

配置:

  1. {
  2. "ReRoutes":[
  3. {
  4. "ReRoutesCaseSensitive":false,
  5. "DownstreamPathTemplate":"/api/values",
  6. "DownstreamScheme":"http",
  7. "LoadBalancerOptions":{
  8. "Type":"RoundRobin"
  9. },
  10. "ServiceName":"MsgService",
  11. "UpstreamHttpMethod":["Get","Post"],
  12. "UpstreamPathTemplate":"/test",
  13. "UseServiceDiscovery":true
  14. }
  15. ],
  16. "GlobalConfiguration":{
  17. "RequestIdKey":"OcRequestId",
  18. "ServiceDiscoveryProvider":{
  19. "Host":"10.248.37.110",
  20. "Port":8500,
  21. "Type":"Consul"
  22. }
  23. }
  24. }

Consul配置:

  1. consul agent -data-dir D:\Tool\consul\tmp\node0 -node=node0 -bind=10.248.37.110-datacenter=dc1 -ui -client=10.248.37.110-server -bootstrap-expect 1

.net core web注册:

  1. publicclassStartup
  2. {
  3. publicStartup(IConfiguration configuration)
  4. {
  5. Configuration= configuration;
  6. }
  7. publicIConfigurationConfiguration{ get;}
  8. // This method gets called by the runtime. Use this method to add services to the container.
  9. publicvoidConfigureServices(IServiceCollection services)
  10. {
  11.             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
  12. }
  13. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  14. publicvoidConfigure(IApplicationBuilder app,IHostingEnvironment env,IApplicationLifetime appLifeTime)
  15. {
  16. if(env.IsDevelopment())
  17. {
  18.                 app.UseDeveloperExceptionPage();
  19. }
  20.             app.UseMvc();
  21.             string ip =Configuration["ip"]??"127.0.0.1";
  22.             string port =Configuration["port"]??"5000";
  23.             string serviceName ="MsgService";
  24. ServiceEntity serviceEntity =newServiceEntity
  25. {
  26.                 IP = ip,
  27. Port=Convert.ToInt32(port),
  28. ServiceName= serviceName,
  29. ConsulIP="10.248.37.110",
  30. ConsulPort="8500"
  31. };
  32.             app.RegisterConsul(appLifeTime, serviceEntity);
  33. }
  34. }

AppBuilderExtensions:

  1. publicstaticclassAppBuilderExtensions
  2. {
  3. publicstaticIApplicationBuilderRegisterConsul(thisIApplicationBuilder app,
  4. IApplicationLifetime lifetime,
  5. ServiceEntity serviceEntity)
  6. {
  7.             var consulClient =newConsulClient(=> x.Address=newUri($"http://{serviceEntity.ConsulIP}:{serviceEntity.ConsulPort}"));//请求注册的 Consul 地址
  8.             var httpCheck =newAgentServiceCheck()
  9. {
  10. DeregisterCriticalServiceAfter=TimeSpan.FromSeconds(5),//服务启动多久后注册
  11. Interval=TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
  12.                 HTTP = $"http://{serviceEntity.IP}:{serviceEntity.Port}/api/health",//健康检查地址
  13. Timeout=TimeSpan.FromSeconds(5)
  14. };
  15. // Register service with consul
  16.             var registration =newAgentServiceRegistration()
  17. {
  18. Checks=new[]{ httpCheck },
  19.                 ID =Guid.NewGuid().ToString(),
  20. Name= serviceEntity.ServiceName,
  21. Address= serviceEntity.IP,
  22. Port= serviceEntity.Port,
  23. Tags=new[]{ $"urlprefix-/{serviceEntity.ServiceName}"}//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别            
  24. };
  25.             consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
  26.             lifetime.ApplicationStopping.Register(()=>
  27. {
  28.                 consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册            
  29. });
  30. return app;
  31. }
  32. }
  33. publicclassServiceEntity
  34. {
  35. public string ServiceName{ get;set;}
  36. public string ConsulIP{ get;set;}
  37. public string ConsulPort{ get;set;}
  38. public string IP { get;set;}
  39. publicintPort{ get;set;}
  40. }

HealthController:

  1. [Produces("application/json")]
  2.     [Route("api/Health")]
  3.     public class HealthController : Controller
  4.     {
  5.         [HttpGet]
  6.         public IActionResult Get()
  7.         {
  8.             Console.WriteLine("健康检查" + DateTime.Now);
  9.             return Content("ok");
  10.         }
  11.     }

 

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:Ocelot+Consul+.netcore高可用&动态伸缩 | Bruce's Blog

发表评论

留言无头像?