在基於.net framework的服務客戶端實現斷路器功能,基本項目創建步驟可以參照我的另一篇發現和調用服務的筆記,地址:http://www.cnblogs.com/troytian/p/8621861.html
在客戶端能實現服務調用基礎上,我們首先需要在appsettings.json中添加Hystrix配置:
1 "hystrix": { 2 "command": { 3 "FortuneService": { 4 "threadPoolKeyOverride": "FortuneServiceTPool" 5 } 6 }, 7 "stream": { 8 "validate_certificates": false 9 } 10 },
在程序入口對斷路器進行注冊:
1 protected void Application_Start() 2 { 3 AreaRegistration.RegisterAllAreas(); 4 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 5 RouteConfig.RegisterRoutes(RouteTable.Routes); 6 BundleConfig.RegisterBundles(BundleTable.Bundles); 7 8 ApplicationConfig.RegisterConfig("development"); 9 10 var builder = new ContainerBuilder(); 11 12 // Add Microsoft Options to container 13 builder.RegisterOptions(); 14 15 // Add Microsoft Logging to container 16 builder.RegisterLogging(ApplicationConfig.Configuration); 17 18 // Add Console logger to container 19 builder.RegisterConsoleLogging(); 20 21 // Register all the controllers with Autofac 22 builder.RegisterControllers(typeof(MvcApplication).Assembly); 23 24 // Register IDiscoveryClient, etc. 25 builder.RegisterDiscoveryClient(ApplicationConfig.Configuration); 26 27 // Register FortuneService Hystrix command 28 builder.RegisterHystrixCommand<IFetchServise, FetchServise>("fetchServise", ApplicationConfig.Configuration); 29 30 // Register Hystrix Metrics/Monitoring stream 31 //builder.RegisterHystrixMetricsStream(ApplicationConfig.Configuration); 32 33 // Create the Autofac container 34 var container = builder.Build(); 35 DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); 36 37 // Get a logger from container 38 var logger = container.Resolve<ILogger<MvcApplication>>(); 39 40 logger.LogInformation("Finished container build, starting background services"); 41 42 // Start the Discovery client background thread 43 container.StartDiscoveryClient(); 44 45 // Start the Hystrix Metrics stream 46 //container.StartHystrixMetricsStream(); 47 48 logger.LogInformation("Finished starting background services"); 49 }
然后需要修改服務調用的方式,添加斷路器fallback回調功能,FetchServise.cs:
1 public class FetchServise : HystrixCommand<string>, IFetchServise 2 { 3 DiscoveryHttpClientHandler _handler; 4 5 private const string RANDOM_FORTUNE_URL = "http://java-service/hi?name=tian"; 6 private ILogger<FetchServise> _logger; 7 8 public FetchServise(IHystrixCommandOptions options, IDiscoveryClient client, ILoggerFactory logFactory = null) : base(options) 9 { 10 _handler = new DiscoveryHttpClientHandler(client, logFactory?.CreateLogger<DiscoveryHttpClientHandler>()); 11 IsFallbackUserDefined = true; 12 _logger = logFactory?.CreateLogger<FetchServise>(); 13 } 14 15 public async Task<string> RandomFortuneAsync() 16 { 17 _logger?.LogInformation("RandomFortuneAsync"); 18 var result = await ExecuteAsync(); 19 _logger?.LogInformation("RandomFortuneAsync returning: " + result); 20 return result; 21 } 22 23 24 protected override async Task<string> RunAsync() 25 { 26 _logger?.LogInformation("RunAsync"); 27 var client = GetClient(); 28 var result = await client.GetStringAsync(RANDOM_FORTUNE_URL); 29 _logger?.LogInformation("RunAsync returning: " + result); 30 return result; 31 } 32 33 protected override async Task<string> RunFallbackAsync() 34 { 35 _logger?.LogInformation("RunFallbackAsync"); 36 return await Task.FromResult("服務斷開,請稍后重試!"); 37 } 38 39 40 private HttpClient GetClient() 41 { 42 var client = new HttpClient(_handler, false); 43 return client; 44 } 45 }
現在我們斷開java-service服務,再啟動程序看看,會不會調用熔斷機制,如果調用了則頁面會顯示我們設定好的提示語【服務斷開,請稍后重試!】:


成功!