.NET Core 微服务架构 Steeltoe 使用(基于 Spring Cloud)

https://www.cnblogs.com/xishuai/p/steeltoe-and-spring-cloud-eureka-config-hystrix.html

阅读目录:

  1. Spring Cloud Eureka 注册服务及调用
  2. Spring Cloud Hystrix 断路器
  3. Spring Cloud Hystrix 指标监控
  4. Spring Cloud Config 配置中心

    现在主流的开发平台是微服务架构,在众多的微服务开源项目中,Spring Cloud 非常具有代表性,但实现平台是基于 Java,那在 .NET Core 平台下,如何兼容实现 Spring Cloud 呢?答案就是 Steeltoe,或者你也可以自行实现,因为 Spring Cloud 各组件基本都是基于 REST HTTP 接口实现,你可以使用任何语言实现兼容。

关于 Steeltoe 的官方介绍:

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.

这边就不翻译了,需要注意的几点:

Netflix Eureka:服务注册中心,实现服务注册,以及服务发现调用。

Hystrix:断路器,实现熔断处理。

Spring Cloud Config Server:分布式配置中心,主要是读取配置中心的信息。

Cloud Foundry:开源 PaaS 云平台,Steeltoe 基本都运行在此平台上,运行在其他平台兼容不好。

另外,Steeltoe 不仅支持 .NET Core,还支持 .NET Framework(具体 ASP.NET 4.x 版本)。

  1. Spring Cloud Eureka 注册服务及调用

    项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Discovery-CircuitBreaker/AspDotNetCore

首先,需要部署一个或多个 Spring Cloud Eureka 服务注册中心,可以使用 Spring Boot 很方便进行实现,这边就不说了。

创建一个 APS.NET Core 应用程序(2.0 版本),然后 Nuget 安装程序包:

install-package Pivotal.Discovery.ClientCore

在appsettings.json配置文件中,增加下面配置:

{

"spring": {

"application": {

"name": "fortune-service"

}

},

"eureka": {

"client": {

"serviceUrl": "http://192.168.1.32:8100/eureka/",

"shouldFetchRegistry": true, //Enable or disable registering as a service

"shouldRegisterWithEureka": true, //Enable or disable discovering services

"validate_certificates": false

},

"instance": {

//"hostName": "localhost",

"port": 5000

}

}

}

这样我们启动 APS.NET Core 应用程序,就会将fortune-service服务注册到 Eureka 中了。

EUREKA-CLIENT是用 Spring Boot 实现的一个服务,下面我们测试FORTUNE-SERVICE如何调用EUREKA-CLIENT。

创建一个IEurekaClientService接口:

public interface IEurekaClientService

{

Task GetServices();

}

然后再创建IEurekaClientService接口的实现EurekaClientService:

public class EurekaClientService : IEurekaClientService

{

DiscoveryHttpClientHandler _handler;

private const string GET_SERVICES_URL = "http://eureka-client/home";
private ILogger<EurekaClientService> _logger; public EurekaClientService(IDiscoveryClient client, ILoggerFactory logFactory = null)
:base(options)
{
_handler = new DiscoveryHttpClientHandler(client, logFactory?.CreateLogger<DiscoveryHttpClientHandler>());
_logger = logFactory?.CreateLogger<EurekaClientService>();
} 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;
}

}

然后创建一个FortunesController:

[Route("api")]

public class FortunesController : Controller

{

private IEurekaClientService _eurekaClientService;

private ILogger _logger;

public FortunesController(IEurekaClientService eurekaClientService, ILogger logger)

{

_eurekaClientService = eurekaClientService;

_logger = logger;

}

// GET: api/services
[HttpGet("services")]
public async Task<IActionResult> GetServices()
{
_logger?.LogInformation("api/services");
return Ok(await _eurekaClientService.GetServices());
}

}

最后在Startup.cs中,添加如下配置:

public class Startup

{

public Startup(IConfiguration configuration)

{

Configuration = configuration;

}

public IConfiguration Configuration { get; private set; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
// 加载服务注册配置
services.AddDiscoveryClient(Configuration); // Add framework services.
services.AddMvc();
} // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
{
app.UseStaticFiles(); app.UseMvc(); // 启动服务注册
app.UseDiscoveryClient();
}

}

然后重新启动服务,执行命令:

$ curl http://192.168.1.3:5000/api/services

Services(get all by DiscoveryClient): [eureka-client, fortune-service]%

可以看到,调用是成功的,实际调用的是EUREKA-CLIENT服务的接口,获取的是 Eureka 注册中心,所有的注册服务信息。

ASP.NET 4.x 版本的实现,和上面的类似,这边就不叙述了,可以查看项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Discovery-CircuitBreaker/AspDotNet4

  1. Spring Cloud Hystrix 断路器

    项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Configuration/AspDotNetCore

Spring Cloud Hystrix 的实现,需要我们对上面的项目进行改造下。

IEurekaClientService增加一个GetServicesWithHystrix接口:

public interface IEurekaClientService

{

Task GetServices();

Task<string> GetServicesWithHystrix();

}

然后对其进行实现:

public class EurekaClientService : HystrixCommand, IEurekaClientService

{

DiscoveryHttpClientHandler _handler;

private const string GET_SERVICES_URL = "http://eureka-client/home";
private ILogger<EurekaClientService> _logger; public EurekaClientService(IHystrixCommandOptions options, IDiscoveryClient client, ILoggerFactory logFactory = null)
:base(options)
{
_handler = new DiscoveryHttpClientHandler(client, logFactory?.CreateLogger<DiscoveryHttpClientHandler>());
IsFallbackUserDefined = true;
_logger = logFactory?.CreateLogger<EurekaClientService>();
} public async Task<string> GetServices()
{
_logger?.LogInformation("GetServices");
var client = GetClient();
return await client.GetStringAsync(GET_SERVICES_URL); } public async Task<string> GetServicesWithHystrix()
{
_logger?.LogInformation("GetServices");
var result = await ExecuteAsync();
_logger?.LogInformation("GetServices returning: " + result);
return result;
} protected override async Task<string> RunAsync()
{
_logger?.LogInformation("RunAsync");
var client = GetClient();
var result = await client.GetStringAsync(GET_SERVICES_URL);
_logger?.LogInformation("RunAsync returning: " + result);
return result;
} protected override async Task<string> RunFallbackAsync()
{
_logger?.LogInformation("RunFallbackAsync");
return await Task.FromResult("This is a error(服务断开,稍后重试)!");
} private HttpClient GetClient()
{
var client = new HttpClient(_handler, false);
return client;
}

}

然后还需要在Startup.cs中添加注入:

public void ConfigureServices(IServiceCollection services)

{

// Register FortuneService Hystrix command

services.AddHystrixCommand<IEurekaClientService, EurekaClientService>("eureka-client", Configuration);

}

然后重启服务,执行命令:

$ curl http://192.168.1.3:5000/api/services/hystrix

Services(get all by DiscoveryClient): [eureka-client, fortune-service]%

Hystrix 断路器的作用,体现在调用服务出现问题不能访问,这边可以进行熔断处理,我们把eureka-client服务停掉,然后再进行访问测试:

$ curl http://192.168.1.3:5000/api/services/hystrix

This is a error(服务断开,稍后重试)!%

可以看到,Hystrix 起到了作用。

ASP.NET 4.x 版本的实现,和上面的类似,这边就不叙述了,可以查看项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Discovery-CircuitBreaker/AspDotNet4

  1. Spring Cloud Hystrix 指标监控

    项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Discovery-CircuitBreaker/AspDotNetCore

在实际应用中,我们需要对 Hystrix 断路器进行监控,比如熔断请求有多少等等,Spring Cloud 中的实现有 Turbine 进行收集,数据展示的话使用 Hystrix Dashboard。

这边需要我们先创建一个 Hystrix Dashboard 项目,我使用的 Spring Boot 进行实现,这边就不叙述了。

我们需要再对上面的项目进行改造,在Startup.cs中添加配置,以启动 Hystrix 指标监控。

public class Startup

{

public void ConfigureServices(IServiceCollection services)

{

// Add Hystrix metrics stream to enable monitoring

services.AddHystrixMetricsStream(Configuration);

}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IApplicationLifetime lifetime)
{
// Startup Hystrix metrics stream
app.UseHystrixMetricsStream();
}

}

另外,还需要配置下Fortune-Teller-Service.csproj:

然后重启项目,然后浏览器打开:http://192.168.1.3:5000/hystrix/hystrix.stream

会看到不断实时刷新的 Hystrix 指标监控数据了,但显示并不友好,我们还需要在仪表盘中显示。

浏览器打开 Hystrix Dashboard(地址:http://192.168.1.31:8170/hystrix),然后在输入框中输入:http://192.168.1.3:5000/hystrix/hystrix.stream

然后点击 Monitor Stream 按钮,就可以看到 Hystrix 图形化监控了(多次请求http://192.168.1.3:5000/api/services/hystrix,以便测试):

另外,ASP.NET 4.x 版本配置的话,访问http://192.168.1.3:5000/hystrix/hystrix.stream会报 404 错误,原因是 ASP.NET 4.x 版本暂不支持 Cloud Foundry 以外的平台,详情参见:

  1. Spring Cloud Config 配置中心

    项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Configuration/AspDotNetCore

需要注意的是,这边只测试 Steeltoe 读取配置中心数据,需要先开发一个 Spring Cloud Config Server 配置中心服务,这边就不叙述了。

我使用的 GitHub 作为配置中心仓库,xishuai-config-dev.yml配置详情:

info:

profile: dev

name: xishuai7

password: '{cipher}AQAc+v42S+FW7H5DiATfeeHY887KLwmeBq+cbXYslcQTtEBNL9a5FKbeF1qDpwrscWtGThPsbb0QFUMb03FN6yZBP2ujF29J8Fvm89igasxA7F67ohJgUku5ni9qOsMNqm5juexCTGJvzPkyinymGFYz55MUqrySZQPbRxoQU9tcfbOv9AH4xR/3DPe5krqjo3kk5pK6QWpH37rBgQZLmM7TWooyPiRkuc5Wn/1z6rQIzH5rCLqv4C8J16MAwgU1W+KTrHd4t8hIDAQG9vwkL9SYAvlz38HMKL9utu2g4c9jhAJE/H0mePlp+LDrWSgnC+R+nyH91niaUlwv3wsehP0maYCgEsTJn/3vsNouk5VCy4IGGZbkPubuJM6hE8RP0r4='

注:对password进行了加密处理。

创建一个 APS.NET Core 应用程序(2.0 版本),然后 Nuget 安装程序包:

install-package Steeltoe.Extensions.Configuration.ConfigServerCore

在appsettings.json配置文件中,增加下面配置:

{

"spring": {

"application": {

"name": "xishuai-config" //配置文件名称

},

"cloud": {

"config": {

"uri": "http://manager1:8180", //指向配置中心地址

"env": "dev" //配置中心profile

}

}

}

}

然后创建一个ConfigServerData模型:

public class ConfigServerData

{

public Info Info { get; set; }

}

public class Info

{

public string Profile { get; set; }

public string Name { get; set; }

public string Password { get; set; }

}

增加HomeController访问:

public class HomeController : Controller

{

private IOptionsSnapshot IConfigServerData { get; set; }

private IConfigurationRoot Config { get; set; }

public HomeController(IConfigurationRoot config, IOptionsSnapshot<ConfigServerData> configServerData)
{
if (configServerData != null)
IConfigServerData = configServerData; Config = config;
} public IActionResult Error()
{
return View();
} public ConfigServerData ConfigServer()
{
var data = IConfigServerData.Value;
return data;
} public IActionResult Reload()
{
if (Config != null)
{
Config.Reload();
} return View();
}

}

Startup.cs中增加配置:

public class Startup

{

public Startup(IHostingEnvironment env)

{

var builder = new ConfigurationBuilder()

.SetBasePath(env.ContentRootPath)

.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)

.AddEnvironmentVariables()

.AddConfigServer(env);

Configuration = builder.Build();

}

public IConfiguration Configuration { get; set; }

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions(); // Optional: Adds IConfiguration and IConfigurationRoot to service container
services.AddConfiguration(Configuration); // Adds the configuration data POCO configured with data returned from the Spring Cloud Config Server
services.Configure<ConfigServerData>(Configuration);
}

}

启动项目,然后执行命令:

$ curl http://192.168.1.3:5000/home/ConfigServer

{"info":{"profile":"dev","name":"xishuai7","password":"xishuai123"}}

当配置中心数据更新了,可以访问http://192.168.1.3:5000/home/Reload进行刷新配置。

ASP.NET 4.x 版本的实现,和上面的类似,这边就不叙述了,可以查看项目代码:https://github.com/yuezhongxin/Steeltoe.Samples/tree/master/Configuration/AspDotNet4

参考资料:

http://steeltoe.io/

https://github.com/SteeltoeOSS/Samples

Enabling .NET Core Microservices with Steeltoe and Pivotal Cloud Foundry

.net framework 4.5 +steeltoe+ springcloud(二) 实现服务发现与调用功能

作者:田园里的蟋蟀

微服务架构 Steeltoe的更多相关文章

  1. .NET Core 微服务架构 Steeltoe 使用(基于 Spring Cloud)

    阅读目录: 1. Spring Cloud Eureka 注册服务及调用 2. Spring Cloud Hystrix 断路器 3. Spring Cloud Hystrix 指标监控 4. Spr ...

  2. 手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

  3. spring cloud+dotnet core搭建微服务架构:配置中心(四)

    前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...

  4. spring cloud+dotnet core搭建微服务架构:配置中心续(五)

    前言 上一章最后讲了,更新配置以后需要重启客户端才能生效,这在实际的场景中是不可取的.由于目前Steeltoe配置的重载只能由客户端发起,没有实现处理程序侦听服务器更改事件,所以还没办法实现彻底实现这 ...

  5. Spring Cloud 微服务架构学习笔记与示例

    本文示例基于Spring Boot 1.5.x实现,如对Spring Boot不熟悉,可以先学习我的这一篇:<Spring Boot 1.5.x 基础学习示例>.关于微服务基本概念不了解的 ...

  6. spring cloud+.net core搭建微服务架构:服务注册(一)

    背景 公司去年开始使用dotnet core开发项目.公司的总体架构采用的是微服务,那时候由于对微服务的理解并不是太深,加上各种组件的不成熟,只是把项目的各个功能通过业务层面拆分,然后通过nginx代 ...

  7. spring cloud+.net core搭建微服务架构:配置中心续(五)

    前言 上一章最后讲了,更新配置以后需要重启客户端才能生效,这在实际的场景中是不可取的.由于目前Steeltoe配置的重载只能由客户端发起,没有实现处理程序侦听服务器更改事件,所以还没办法实现彻底实现这 ...

  8. spring cloud+.net core搭建微服务架构:配置中心(四)

    前言 我们项目中有很多需要配置的地方,最常见的就是各种服务URL地址,这些地址针对不同的运行环境还不一样,不管和打包还是部署都麻烦,需要非常的小心.一般配置都是存储到配置文件里面,不管多小的配置变动, ...

  9. .NET Core微服务架构学习与实践系列文章索引目录

    一.为啥要总结和收集这个系列? 今年从原来的Team里面被抽出来加入了新的Team,开始做Java微服务的开发工作,接触了Spring Boot, Spring Cloud等技术栈,对微服务这种架构有 ...

随机推荐

  1. (转)HLS协议,html5视频直播一站式扫盲

    本文来自于腾讯bugly开发者社区,原文地址:http://bugly.qq.com/bbs/forum.php?mod=viewthread&tid=1277 视频直播这么火,再不学就 ou ...

  2. stack_1.设计一个有getMin功能的栈

    思路 : 生成两个栈($stack ,$stack_min ),往$stack塞数据($value)的时候 ,比较一下$value和$stack_min最上面的元素的大小,如果$value小,则压入$ ...

  3. EVC入门之二: 在未被加载的DLL中设置断点 (虽然没有遇到这个问题,不过先摘抄下来)

    问题: 这个问题居然也郁闷了我一段时间. 我们假设在EVC里建立了一个project, 里面有SubProject_1(以下简称SB1,嘿嘿), 编译生成一个EXE; SubProject_2(以下简 ...

  4. codeforces 610D D. Vika and Segments(离散化+线段树+扫描线算法)

    题目链接: D. Vika and Segments time limit per test 2 seconds memory limit per test 256 megabytes input s ...

  5. bzoj 3796 Mushroom追妹纸 —— 后缀数组

    题目:https://www.lydsy.com/JudgeOnline/problem.php?id=3796 先把三个串拼在一起,KMP 求 s1 , s2 中每个位置和 s3 的匹配情况: 注意 ...

  6. The Review Plan I-禁位排列和容斥原理

    The Review Plan I Time Limit: 5000ms Case Time Limit: 5000ms Memory Limit: 65536KB   64-bit integer ...

  7. C# 深化基本概念

    关于IDisposable的Dispose方法 .Net中GC会自动回收托管资源, 对于非托管资源应该使用Dispose方法. 在使用Dispose方法时,应注意避免在Dispose内部中继续释放托管 ...

  8. TCP点对点穿透探索--失败

    TCP点对点穿透探索 点对点穿透是穿透什么 点对点穿透,需要实现的是对NAT的穿透.想实现NAT的穿透,当然要先了解NAT到底是什么,以及NAT是用来干什么的.NAT全称Network Address ...

  9. Spring管理Filter和Servlet(在servlet中注入spring容器中的bean)

    在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对 ...

  10. sum(sum(abs(y))) 中 sum(sum())什么意思?

    >> y=[1 3;2 5] y =      1     3      2     5 >> sum(y) ans =      3     8 >> sum(s ...