首先,寫一個簡單的可被調用的服務注冊到服務中心,我們這命名為java-service,用的是IDEA創建一個spring boot項目,選擇spring client類型。
修改application.properties,配置服務中心地址和服務端口號:
spring.application.name=java-service server.port=3222 eureka.client.serviceUrl.defaultZone=http://localhost:8761/eureka/
修改pom.xml,加入架包引用:
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-eureka</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
修改主程序入口DemoclientApplication.java:
package com.ty.democlient; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @SpringBootApplication @EnableEurekaClient @RestController public class DemoclientApplication { public static void main(String[] args) { SpringApplication.run(DemoclientApplication.class, args); } @Value("${server.port}") String port; @RequestMapping("/hi") public String home(@RequestParam String name) { return "hi "+name+",i am from port:" +port; } }
把服務跑起來之后,我們看到在服務中心已經能看見這個服務了:


打開瀏覽器輸入
http://localhost:3222/hi?name=demo,可以看到服務正常返回:


現在我們的目標是在另外一個.NET MVC項目里通過服務名就能正常調用到這個服務,來看看怎么做:
新建一個基於.Net Framework 4.5 的MVC項目,首先根目錄還是要有一個appsettings.json的文件作為服務配置文件:
{ "spring": { "application": { "name": "demo_netfetch" } }, "eureka": { "client": { "serviceUrl": "http://localhost:8761/eureka/", "shouldFetchRegistry": true, "shouldRegisterWithEureka": true, "validate_certificates": false }, "instance": { "port": 3001 // Remove comments to enable SSL requests // More changes in Program.cs are required if using direct C2C communications //,"securePortEnabled": true } }, "Logging": { "IncludeScopes": false, "LogLevel": { "Default": "Debug", "Pivotal": "Debug", "Steeltoe": "Debug" } } }
shouldFetchRegistry設置為true代表這是一個服務發現客戶端
然后在項目目錄下創建Service調用的類,配置具體調用的服務名,內容輸出方式等:
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using System.Web; using Microsoft.Extensions.Logging; using Steeltoe.Common.Discovery; namespace DemoNetFetchClient.Services { public class FetchServise : IFetchServise { DiscoveryHttpClientHandler _handler; private const string RANDOM_FORTUNE_URL = "http://java-service/hi?name=tian";//服務中心已注冊的服務地址 private ILogger<FetchServise> _logger; public FetchServise(IDiscoveryClient client, ILoggerFactory logFactory = null) { _handler = new DiscoveryHttpClientHandler(client); _logger = logFactory?.CreateLogger<FetchServise>(); } public async Task<string> RandomFortuneAsync() { _logger?.LogInformation("RandomFortuneAsync"); var client = GetClient(); return await client.GetStringAsync(RANDOM_FORTUNE_URL); } private HttpClient GetClient() { var client = new HttpClient(_handler, false); return client; } } }
注意這里需要引用擴展包:Steeltoe.Common.Discovery,從NuGet里加載就可以,注意版本,要選擇NET專用的,而不是Core用的。
修改HomeController.cs,異步請求調用內部服務:
public class HomeController : Controller { IFetchServise _fortunes; ILogger<HomeController> _logger; public HomeController(IFetchServise fortunes, ILoggerFactory logFactory = null) { _fortunes = fortunes; _logger = logFactory?.CreateLogger<HomeController>(); } public async System.Threading.Tasks.Task<ActionResult> Index() { ViewBag.Message = await _fortunes.RandomFortuneAsync(); return View(); } }
修改Global.asax,注冊服務客戶端:
這里要注意,如果項目是webapi程序,需要按Autofac集成webAPI的配置,具體請參考我的另一篇筆記:C# Autofac集成之Framework WebAPI
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ApplicationConfig.RegisterConfig("development"); var builder = new ContainerBuilder(); // Add Microsoft Options to container builder.RegisterOptions(); // Add Microsoft Logging to container builder.RegisterLogging(ApplicationConfig.Configuration); // Add Console logger to container builder.RegisterConsoleLogging(); // Register all the controllers with Autofac builder.RegisterControllers(typeof(MvcApplication).Assembly); // Register IDiscoveryClient, etc. builder.RegisterDiscoveryClient(ApplicationConfig.Configuration); // Register FortuneService builder.RegisterType<FetchServise>().As<IFetchServise>().SingleInstance(); // Create the Autofac container var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); // Get a logger from container var logger = container.Resolve<ILogger<MvcApplication>>(); logger.LogInformation("Finished container build, starting background services"); // Start the Discovery client background thread container.StartDiscoveryClient(); logger.LogInformation("Finished starting background services"); }
ok!done!程序跑起來效果,成功調用到服務中心內部服務java-service:
