在ProductService\appsettings.json加入eureka與service registry相關的設定
"spring": {
"application": {
"name": "ProductService"
}
},
"eureka": {
"client": {
"serviceUrl": "http://localhost:8761/eureka/",
"shouldFetchRegistry": false
},
"instance": {
"port": 1111
// Remove comments to enable SSL requests
// More changes in Program.cs are required if using direct C2C communications
//,"securePortEnabled": true
}
}
然後修改ProductService\Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Steeltoe.Discovery.Client;
namespace ProductService
{
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();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services) {
services.AddDiscoveryClient(Configuration);
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) {
if (env.IsDevelopment()) {
app.UseDeveloperExceptionPage();
}
app.UseStaticFiles();
app.UseMvc();
app.UseDiscoveryClient();
}
}
}
打開Eureka server,可以發現ProductService已經註冊了
跟Day7的練習相比,免除了程式自己在啟動與結束時候通知APIGateway的動作,加入幾行code就享有Eureka提供的監控服務,在架構微服務的時候不用分心去處理這塊。
練習改成用Eureka service discovery的時候APIGateway專案一直無法解析ProductService服務名字,交叉用Fortune-Teller-UI測試是ok的,有點擔心也是不相容core 2.0,找到問題後會再補上。