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本文版權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連結。