目錄
微服務:整合 Spring Cloud Eureka - 注冊中心 Eureka Server
微服務:整合 Spring Cloud Eureka - 服務注冊 Eureka Client
微服務:整合 Spring Cloud Eureka - 服務發現 DiscoveryClient
微服務:整合 Spring Cloud Eureka - 服務消費以及Ribbon簡單使用
微服務:整合 Spring Cloud Eureka - 高可用集群
微服務:整合 Spring Cloud Eureka - .NET Core Mvc Api (C#)
微服務:整合 Spring Cloud Eureka - 服務治理機制
微服務:整合 Spring Cloud Eureka - 服務事件監聽
微服務:整合 Spring Cloud Eureka - 高級屬性Region、Zone
微服務:整合 Spring Cloud Eureka - Rest接口文檔
微服務:整合 Spring Cloud Eureka - Security 安全保護
一、前言
記得在幾年前,在做一個.Net 項目,需要一個服務注冊中心,那時候還傻乎乎的自己手寫了一個注冊中心。雖然簡陋,但是對應的心跳以及負載均衡還是有的。現在隨着技術日新月異,也要與時俱進。今天和大家分享一個 .NET Core Mvc Api 如何與Spring Cloud Eureka集成,做服務注冊與發現,並和java項目相互調用。
二、搭建Spring Cloud Eureka 注冊中心
參考 《微服務:整合 Spring Cloud Eureka - 注冊中心 Eureka Server 》
三、搭建Spring Cloud 服務提供者
參考《微服務:整合 Spring cloud Eureka - 服務注冊 Eureka Client》
四、搭建Spring Cloud 服務消費者
參考《微服務:整合 Spring cloud Eureka - 服務消費以及Ribbon簡單使用 》
修改 demo-service-consumer中 ConsumerHelloController.java中的代碼:
package com.demo.service.consumer.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @RestController public class ConsumerHelloController { @Autowired RestTemplate restTemplate; @RequestMapping("/hello/{name}") public String hello(@PathVariable("name")String name){ String ribbon_url = "http://demo-service-provider/hello/sayhello/" + name; String msg =restTemplate.getForEntity(ribbon_url,String.class).getBody(); System.out.println("服務返回信息為:" + msg); return "服務返回信息為:" + msg; } @RequestMapping("/netapi/values") public String netapi(){ String ribbon_url = "http://net-core-app4/api/values"; // .net 服務地址 String msg =restTemplate.getForEntity(ribbon_url,String.class).getBody(); System.out.println("服務返回信息為:" + msg); return "服務返回信息為:" + msg; } }
五、搭建Asp.Net Core Mvc Api 項目
1、C# 項目結構
2、IJavaProviderService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WebApplication4.Service { public interface IJavaProviderService { Task<string> GetValueAsync(); } }
3、JavaProviderService.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; namespace WebApplication4.Service { public class JavaProviderService : IJavaProviderService { private readonly HttpClient _httpClient; public JavaProviderService(HttpClient httpClient) { _httpClient = httpClient; } public async Task<string> GetValueAsync() { var result = await _httpClient.GetStringAsync("hello/sayhello/java"); return result; } } }
4、ValuesController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using WebApplication4.Service; namespace WebApplication4.Controllers { [Route("api/[controller]")] [ApiController] public class ValuesController : ControllerBase { private readonly IJavaProviderService _javaProviderService; public ValuesController(IJavaProviderService javaProviderService) { _javaProviderService = javaProviderService; } // GET api/values // 供Java項目調用 [HttpGet] public ActionResult<IEnumerable<string>> Get() { return new string[] { "value1", "value2" }; } // GET api/values // .Net 通過Eureka調用java服務 [Route("java")] [HttpGet] public async Task<string> Getsss() { return $"client { await _javaProviderService.GetValueAsync()}"; } } }
5、Program.cs
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace WebApplication4 { public class Program { public static void Main(string[] args) { CreateWebHostBuilder(args).Build().Run(); } public static IWebHostBuilder CreateWebHostBuilder(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .UseUrls("http://*:5001"); } }
6、Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Steeltoe.Common.Http.Discovery; using Steeltoe.Discovery.Client; using WebApplication4.Service; namespace WebApplication4 { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } 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().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddTransient<DiscoveryHttpMessageHandler>(); // 指定 BaseService 內使用的 HttpClient 在發送請求前通過 DiscoveryHttpMessageHandler 解析 BaseAddress 為已注冊服務的 host:port services.AddHttpClient("java-provider-service", c => { c.BaseAddress = new Uri(Configuration["services:java-provider-service:url"]); }) .AddHttpMessageHandler<DiscoveryHttpMessageHandler>() .AddTypedClient<IJavaProviderService, JavaProviderService>(); } // 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(); app.UseDiscoveryClient(); } } }
7、appsettings.json
{ "Logging": { "LogLevel": { "Default": "Warning" } }, "spring": { "application": { "name": "net-core-app4" } }, "eureka": { "client": { "serviceUrl": "http://localhost:8001/register/eureka/", "shouldFetchRegistry": true, "shouldRegisterWithEureka": true, "validate_certificates": false }, "instance": { "hostname": "localhost", "port": 5001, "instanceId": "localhost:net-core-app4:5001" } }, "services": { "java-provider-service": { "url": "http://demo-service-provider/" } }, "AllowedHosts": "*" }
8、launchSettings.json
{ "$schema": "http://json.schemastore.org/launchsettings.json", "iisSettings": { "windowsAuthentication": false, "anonymousAuthentication": true, "iisExpress": { "applicationUrl": "http://localhost:5001", "sslPort": 0 } }, "profiles": { "IIS Express": { "commandName": "IISExpress", "launchBrowser": true, "launchUrl": "api/values", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } }, "WebApplication4": { "commandName": "Project", "launchBrowser": true, "launchUrl": "api/values", "applicationUrl": "http://localhost:5000", "environmentVariables": { "ASPNETCORE_ENVIRONMENT": "Development" } } } }
六、啟動項目
1、啟動Eureka 注冊中心
2、啟動demo-service-provider服務提供者,可啟動兩個實例
3、啟動demo-service-consumer服務消費者
4、啟動.NET 項目WebApplication4
5、驗證:
如果啟動成功,我們可以看到如下兩個界面:
- Eureka 注冊中心:http://localhost:8001/register/
- .net core 項目 http://localhost:5001/api/values
七、測試接口
1、java中demo-service-provider調用.Net 接口:http://localhost:8201/netapi/values
2、.Net 調用 Java 服務接口:
.net和Java之間的服務接口相互調用測試成功!