03 .NET CORE 2.2 使用OCELOT -- Docker中的Consul

部署consul-docker镜像

先搜索consul的docker镜像

docker search consul

然后选择了第一个,也就是官方镜像

 

 下载镜像

docker pull consul

然后运行镜像

docker run -d --name consul -v /home/root/config:/config --restart=always\
-p 8300:8300 \
-p 8301:8301 \
-p 8301:8301/udp \
-p 8302:8302 \
-p 8302:8302/udp \
-p 8400:8400 \
-p 8500:8500 \
consul agent -server \
-bootstrap-expect 1 \
-ui \
-client 0.0.0.0

 

consul中每个启动参数的含义,参考了以下链接:

https://www.bitdoom.com/2017/09/07/p125/

https://yq.aliyun.com/articles/536508

https://blog.csdn.net/yinwaner/article/details/80762757

https://blog.csdn.net/qq_36228442/article/details/89085373

https://www.cnblogs.com/PearlRan/p/11225953.html

https://www.cnblogs.com/magic-chenyang/p/7975677.html

 

注册服务

参考链接:

https://blog.csdn.net/hailang2ll/article/details/82079192

 

新建一个common项目

 

  

新建ConsulBuilderExtensions.cs 、ConsulService.cs、HealthService.cs

 1 using Consul;
 2 using Microsoft.AspNetCore.Builder;
 3 using Microsoft.AspNetCore.Hosting;
 4 using System;
 5 using System.Collections.Generic;
 6 using System.Linq;
 7 using System.Threading.Tasks;
 8 
 9 namespace Test.WebApi.Common
10 {
11     public static class ConsulBuilderExtensions
12 
13     {
14 
15         // 服务注册
16 
17         public static IApplicationBuilder RegisterConsul(this IApplicationBuilder app, IApplicationLifetime lifetime, HealthService healthService, ConsulService consulService)
18 
19         {
20 
21             var consulClient = new ConsulClient(x => x.Address = new Uri($"http://{consulService.IP}:{consulService.Port}"));//请求注册的 Consul 地址
22 
23             var httpCheck = new AgentServiceCheck()
24 
25             {
26 
27                 DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),//服务启动多久后注册
28 
29                 Interval = TimeSpan.FromSeconds(10),//健康检查时间间隔,或者称为心跳间隔
30 
31                 HTTP = $"http://{healthService.IP}:{healthService.Port}/api/health",//健康检查地址
32 
33                 Timeout = TimeSpan.FromSeconds(5)
34 
35             };
36 
37             // Register service with consul
38 
39             var registration = new AgentServiceRegistration()
40 
41             {
42 
43                 Checks = new[] { httpCheck },
44 
45                 ID = healthService.Name + "_" + healthService.Port,
46 
47                 Name = healthService.Name,
48 
49                 Address = healthService.IP,
50 
51                 Port = healthService.Port,
52 
53                 Tags = new[] { $"urlprefix-/{healthService.Name}" }//添加 urlprefix-/servicename 格式的 tag 标签,以便 Fabio 识别
54 
55             };
56 
57             consulClient.Agent.ServiceRegister(registration).Wait();//服务启动时注册,内部实现其实就是使用 Consul API 进行注册(HttpClient发起)
58 
59             lifetime.ApplicationStopping.Register(() =>
60 
61             {
62 
63                 consulClient.Agent.ServiceDeregister(registration.ID).Wait();//服务停止时取消注册
64 
65             });
66 
67             return app;
68 
69         }
70 
71     }
72 }

 

 1 namespace Test.WebApi.Common
 2 {
 3     public class ConsulService
 4 
 5     {
 6 
 7         public string IP { get; set; }
 8 
 9         public int Port { get; set; }
10 
11     }
12 }

 

 1 namespace Test.WebApi.Common
 2 {
 3     public class HealthService
 4     {
 5         public string Name { get; set; }
 6 
 7         public string IP { get; set; }
 8 
 9         public int Port { get; set; }
10     }
11 }

 

两个webapi项目引用这个common项目

并修改各自的 startup.cs

 1 public void Configure(IApplicationBuilder app, IHostingEnvironment env, IApplicationLifetime lifetime)
 2         {
 3             if (env.IsDevelopment())
 4             {
 5                 app.UseDeveloperExceptionPage();
 6             }
 7             else
 8             {
 9                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
10                 app.UseHsts();
11             }
12             ConsulService consulService = new ConsulService()
13             {
14                 IP = Configuration["Consul:IP"],
15                 Port = Convert.ToInt32(Configuration["Consul:Port"])
16             };
17             HealthService healthService = new HealthService()
18             {
19                 IP = Configuration["Service:IP"],
20                 Port = Convert.ToInt32(Configuration["Service:Port"]),
21                 Name = Configuration["Service:Name"],
22             };
23 
24             app.RegisterConsul(lifetime, healthService, consulService);
25 
26             //app.UseConsul();
27             app.UseHttpsRedirection();
28             app.UseMvc();
29         }

修改 appsettings.json。 192.168.2.16是本机地址。192.168.2.29是docker中consul的地址。 两个项目的配置类似,区别是本地项目的端口9001、9002。

 1 {
 2   "Logging": {
 3     "LogLevel": {
 4       "Default": "Warning"
 5     }
 6   },
 7   "AllowedHosts": "*",
 8 
 9   "Service": {
10     "Name": "ApiService",
11     "IP": "192.168.2.16",
12     "Port": "9001"
13   },
14   "Consul": {
15     "IP": "192.168.2.29",
16     "Port": "8500"
17   }
18 }

 

IIS部署 .NET CORE 2.2

参考链接:

https://www.cnblogs.com/wxlv/p/netcore-to-iis.html

 

部署期间遇到过以下问题

HTTP Error 500.35 - ANCM Multiple In-Process Applications in same Process ASP.NET Core 3

解决方法:两个webapi项目 用不一样的应用池。

 

 

部署完成后,测试下 各自项目的 /api/health接口是否正常。

 

 

测试网关项目

修改网关项目的配置configuration.json

 1 {
 2   "ReRoutes": [
 3     {
 4       "UseServiceDiscovery": true,
 5       "DownstreamPathTemplate": "/{url}",
 6       "DownstreamScheme": "http",
 7       "ServiceName": "ApiService",
 8       "LoadBalancerOptions": {
 9         "Type": "RoundRobin"
10       },
11       "UpstreamPathTemplate": "/{url}",
12       "UpstreamHttpMethod": [ "Get" ],
13       "ReRoutesCaseSensitive": false
14     }
15   ],
16   "GlobalConfiguration": {
17     "ServiceDiscoveryProvider": {
18       "Host": "192.168.2.29",
19       "Port": 8500,
20       "Type": "PollConsul",
21       "PollingInterval": 100
22     }
23   }
24 }

修改 startup.cs

 1 public void ConfigureServices(IServiceCollection services)
 2         {
 3             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
 4             services.AddOcelot(new ConfigurationBuilder()
 5                     .AddJsonFile("configuration.json")
 6                     .Build())
 7                     .AddConsul();
 8         }
 9 
10         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
11         public async void Configure(IApplicationBuilder app, IHostingEnvironment env)
12         {
13             if (env.IsDevelopment())
14             {
15                 app.UseDeveloperExceptionPage();
16             }
17             else
18             {
19                 // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
20                 app.UseHsts();
21             }
22             await app.UseOcelot();
23             app.UseHttpsRedirection();
24             app.UseMvc();
25         }

F5启动项目

 

 

 

 

 

 

 

posted @ 2019-10-18 14:43  枫欣慧20151010  阅读(375)  评论(1编辑  收藏  举报