Eureka NetCore 服务注册与发现

1 创建springboot eureka项目。

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>2.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <version>2.7.8</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
            <version>3.1.4</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.9.1</version>
        </dependency>

    </dependencies>
@SpringBootApplication
@EnableEurekaServer
public class EurekaServiceApplication {
    public static void main(String[] args) {
        SpringApplication.run(EurekaServiceApplication.class, args);
    }
}
spring.profiles.active=dev
spring.application.name=eureka-server

server.port=8765

eureka.environment=dev
eureka.server.enable-self-preservation=false
eureka.server.eviction-interval-timer-in-ms=5000
eureka.instance.hostname=localhost
eureka.client.register-with-eureka=false
eureka.client.fetch-registry=false

启动项目,地址栏输入 http://172.17.17.53:8765/  eureka成功启动 

 

 

 2 netcore3.1创建一个api项目,用于提供XXX服务

nuget项目引用 Steeltoe.Discovery.Eureka(我用的版本是3.2.3)

<PackageReference Include="Steeltoe.Discovery.Eureka" Version="3.2.3" />

appsettings.json配置文件添加:

  "Urls": "http://*:20000",
  "spring": {
    "application": {
      "name": "coreApi"
    }
  },
  "eureka": {
    "client": {
      "serviceUrl": "http://localhost:8765/eureka/",
      "shouldFetchRegistry": true, // registering as a service
      "shouldRegisterWithEureka": true, // discovering services
      "ValidateCertificates": false,
      "RegistryFetchIntervalSeconds": 5,
      //"EurekaServerRetryCount": 3,
      "CacheTTL": 5
    },
    "instance": {
      //"port": 20000,
      "preferIpAddress": true
    }
  }

添加配置:

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDiscoveryClient(Configuration);
            services.addController();

        }

添加被服务提供接口:api/usr/getUsrDto,下面是controller  action代码

        /// <summary>
        /// 查站点根目录、应用名、环境名
        /// </summary> 
        [HttpGet]
        public UsrDto getUsrDto()
        {
            var header = contextAccess.HttpContext.Request.Headers;
            return new UsrDto()
            {
                Age = 34,
                CreTime = DateTime.Now,
                Id = $"BaseDirectory={AppContext.BaseDirectory},ApplicationName={env.ApplicationName},EnvironmentName={env.EnvironmentName}",
                LoginAccount = configuration.GetSection("Urls").Value,
                Score = 9823.123456m
            };
        }

        /// <summary>
        /// action过滤器打印post参数
        /// </summary>  
        [HttpPost]
        public async Task< string> addUsr(UsrDto usr, string age)
        {
            await Task.Delay(3 * 1000);
            return "ok";
        }

启动项目,再刷新eureka 界面:

 

 

 发现我们写的服务已经注册进来 :coreApi

3 我们再用netcore建立一个此服务的消费(调用)项目,Steeltoe.Discovery.Eureka同样nuget引用,services.AddDiscoveryClient(Configuration);也相同。配置也基本相同:

  "Urls": "http://*:20001",
  "spring": {
    "application": {
      "name": "coreApiClient"
    }
  },
  "eureka": {
    "client": {
      "serviceUrl": "http://localhost:8765/eureka/",
      "shouldFetchRegistry": true, // registering as a service
      "shouldRegisterWithEureka": true, // discovering services
      "ValidateCertificates": false,
      "RegistryFetchIntervalSeconds": 5,
      //"EurekaServerRetryCount": 3,
      "CacheTTL": 5
    },
    "instance": {
      //"port": 20001,
      "preferIpAddress": true
    }
  }

启动项目,再刷新eureka:

 

 发现消费服务也注册进来:COREAPICLIENT

我们再写个“消费”服务,来调用COREAPI 提供的服务接口:

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Steeltoe.Common.Http;
using System;
using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;

namespace CoreApiClient.Controllers {
    [ApiController]
    [Route("[controller]/[action]")]
    public class WeatherController : ControllerBase {

        private readonly ILogger<WeatherController> _logger;

        Steeltoe.Discovery.IDiscoveryClient discoveryClient; 
        Steeltoe.Common.Discovery.DiscoveryHttpClientHandler httpClientHandler;
        System.Net.Http.HttpClient httpClient;
        string getUsrUrl = "http://coreapi/api/usr/getUsrDto";
        string addUsrUrl = "http://coreapi/api/usr/addUsr?age=12";

        public WeatherController(ILogger<WeatherController> logger, Steeltoe.Discovery.IDiscoveryClient client) {
            _logger = logger;
            discoveryClient = client;
            httpClientHandler = new Steeltoe.Common.Discovery.DiscoveryHttpClientHandler(client); 
            httpClient = HttpClientHelper.GetHttpClient(httpClientHandler);
            httpClient.Timeout = TimeSpan.FromSeconds(10);
            httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", "123456");
        }

        [HttpGet]
        public async Task< string> getUsrDtoProxy() { 
            var resp = await httpClient.GetAsync(getUsrUrl);
            var content = await resp.Content.ReadAsStringAsync();
            return content;
        }

        [HttpGet]
        public async Task<string> addUsrProxy() { 
            var resp = await httpClient.PostAsync(addUsrUrl, JsonContent.Create(new { Id = "hc", Age = 34, CreTime = DateTime.Now, Score = 23.34 }));
            var content = await resp.Content.ReadAsStringAsync();
            return content;
        }
    }
}

 

4 重新启动COREAPICLIENT项目,让上面写的代码生效,我们用postman试试 接口getUsrDtoProxy

http://localhost:20001/weather/getUsrDtoProxy

 

 5 结束,springcloud 提供微服务框架和平台,netcore用具体“业务”提供或消费服务。

 

posted on 2023-03-29 16:47  jonney_wang  阅读(137)  评论(0编辑  收藏  举报

导航