纵有疾风起
人生不言弃

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

Tip: 此篇已加入.NET Core微服务基础系列文章索引

=>  Steeltoe目录快速导航

1. 基于Steeltoe使用Spring Cloud Eureka

2. 基于Steeltoe使用Spring Cloud Zuul

3. 基于Steeltoe使用Spring Cloud Hystrix

4. 基于Steeltoe使用Spring Cloud Config

5. 基于Steeltoe使用Zipkin

一、关于Steeltoe与Spring Cloud

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图

  Steeltoe的官方地址:http://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。有关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-serverserver:  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之间无法正常通信。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。关于自我保护机制,更多内容可以参考:《Spring Cloud Eureka全解之自我保护机制》 

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

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图1

三、在ASP.NET Core中集成Eureka

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

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图2

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": "http://localhost:8761/eureka/",      "shouldFetchRegistry": true,      "validateCertificates": false    },    "instance": {      "port": 8010,      "preferIpAddress": true,      "instanceId": "agent-service-container:8010"    }  }

  PS:更多配置属性的说明,请参考:http://steeltoe.io/docs/steeltoe-discovery/

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

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

3.4 加入服务消费示例代码

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

  (1)ClientService.cs

    public class ClientService : IClientService    {        private ILogger<ClientService> _logger;        private readonly HttpClient _httpClient;        public ClientService(HttpClient httpClient, ILoggerFactory logFactory = null)        {            _httpClient = httpClient;            _logger = logFactory?.CreateLogger<ClientService>();        }        public async Task<string> GetClientName(int clientId)        {            var result = await _httpClient.GetStringAsync(clientId.ToString());            _logger?.LogInformation($"GetClientName - ClientId:{clientId}");            return result;        }    }

  (2)Startup.cs => 为了正确使用HttpClientFactory,需要在启动类中添加一点配置,如下标粗显示。

    public class Startup    {        public Startup(IConfiguration configuration)        {            Configuration = configuration;        }        public IConfiguration Configuration { get; }        // This method gets called by the runtime. Use this method to add services to the container.        public void ConfigureServices(IServiceCollection services)        {            services.AddSingleton<IClientService, ClientService>();            // Add Steeltoe Discovery Client service            services.AddDiscoveryClient(Configuration);            // Add Steeltoe handler to container            services.AddTransient<DiscoveryHttpMessageHandler>();            // Configure a HttpClient            services.AddHttpClient("client-api-values", c =>            {                c.BaseAddress = new Uri(Configuration["Services:Client-Service:Url"]);            })            .AddHttpMessageHandler<DiscoveryHttpMessageHandler>()            .AddTypedClient<IClientService, ClientService>();            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();        }    }

  这里在注入HttpClient时,AddTypedClient<IClientService, ClientService>() 表明注入的这个HttpClient是给这个类型用的。而AddHttpMessageHandler<DiscoveryHttpMessageHandler>() 则表明使用这个HttpClient的时候,会使用这个Handler (DiscoveryHttpMessageHandler)。

  另外,这里的Uri来自appSettings.json配置文件中:

  "Services": {    "Client-Service": {      "Url": "http://client-service/api/values/"    }  }

  这里摘抄一段老九大大(老九大大对HttpClient有着比较深入的了解,一直在维护WebApiClient项目)的文章里面的原话:“HttpClientFactory用于提供HttpClient的创建和生命周期自动管理,完美解决到底选择单例还是每个请求创建和释放HttpClient这个左右难为的问题。所以在asp.net core项目开发中,请别再写手动new HttpClient了,所有HttpClient的实例,都要由HttpClientFactory来创建,所有的外部HttpMessageHandler,也应该配置到HttpClientFactory,让它与HttpClient关联起来。”

  关于更多的如何使用HttpClientFactory在.NET Core 2.1下的使用姿势,请参考这一篇:《3 ways to use HTTPClientFactory in ASP.NET Core 2.1》。

  此外,最近看到了老九大大针对SteeltoeOSS.DiscoveryClient进行了扩展,我们可以在这种架构(ASP.NET Core + Spring Cloud)下使用WebApiClient了,它可以让我们像使用Feign一样实现声明式的REST调用,提高编码效率。

PM> Install-Package WebApiClient.Extensions.DiscoveryClient

  关于如何使用这个WebApiClient的扩展WebApiClient.Extensions.DiscoveryClient,可以参考老九大大的这一篇《WebApiClient的SteeltoeOSS.Discovery扩展》。

  而关于WebApiClient的使用,我也有写一篇短文《.NET Core微服务之服务间的调用(REST and RPC)》。

四、快速验证性测试

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

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图3

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

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

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图4

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

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

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图5

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

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

  第一次调用:

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图6

  第二或第三次调用:

  .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现插图7

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

五、小结

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

示例代码

  点击这里 => https://github.com/EdisonChou/Microservice.PoC.Steeltoe

参考资料

Steeltoe官方文档:《Steeltoe Doc

Steeltoe官方示例:https://github.com/SteeltoeOSS/Samples

蟋蟀,《.NET Core 微服务架构 Steeltoe的使用

nerocloud,《Spring Cloud 和 .NET Core 实现微服务架构

龙应辉,《Spring Cloud + .NET Core 搭建微服务架构

黄文清,《HttpClientFactory与Steeltoe结合来完成服务发现

老九,《WebApiClient的SteeltoeOSS.Discovery扩展》=> 好文,推荐阅读

 

文章转载于:https://www.cnblogs.com/edisonchou/p/dotnet_core_microservice_integrate_with_springcloud_eureka.html

原著是一个有趣的人,若有侵权,请通知删除

未经允许不得转载:起风网 » .NET Core微服务之基于Steeltoe使用Eureka实现服务注册与发现
分享到: 生成海报

评论 抢沙发

评论前必须登录!

立即登录