Asp.Net Core Ocelot Consul 微服务

做一个简单的微服务架构如下图:

这个图表示的是一个网关代理Consul的两个服务,consul每个服务注册集群

  • 安装 Consul的服务,这里安装单机版的,集群版配置最低要求(3个Consul server)的需要三台虚拟机,穷
    这是下载地址 Consul 我这里部署的是CentOS7 ip是:192.168.31.140 记得关闭防火墙
yum instarll wget -y
yum instarll unzip -y
wget  https://releases.hashicorp.com/consul/1.7.2/consul_1.7.2_linux_amd64.zip
unzip consul_1.7.2_linux_amd64.zip
mv consul /usr/local/bin/
consul -v 查看图一代表安装成功了
nohup consul agent -server -ui -bootstrap-expect=1 -data-dir=/tmp/consul  -node=consul-1 -client=0.0.0.0   -datacenter=dc1 & 后台启动会生成一个nohup.out的日子文件
curl http://127.0.0.1:8500/ui/dc1/services  访问 如下图二代表服务启动OK
consul可以通过配置文件注册服务,我这里用的是api代码注册
配置文件注册vi /etc/consul/services_config.json创建配置文件重启即可

图一

图二

  • 接下来写ServiceUser的服务,选择asp.net core Api模板创建项目,安装Consul包

  • 添加一个健康检查的API直接返回OK
  • 再添加一个返回用户数据的API
  • 在写一个服务注册的方法在Startup.cs里,ip和port及id我是从命令行获取的其他配置均写在配置文件里
       private static void ServiceRegister(IConfiguration configuration)
        {
            
            ConsulClient client = new ConsulClient(new Action<ConsulClientConfiguration>(t => {
                t.Address = new Uri(configuration["consul:servicesAddr"]);//这是Consul的服务地址192.168.31.140
                t.Datacenter = configuration["consul:datacenter"];//储存名
            }));           
            //注册一个实例
            var result = client.Agent.ServiceRegister(new AgentServiceRegistration()
            {
                Address = configuration["ip"], //注册服务的IP
                ID = $"{configuration["consul:serviceName"]}{configuration["id"]}",//服务id唯一的
                Name = configuration["consul:serviceName"],//服务名
                Port = Convert.ToInt32(configuration["port"]),//端口
                Tags = null,
                Check = new AgentServiceCheck()
                {
                    HTTP = $"http://{configuration["ip"]}:{configuration["port"]}{configuration["consul:healthCheck"]}",//健康检查的API地址
                    Interval = new TimeSpan(0, 0, 10),//间隔多少检查一次
                    DeregisterCriticalServiceAfter = new TimeSpan(0, 1, 0) //多久注销不健康的服务
                }
            }).Result;
        }
  • 获取命令行参数 写在main 方法里如下图
new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddCommandLine(args).Build();

  • 编写配置文件
  "consul": {
    "servicesAddr": "http://192.168.31.140:8500",
    "datacenter": "dr1",
    "serviceName": "ServiceCommodity",
    "healthCheck": "/api/Health"
  }
  • ServiceCommodity和ServiceUser一样

    接下来启动实例注册服务,我这里用端口区分不同的实例
dotnet ServiceCommodity.dll --urls http://*:5000  --environment Development --ip 192.168.31.137 --port 5000 --id 1
dotnet ServiceCommodity.dll --urls http://*:5001  --environment Development --ip 192.168.31.137 --port 5001 --id 2
dotnet ServiceCommodity.dll --urls http://*:5002  --environment Development --ip 192.168.31.137 --port 5002 --id 3
dotnet ServiceUser.dll --urls http://*:6000  --environment Development --ip 192.168.31.137 --port 6000 --id 1
dotnet ServiceUser.dll --urls http://*:6001  --environment Development --ip 192.168.31.137 --port 6001 --id 2
dotnet ServiceUser.dll --urls http://*:6002  --environment Development --ip 192.168.31.137 --port 6002 --id 3


  • 接下来注册Ocelot网关,微服务是离不开网关的,现在可能看不出网关的效果,Consul搭建成集群就能看出效果了
    创建一个空的web项目安装如下两个包
  • 在Startup.cs 里注册
  • 创建ocelot.json配置文件
{
  "ReRoutes": [
    {
      "DownstreamPathTemplate": "/api/{controller}",//你的api路径
      "DownstreamScheme": "http",
      "UpstreamPathTemplate": "/dust/{controller}",//你映射的路径
      "UpstreamHttpMethod": [ "get", "post" ],//请求方法
      "ServiceName": "ServiceCommodity",//你的服务名称
      "LoadBalancerOptions": {
        "Type": "LeastConnection"//ocelot提供了几种均衡方法,这里用的是最小连接
      }
    },
    {
        "DownstreamPathTemplate": "/api/{controller}",
        "DownstreamScheme": "http",
        "UpstreamPathTemplate": "/dust1/{controller}",
        "UpstreamHttpMethod": [ "get", "post" ],
        "ServiceName": "ServiceUser",
        "LoadBalancerOptions": {
          "Type": "LeastConnection"
        }
    }
  ],
  "GlobalConfiguration": {
    "ServiceDiscoveryProvider": {
      "Host": "192.168.31.140",//你的Consul的ip地址
      "Port": 8500,//你的Consul的端口
      "ConfigurationKey": "Consul"//指定Consul,ocelot提供了几种,可以去官网看看
    }

  }
}
  • 加载配置文件
  .ConfigureAppConfiguration((hostingContext, config) =>
               {
                   config
                       .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                       .AddJsonFile("appsettings.json", true, true)
                       .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", true, true)
                       .AddJsonFile("ocelot.json")
                       .AddEnvironmentVariables();
               })

启动 dotnet GateWayOcelot.dll --urls http://*:7000  
  • 最后应用请求网关
  string[] userAry = null;
            string[] commodityAry = null;
            using (HttpClient httpClient = new HttpClient()) 
            {
                HttpResponseMessage httpResponseMessage  = httpClient.GetAsync("http://192.168.31.137:7000/dust1/user").Result;

                userAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
            }
            using (HttpClient httpClient = new HttpClient())
            {
                HttpResponseMessage httpResponseMessage = httpClient.GetAsync("http://192.168.31.137:7000/dust/commodity").Result;

                commodityAry = JsonConvert.DeserializeObject<string[]>(httpResponseMessage.Content.ReadAsStringAsync().Result);
            }
            this.ViewBag.msgText = $"{userAry[0]}和{userAry[1]}讨论项目,去烧烤摊点了{commodityAry[0]},{commodityAry[1]},{commodityAry[2]},第二天凌晨5点两个人支起了早餐摊!";

到此一个简单的微服务OK了
Demo下载地址

猜你喜欢

转载自www.cnblogs.com/SuperDust/p/12595299.html