±à¼ÍƼö: |
±¾ÎÄÀ´×ÔÓÚcnblogs
£¬½éÉÜÁËSpring Cloud Eureka ×¢²á·þÎñ¼°µ÷Óã¬Spring Cloud
Hystrix ¶Ï·Æ÷£¬Spring Cloud Hystrix Ö¸±ê¼à¿Ø£¬Spring
Cloud Config ÅäÖÃÖÐÐÄ¡£ |
|
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 ʵÏÖµÄÒ»¸ö·þÎñ£¬ÏÂÃæÎÒÃDzâÊÔFORTUNE-SERVICEÈçºÎµ÷ÓÃEUREKA-CLIENT¡£
´´½¨Ò»¸öIEurekaClientService½Ó¿Ú£º
public interface IEurekaClientService
{
Task <string> 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 <DiscoveryHttp
ClientHandler> ());
_ 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 <FortunesController> _logger;
public FortunesController (IEureka ClientService
eureka ClientService , ILogger <FortunesController>
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] % |
¿ÉÒÔ¿´µ½£¬µ÷ÓÃÊdzɹ¦µÄ£¬Êµ¼Êµ÷ÓõÄÊÇEUREKA-CLIENT·þÎñµÄ½Ó¿Ú£¬»ñÈ¡µÄÊÇ Eureka
×¢²áÖÐÐÄ£¬ËùÓеÄ×¢²á·þÎñÐÅÏ¢¡£
ASP.NET 4.x °æ±¾µÄʵÏÖ£¬ºÍÉÏÃæµÄÀàËÆ£¬Õâ±ß¾Í²»ÐðÊöÁË£¬¿ÉÒԲ鿴ÏîÄ¿´úÂ룺https:
//github.com /yuezhongxin /Steeltoe.Samples /tree/
master /Discovery- CircuitBreaker /AspDotNet4
2. Spring Cloud Hystrix ¶Ï·Æ÷
ÏîÄ¿´úÂ룺https: //github.com /yuezhongxin
/Steeltoe .Samples /tree /master /Configuration /AspDotNetCore
Spring Cloud Hystrix µÄʵÏÖ£¬ÐèÒªÎÒÃǶÔÉÏÃæµÄÏîÄ¿½øÐиÄÔìÏ¡£
IEurekaClientService Ôö¼ÓÒ»¸öGetServicesWithHystrix
½Ó¿Ú£º
public interface
IEurekaClientService
{
Task<string> GetServices();
Task<string> GetServicesWithHystrix();
} |
È»ºó¶ÔÆä½øÐÐʵÏÖ£º
public class
EurekaClientService : HystrixCommand <string>,
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
3. 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£º
<ItemGroup
Condition= "'$(BUILD)' == 'LOCAL'" >
<PackageReference Include = "Steeltoe
.CircuitBreaker .Hystrix .MetricsStreamCore "
Version = "2.0.0" />
<PackageReference Include = "RabbitMQ
.Client " Version = "5.0.1" /> </ItemGroup>
<ItemGroup Condition ="'$(BUILD)' == ''">
<PackageReference Include = "Steeltoe
.CircuitBreaker . Hystrix .MetricsEventsCore"
Version = "2.0.0" />
<PackageReference Include = "System .Threading
.ThreadPool " Version = "4.3.0"
/>
</ItemGroup> |
È»ºóÖØÆôÏîÄ¿£¬È»ºóä¯ÀÀÆ÷´ò¿ª£ºhttp: //192.168.1.3:5000/
hystrix/ hystrix.stream

»á¿´µ½²»¶ÏʵʱˢÐ嵀 Hystrix Ö¸±ê¼à¿ØÊý¾ÝÁË£¬µ«ÏÔʾ²¢²»ÓѺã¬ÎÒÃÇ»¹ÐèÒªÔÚÒDZíÅÌÖÐÏÔʾ¡£
ä¯ÀÀÆ÷´ò¿ª 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:500 0/api /services
/hystrix £¬ÒÔ±ã²âÊÔ£©£º

ÁíÍ⣬ASP.NET 4.x °æ±¾ÅäÖõϰ£¬·ÃÎÊhttp: //192.168
.1.3: 5000/ hystrix/ hystrix. stream»á±¨ 404 ´íÎó£¬ÔÒòÊÇ
ASP.NET 4.x °æ±¾Ôݲ»Ö§³Ö Cloud Foundry ÒÔÍâµÄƽ̨£¬ÏêÇé²Î¼û£º

4. Spring Cloud Config ÅäÖÃÖÐÐÄ
ÏîÄ¿´úÂ룺https: //github.com /yuezhongxin
/Steeltoe .Samples /tree /master /Configuration /AspDotNetCore
ÐèҪעÒâµÄÊÇ£¬Õâ±ßÖ»²âÊÔ Steeltoe ¶ÁÈ¡ÅäÖÃÖÐÐÄÊý¾Ý£¬ÐèÒªÏÈ¿ª·¢Ò»¸ö Spring Cloud
Config Server ÅäÖÃÖÐÐÄ·þÎñ£¬Õâ±ß¾Í²»ÐðÊöÁË¡£
ÎÒʹÓÃµÄ GitHub ×÷ΪÅäÖÃÖÐÐIJֿ⣬xishuai- config-
dev.ymlÅäÖÃÏêÇ飺
info:
profile: dev
name: xishuai7
password : '{cipher}AQAc+ v42S+FW7H5DiATfee HY887
KLwmeBq +cbXYslcQTtEBNL9a5FKbeF1qDpwrscW tGThPsbb0Q
FUMb03FN6yZBP2ujF29J8Fvm89 igasxA7F67ohJgUkuniqOsMNqm
5juexCTGJvzPkyiny mGFYz55MUqrySZQP bRxoQU9tcfbOv9
AH4 xR /3DPe5krqjo3kk5pK6QWpH37rBgQZLmM7TWooyPiRkuc5Wn
/ 1z6rQIzH5 rCLqv4C8J16 MAwgU1W +KTrHd4t 8hIDAQG9vwkL
9SYAvlz38HMKL 9utu2g4c9jhAJE /H0mePlp+ LDrWSgnC+R+
nyH9 1niaUlwv3wsehP0maYCgEsTJn /3vsNouk5 VCy4IGGZ
bkPubuJM 6hE8RP0r4 =' |
×¢£º¶Ô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 <ConfigServerData>
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 |