为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
C#

一、关于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
@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之间无法正常通信。它的架构哲学是宁可同时保留所有微服务(健康的微服务和不健康的微服务都会保留),也不盲目注销任何健康的微服务。关于自我保护机制,更多内容可以参考:《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”。

  此外,如果我们用的是.NET Core 2.1,那么也可以借助HttpClientFactory来实现(Steeltoe的组件升级到2.1后也开始支持HttpClientFactory),可以参考下面的示例代码。更多有关HttpClientFactory的介绍,可以参考这篇《.NET Core开发日志—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("http://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是一个选择(虽然觉得不是最优,毕竟是寄居)。

示例代码

  点击这里 => 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结合来完成服务发现

 

作者:周旭龙

出处:https://www.cnblogs.com/edisonchou/p/dotnet_core_microservice_integrate_with_springcloud_eureka.html  

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


点击查看更多内容
1人点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消