C#编程之.NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现
小标 2019-04-08 来源 : 阅读 4537 评论 0

摘要:本文主要向大家介绍了C#编程之.NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

本文主要向大家介绍了C#编程之.NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现,通过具体的内容向大家展示,希望对大家学习C#编程有所帮助。

C#编程之.NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现

一、关于Steeltoe与Spring Cloud

  

  Steeltoe的官方地址://steeltoe.io/,其官方介绍如下:

Steeltoe is an open source project that enables .NET developers to implement industry standard best practices when building resilient microservices for the cloud. The Steeltoe client libraries enable .NET Core and .NET Framework apps to easily leverage Netflix Eureka, Hystrix, Spring Cloud Config Server, and Cloud Foundry services.  

  我们主要关注的就是这句话:enable .NET Core and .NET Framework apps to easily leverage Netflix Eureka, Hystrix, Spring Cloud Config Server, and Cloud Foundry services  => 可以使我们的.NET/.NET Core应用程序轻松地使用Spring Cloud的一些核心组件如Eureka、Hystrix、Config Server以及云平台服务(例如PCF)。这里也可以看出,目前Steeltoe的客户端也仅仅支持轻松使用这几个组件而已。

  Spring Cloud是一个基于Java的成熟的微服务全家桶架构,它为配置管理、服务发现、熔断器、智能路由、微代理、控制总线、分布式会话和集群状态管理等操作提供了一种简单的开发方式,已经在国内众多大中小型的公司有实际应用案例。许多公司的业务线全部拥抱Spring Cloud,部分公司选择部分拥抱Spring Cloud。

二、快速构建Eureka Server

  (1)使用IDE (我使用的是IntelljIdea)新建一个Spring Boot应用程序

  (2)pom.xml中增加Spring Cloud的依赖和Eureka的starter

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <!-- eureka server -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka-server</artifactId>
        </dependency>
    </dependencies>

    <!-- spring cloud dependencies -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Edgware.SR3</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

  (3)在启动类上添加EnableEurekaServer注解

@SpringBootApplication
@EnableEurekaServerpublic class EurekaServiceApplication {    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class, args);
    }
}

  (4)必要的Eureka配置

spring:
  application:
    name: eureka-server

server:
  port: 8761eureka:
  server:
    enable-self-preservation: false          # 本地调试环境下关闭自我保护机制
    eviction-interval-timer-in-ms: 5000      # 清理间隔时间,单位为毫秒
  instance:
    hostname: localhost
    #prefer-ip-address: true
  client:
    register-with-eureka: false
    fetch-registry: false

  PS:这里关闭了Eureka的自我保护机制,是因为可以让我们方便地看到服务被移除的效果。至于Eureka的自我保护机制,这是因为Eureka考虑到生产环境中可能存在的网络分区故障,会导致微服务与Eureka Server之间无法正常通信。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。

  (5)启动项目,效果如下图所示:暂时无任何服务注册到该Eureka Server中

  

三、在ASP.NET Core中集成Eureka

3.1 快速准备几个ASP.NET Core WebAPI

  

3.2 安装Steeltoe服务发现客户端并启用

  分别对三个WebAPI通过Nuget安装服务发现.NET Core客户端(目前最新版本是2.1.0):

PM> Install-Package Pivotal.Discovery.ClientCore  

  按照惯例,需要在启动类中启用该客户端:

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {        // Add Steeltoe Discovery Client service        services.AddDiscoveryClient(Configuration);
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseMvc();        // Add Steeltoe Discovery Client service        app.UseDiscoveryClient();
    }

3.3 Eureka Client必要配置

  分别对三个WebAPI进行如下配置(appSettings.json),下面以agent-service为例:

  "spring": {    "application": {      "name": "agent-service"
    }
  },  "eureka": {    "client": {      "serviceUrl": "//localhost:8761/eureka/",      "shouldFetchRegistry": true,      "validateCertificates": false
    },    "instance": {      "port": 8010,      "preferIpAddress": true,      "instanceId": "agent-service-container:8010"
    }
  }

  此外,如果想启用Steeltoe的日志,看到更多调试信息,可以加上以下配置:

"Logging": {    "IncludeScopes": false,    "LogLevel": {      "Default": "Warning",      "Pivotal": "Debug",      "Steeltoe": "Debug"
    }
  }

3.4 加入服务消费示例代码

  这里假设其中的一个premium-service需要调用client-service的一个API接口,于是编写了一个clientservice去消费API。这里借助一个加入了DiscoveryHttpClientHandler的HttpClient来进行目标地址的解析和请求,具体代码如下:

    public class ClientService : IClientService
    {
        DiscoveryHttpClientHandler _handler;        private const string API_GET_CLIENT_NAME_URL = "//client-service/api/values";        private ILogger<ClientService> _logger;        public ClientService(IDiscoveryClient client, ILoggerFactory logFactory = null)
        {
            _handler = new DiscoveryHttpClientHandler(client);
            _logger = logFactory?.CreateLogger<ClientService>();
        }        private HttpClient GetClient()
        {            var client = new HttpClient(_handler, false);            return client;
        }        public async Task<string> GetClientName(int clientId)
        {
            _logger?.LogInformation("GetClientName");            var client = GetClient();            return await client.GetStringAsync($"{API_GET_CLIENT_NAME_URL}/{clientId}");
        }
    }

  在实际请求中,会先从Eureka取得client-service所对应的IP和端口,然后解析为一个真实的访问URL再得到最终的消费结果。而这里这个GetClientName实际的返回结果很简单,就返回一个字符串:“Edison Zhou”。

  此外,如果我们用的是.NET Core 2.1,那么也可以借助HttpClientFactory来实现(Steeltoe的组件升级到2.1后也开始支持HttpClientFactory),可以参考下面的示例代码。更多有关HttpClientFactory的介绍。

public class Startup
{    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }    public IConfiguration Configuration { get; set; }    public void ConfigureServices(IServiceCollection services)
    {
      services.AddDiscoveryClient(Configuration);      // Add Steeltoe handler to container
      services.AddTransient<DiscoveryHttpMessageHandler>();      // Configure a HttpClient
      services.AddHttpClient("values", c =>
      {
              c.BaseAddress = new Uri("//client-service/api/values/");
      })
      .AddHttpMessageHandler<DiscoveryHttpMessageHandler>()
      .AddTypedClient<IClientService, ClientService>();      // Add framework services.      services.AddMvc();
    }

    ......
}

四、快速验证性测试

4.1 启动三个WebAPI,查看服务是否注册到Eureka

  

  可以看到,三个服务均已成功注册到Eureka Server。

4.2 关闭Agent-Service,查看Eureka Server是否移除该服务

  

  可以看到,Agent-Service已被Eureka移除。

4.3 启动多个Client-Service实例,查看Eureka Server服务列表

  

  可以看到,Client-Service的两个实例都已注册。

4.4 从Premium-Service消费Client-Service,验证是否能成功消费

  第一次调用:

  

  第二或第三次调用:

  

  可以看到,客户端每次(不一定是每次)解析得到的都是服务集群中的不同实例节点,因此也就实现了类似于Ribbon的客户端的负载均衡效果。

五、小结

  本文简单地介绍了一下Steeltoe与Spring Cloud,然后演示了一下基于Steeltoe使得ASP.NET Core应用程序与Spring Cloud Eureka进行集成以实现服务注册与发现的效果。更多内容,请参考Steeltoe官方文档或示例项目。对于已有Spring Cloud微服务架构环境的项目,如果想要ASP.NET Core微服务与Java Spring Boot微服务一起共享Spring Cloud Eureka来提供服务,基于Steeltoe是一个选择(虽然觉得不是最优,毕竟是寄居)。

本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标编程语言C#.NET频道!

本文由 @小标 发布于职坐标。未经许可,禁止转载。
喜欢 | 1 不喜欢 | 0
看完这篇文章有何感觉?已经有1人表态,100%的人喜欢 快给朋友分享吧~
评论(0)
后参与评论

您输入的评论内容中包含违禁敏感词

我知道了

助您圆梦职场 匹配合适岗位
验证码手机号,获得海同独家IT培训资料
选择就业方向:
人工智能物联网
大数据开发/分析
人工智能Python
Java全栈开发
WEB前端+H5

请输入正确的手机号码

请输入正确的验证码

获取验证码

您今天的短信下发次数太多了,明天再试试吧!

提交

我们会在第一时间安排职业规划师联系您!

您也可以联系我们的职业规划师咨询:

小职老师的微信号:z_zhizuobiao
小职老师的微信号:z_zhizuobiao

版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
 沪公网安备 31011502005948号    

©2015 www.zhizuobiao.com All Rights Reserved

208小时内训课程