您现在的位置是:首页 > 文章详情

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

日期:2019-06-20点击:325

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

一、关于Steeltoe与Spring Cloud

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 @EnableEurekaServer public class EurekaServiceApplication { public static void main(String[] args) { SpringApplication.run(EurekaServiceApplication.class, args); } }

(4)必要的Eureka配置

spring: application: name: eureka-server server: port: 8761 eureka: 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中

三、在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": "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来进行目标地址的解析和请求,具体代码如下:

 public class ClientService : IClientService { DiscoveryHttpClientHandler _handler; private const string API_GET_CLIENT_NAME_URL = "http://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”。

四、快速验证性测试

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是一个选择(虽然觉得不是最优,毕竟是寄居)。

示例代码

点击这里 => 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 搭建微服务架构

作者:周旭龙

出处:http://edisonchou.cnblogs.com

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。

原文链接:https://yq.aliyun.com/articles/706180
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章