.net core+Spring Cloud学习之路 二

  前言:

  原本计划这次写一下搭建eureka群集。但是发现上次写的只是服务的注册,忘了写服务的发现,所以这次先把服务发现补上去。

  1.   我们基于上篇文章,再新建两个.net core web api项目,分别起名为order_one,order_two, 作为两个订单服务。我们以order_one为例。
    1. 同理先使用nuget添加Pivotal.Discovery.ClientCore库。
    2. Startup.cs 中添加
      1 public void ConfigureServices(IServiceCollection services)
      2         {
      3             // services.AddDiscoveryClient(Configuration);
      4             services.AddDiscoveryClient(Configuration);
      5             services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
      6         }
       1 public void Configure(IApplicationBuilder app, IHostingEnvironment env,ILoggerFactory loggerFactory)
       2         {
       3             loggerFactory.AddConsole(Configuration.GetSection("Logging"));
       4             loggerFactory.AddDebug();
       5             if (env.IsDevelopment())
       6             {
       7                 app.UseDeveloperExceptionPage();
       8             }
       9             else
      10             {
      11                 app.UseHsts();
      12             }
      13             app.UseDiscoveryClient();
      14             app.UseHttpsRedirection();
      15             app.UseMvc();
      16         }

      需要using Pivotal.Discovery.Client; 

    3. appsettings.json 添加eureka服务配置
      {
        "Logging": {
          "IncludeScopes": false,
          "Debug": {
            "LogLevel": {
              "Default": "Warning"
            }
          },
          "Console": {
            "LogLevel": {
              "Default": "Warning"
            }
          }
        },
        "spring": {
          "application": {
            "name": "order"
          }
        },
        "eureka": {
          "client": {
            "serviceUrl": "http://localhost:8888/eureka/",
            "shouldFetchRegistry": true
          },
          "instance": {
            "port": 5001,
            "hostName": "localhost"
          }
        }
      }

       

    4. 修改launchSettings.json 端口改为5001
      {
        "iisSettings": {
          "windowsAuthentication": false,
          "anonymousAuthentication": true,
          "iisExpress": {
            "applicationUrl": "http://localhost:5001/",
            "sslPort": 0
          }
        },
        "profiles": {
          "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "api/values",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            }
          },
          "Order_One": {
            "commandName": "Project",
            "launchBrowser": true,
            "launchUrl": "api/order",
            "environmentVariables": {
              "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "http://localhost:5001/"
          }
        }
      }

       

    5. 添加一个控制器,返回order one
      [Route("api")]
          public class ValuesController : Controller
          {
      
      
              // GET api/values
              [HttpGet("value")]
              public string Get()
              {
                  return "Order One";
              }
          }

       

    6. 再建一个同样的项目,order_two
  2. 上述项目创建完成后,我们先启动spring cloud项目。然后同时启动三个.net core项目。这个时候我们刷新一下spring cloud页面。

    这个时候发现名为order的有两个服务。

  3. 修改一下orderserver的控制器代码
    [Route("api")]
        public class ValuesController : Controller
        {
    
            DiscoveryHttpClientHandler _handler;
    
           
    
            private const string GET_SERVICES_URL = "http://order/api/value";
            private ILogger<ValuesController> _logger;
    
    
            public ValuesController(IDiscoveryClient client, ILoggerFactory logFactory = null)
            {
                _handler = new DiscoveryHttpClientHandler(client);
                _logger = logFactory?.CreateLogger<ValuesController>();
            }
    
            [HttpGet("order")]
            public async Task<string> GetServices()
            {
                _logger?.LogInformation("GetServices");
                var client = GetClient();
                return await client.GetStringAsync(GET_SERVICES_URL);
    
            }
    
            private HttpClient GetClient()
            {
                var client = new HttpClient(_handler, false);
                return client;
            }
    
        }

    然后再次启动这三个.net core项目,并访问http://localhost:5000/api/order,如图,他成功返回了order two,多刷新几次会发现返回的order One 和 order two是来回变的。

    说明eureka服务中心帮我们实现了负载均衡。

     

  4. 这个时候,我们可以把order_one 或者 order_two关掉一个。我们再次访问http://localhost:5000/api/order会出现一次错误,然后eureka会自动把有问题的服务踢掉(时间可配置),再次访问不再有问题。

参考资料:

Spring Cloud

Steeltoe

总结

现在网络上类似这样的文章很多,自己再单独写一份就是为了做个笔记,跟各位大牛交流一下,自己也学习学习。

posted on 2019-01-15 10:59  请叫我小冯哥哥  阅读(1101)  评论(0编辑  收藏  举报