背景

对于公司内部的 API 接口,在引入注册中心之后,免不了会用上服务发现这个东西。

现在比较流行的接口调用方式应该是基于声明式接口的调用,它使得开发变得更加简化和快捷。

.NET 在声明式接口调用这一块,有 WebApiClient 和 Refit 可以选择。

前段时间有个群友问老黄,有没有 WebApiClient 和 Nacos 集成的例子。

找了一圈,也确实没有发现,所以只好自己动手了。

本文就以 WebApiClient 为例,简单介绍一下它和 Nacos 的服务发现结合使用。

API接口

基于 .NET 6 创建一个 minimal api。

using Nacos.AspNetCore.V2;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddNacosAspNet(x =>
{
x.ServerAddresses = new List<string> { "http://localhost:8848/" };
x.Namespace = "cs"; // 服务名这一块统一用小写!!
x.ServiceName = "sample";
x.GroupName = "Some_Group";
x.ClusterName = "DC_1";
x.Weight = 100;
x.Secure = false;
}); var app = builder.Build();
.
app.MapGet("/api/get", () =>
{
return Results.Ok("from .net6 minimal API");
}); app.Run("http://*:9991");

这个应用是 provider,在启动的时候,会向 Nacos 进行注册,可以被其他应用发现并调用。

声明式接口调用

这里同样是创建一个 .NET 6 的 WEB API 项目来演示,这里需要引入一个 nuget 包。

<ItemGroup>
<PackageReference Include="WebApiClientCore.Extensions.Nacos" Version="0.1.0" />
</ItemGroup>

首先来声明一下这个接口。

// [HttpHost("http://192.168.100.100:9991")]
[HttpHost("http://sample")]
public interface ISampleApi : IHttpApi
{
[HttpGet("/api/get")]
Task<string> GetAsync();
}

这里其实要注意的就是 HttpHost 这个特性,正常情况下,配置的是具体的域名或者是IP地址。

我们如果需要通过 nacos 去发现这个接口对应的真实地址的话,只需要配置它的服务名就好了。

后面是要进行接口的注册,让这个 ISampleApi 可以动起来。

var builder = WebApplication.CreateBuilder(args);

// 添加 nacos 服务发现模块
// 这里没有把当前服务注册到 nacos,按需调整
builder.Services.AddNacosV2Naming(x =>
{
x.ServerAddresses = new List<string> { "http://localhost:8848/" };
x.Namespace = "cs";
}); // 接口注册,启用 nacos 的服务发现功能
// 注意分组和集群的配置
// builder.Services.AddNacosDiscoveryTypedClient<ISampleApi>("Some_Group", "DC_1");
builder.Services.AddNacosDiscoveryTypedClient<ISampleApi>(x =>
{
// HttpApiOptions
x.UseLogging = true;
}, "Some_Group", "DC_1"); var app = builder.Build(); app.MapGet("/", async (ISampleApi api) =>
{
var res = await api.GetAsync();
return $"client ===== {res}" ;
}); app.Run("http://*:9992");

运行并访问 localhost:9992 就可以看到效果了

从上面的日志看,它请求的是 http://sample/api/get,实际上是 http://192.168.100.220:9991/api/get,刚好这个地址是注册到 nacos 上面的,也就是服务发现是生效了。

info: System.Net.Http.HttpClient.ISampleApi.LogicalHandler[100]
Start processing HTTP request GET http://sample/api/get
info: System.Net.Http.HttpClient.ISampleApi.ClientHandler[100]
Sending HTTP request GET http://sample/api/get
info: Microsoft.AspNetCore.Hosting.Diagnostics[1]
Request starting HTTP/1.1 GET http://192.168.100.220:9991/api/get - -
info: Microsoft.AspNetCore.Routing.EndpointMiddleware[0]
Executing endpoint 'HTTP: GET /api/get'

下面来看看 WebApiClientCore.Extensions.Nacos 这个包做了什么。

简单剖析

本质上是加了一个 HttpClientHandler,这个 handler 依赖于 sdk 提供的 INacosNamingService

public static IHttpClientBuilder AddNacosDiscoveryTypedClient<TInterface>(
this IServiceCollection services,
Action<HttpApiOptions, IServiceProvider> configOptions,
string group = "DEFAULT_GROUP",
string cluster = "DEFAULT")
where TInterface : class, IHttpApi
{
NacosExtensions.Common.Guard.NotNull(configOptions, nameof(configOptions)); return services.AddHttpApi<TInterface>(configOptions)
.ConfigurePrimaryHttpMessageHandler(provider =>
{
var svc = provider.GetRequiredService<INacosNamingService>();
var loggerFactory = provider.GetService<ILoggerFactory>(); if (svc == null)
{
throw new InvalidOperationException(
"Can not find out INacosNamingService, please register at first");
} return new NacosExtensions.Common.NacosDiscoveryHttpClientHandler(svc, group, cluster, loggerFactory);
});
}

在 handler 里面重写了 SendAsync 方法,替换了 HttpRequestMessage 的 RequestUri,也就是把服务名换成了真正的服务地址。

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
var current = request.RequestUri;
try
{
request.RequestUri = await LookupServiceAsync(current).ConfigureAwait(false);
var res = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);
return res;
}
catch (Exception e)
{
_logger?.LogDebug(e, "Exception during SendAsync()");
throw;
}
finally
{
// Should we reset the request uri to current here?
// request.RequestUri = current;
}
}

具体查找替换逻辑如下:

internal async Task<Uri> LookupServiceAsync(Uri request)
{
// Call SelectOneHealthyInstance with subscribe
// And the host of Uri will always be lowercase, it means that the services name must be lowercase!!!!
var instance = await _namingService
.SelectOneHealthyInstance(request.Host, _groupName, new List<string> { _cluster }, true).ConfigureAwait(false); if (instance != null)
{
var host = $"{instance.Ip}:{instance.Port}"; // conventions here
// if the metadata contains the secure item, will use https!!!!
var baseUrl = instance.Metadata.TryGetValue(Secure, out _)
? $"{HTTPS}{host}"
: $"{HTTP}{host}"; var uriBase = new Uri(baseUrl);
return new Uri(uriBase, request.PathAndQuery);
} return request;
}

这里是先查询一个健康的实例,如果存在,才会进行组装,这里有一个关于 HTTPS 的约定,也就是元数据里面是否有 Secure 的配置。

大致如下图:

写在最后

声明式的接口调用,对Http接口请求,还是很方便的

感兴趣的话,欢迎您的加入,一起开发完善。

nacos-sdk-csharp 的地址 :https://github.com/nacos-group/nacos-sdk-csharp

nacos-csharp-extensions 的地址: https://github.com/catcherwong/nacos-csharp-extensions

本文示例代码的地址 :https://github.com/catcherwong-archive/2021/tree/main/WebApiClientCoreWithNacos

聊一聊声明式接口调用与Nacos的结合使用的更多相关文章

  1. Spring Cloud07: Feign 声明式接口调用

    一.什么是Feign Feign也是去实现负载均衡,但是它的使用要比Ribbon更加简化,它实际上是基于Ribbon进行了封装,让我们可以通过调用接口的方式实现负载均衡.Feign和Ribbon都是由 ...

  2. spring cloud 系列第4篇 —— feign 声明式服务调用 (F版本)

    源码Gitub地址:https://github.com/heibaiying/spring-samples-for-all 一.feign 简介 在上一个用例中,我们使用ribbon+restTem ...

  3. springcloud-feign组件实现声明式的调用

    11.使用feign实现声明式的调用 使用RestTemplate+ribbon已经可以完成对服务端负载均衡的调用,为什么还要使用feign? @RequestMapping("/hi&qu ...

  4. Spring Cloud Feign 声明式服务调用

    目录 一.Feign是什么? 二.Feign的快速搭建 三.Feign的几种姿态 参数绑定 继承特性 四.其他配置 Ribbon 配置 Hystrix 配置 一.Feign是什么? ​ 通过对前面Sp ...

  5. SpringCloud学习笔记(3):使用Feign实现声明式服务调用

    简介 Feign是一个声明式的Web Service客户端,它简化了Web服务客户端的编写操作,相对于Ribbon+RestTemplate的方式,开发者只需通过简单的接口和注解来调用HTTP API ...

  6. Spring Cloud Eureka 分布式开发之服务注册中心、负载均衡、声明式服务调用实现

    介绍 本示例主要介绍 Spring Cloud 系列中的 Eureka,使你能快速上手负载均衡.声明式服务.服务注册中心等 Eureka Server Eureka 是 Netflix 的子模块,它是 ...

  7. SpringCloud系列-利用Feign实现声明式服务调用

    上一篇文章<手把手带你利用Ribbon实现客户端的负载均衡>介绍了消费者通过Ribbon调用服务实现负载均衡的过程,里面所需要的参数需要在请求的URL中进行拼接,但是参数太多会导致拼接字符 ...

  8. Spring Cloud第七篇 | 声明式服务调用Feign

    本文是Spring Cloud专栏的第七篇文章,了解前六篇文章内容有助于更好的理解本文: Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cloud ...

  9. 6.使用Feign实现声明式REST调用

                        使用Feign实现声明式REST调用 6.1. Feign简介 Feign是一个声明式的REST客户端,它的目的就是让REST调用更加简单. Feign提供了H ...

随机推荐

  1. VUE页面跳转方式

    一.to +跳转路径 <router-link to="/">跳转到主页</router-link> <router-link :to="{ ...

  2. [转载]CentOS 7 创建本地YUM源

    本文中的"本地YUM源"包括三种类型:一是直接使用CentOS光盘作为本地yum源,优点是简单便捷,缺点是光盘软件包可能不完整(centos 7 Everything 总共才6.5 ...

  3. Nresource服务之接口缓存化

    1. 背景 Nresource服务日均4.5亿流量,考虑到未来流量急增场景,我们打算对大流量接口进行缓存化处理:根据服务管理平台数据统计显示getUsableResoureCount接口调用量很大,接 ...

  4. CF438E-The Child and Binary Tree【生成函数】

    正题 题目链接:https://www.luogu.com.cn/problem/CF438E 题目大意 每个节点有\(n\)个权值可以选择,对于\(1\sim m\)中的每个数字\(k\),求权值和 ...

  5. 设计 4 个线程,其中两个线程每次对 j 增加 1 ,另外两个线程对 j 每次减少 1 。写出程序。

    题目:设计 4 个线程,其中两个线程每次对 j 增加 1 ,另外两个线程对 j 每次减少 1 .写出程序. 代码实现 public class ThreadTest{ private int j; c ...

  6. Java基础- 重写,重构和重载

    重写也称为覆盖, 是指子类与父类的方法名相同但是可以有不同的权限(子类权限需大于父类),返回值(J2SE 5.0以后增加的功能,且子类的返回值必须是父类返回值的子类)或者方法实现. 重写体现了子类补充 ...

  7. iOS实现XMPP通讯(一)搭建Openfire

    安装Openfire Openfire官网下载地址:https://igniterealtime.org/downloads/ (也是Spark客户端的下载地址) Openfire下载并安装后,打开系 ...

  8. 从源码分析node-gyp指定node库文件下载地址

    当我们安装node的C/C++原生模块时,涉及到使用node-gyp对C/C++原生模块的编译工作(configure.build).这个过程,需要nodejs的头文件以及静态库参与(后续称库文件)对 ...

  9. 从零入门 Serverless | 函数计算如何粘合云服务,提供端到端解决方案

    作者 | 西流 阿里云技术专家 导读:阿里云 Serverless 产品函数计算可以作为粘合剂,串联其他云服务提供端到端解决方案,从而简化编程模型,快速实现最上层的业务目标. 传统单体应用的拆解 首先 ...

  10. NOI 2017 Day1 题解

    被虐爆了... T1 整数 题目传送门 Description 有一个整数 \(x\),有 \(n\) 此操作,每次操作为以下两种情况: 给出 \(a,b\),将 \(x\) 加上 \(a\times ...