微服务:整合 Spring Cloud Eureka - .NET Core Mvc Api (C#)

目录

   微服务:整合 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、验证:

  如果启动成功,我们可以看到如下两个界面:

 

 

 

 

 

 

 

 七、测试接口

1、java中demo-service-provider调用.Net 接口:http://localhost:8201/netapi/values

 

 

 2、.Net 调用 Java 服务接口:

.net和Java之间的服务接口相互调用测试成功!

 

 

 

 

  

posted @ 2020-03-25 11:31  颜士  阅读(2036)  评论(0编辑  收藏  举报