1、启用nacos服务端,本例使用的是2.1版本
在nacos创建yarp命名空间
2、创建net5webapi服务
2.1、ordersvc服务
appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Nacos.AspNetCore": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"nacos": {
"EndPoint": "",
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "yarp",
"ListenInterval": 1000,
"ServiceName": "ordersvc",
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"Ip": "",
"PreferredNetworks": "",
"Port": 0,
"Weight": 100,
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"Secure": false,
"AccessKey": "",
"SecretKey": "",
"UserName": "",
"Password": "",
"ConfigUseRpc": false,
"NamingUseRpc": false,
"NamingLoadCacheAtStart": ""
}
}
代码
using Nacos.AspNetCore.V2;
var builder = WebApplication.CreateBuilder(args);
// nacos server v1.x or v2.x
builder.Services.AddNacosAspNet(builder.Configuration);
builder.Services.AddControllers();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", () =>
{
return Results.Ok("order svc 9001");
});
});
app.Run("http://*:9001");
2.2 usersvc服务
appsetting.json
{
"Logging": {
"LogLevel": {
"Default": "Warning",
"Nacos.AspNetCore": "Information",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"nacos": {
"EndPoint": "",
"ServerAddresses": [ "http://localhost:8848" ],
"DefaultTimeOut": 15000,
"Namespace": "yarp",
"ListenInterval": 1000,
"ServiceName": "usersvc",
"GroupName": "DEFAULT_GROUP",
"ClusterName": "DEFAULT",
"Ip": "",
"PreferredNetworks": "",
"Port": 0,
"Weight": 100,
"RegisterEnabled": true,
"InstanceEnabled": true,
"Ephemeral": true,
"Secure": false,
"AccessKey": "",
"SecretKey": "",
"UserName": "",
"Password": "",
"ConfigUseRpc": false,
"NamingUseRpc": false,
"NamingLoadCacheAtStart": ""
}
}
代码
using Nacos.AspNetCore.V2;
var builder = WebApplication.CreateBuilder(args);
// nacos server v1.x or v2.x
builder.Services.AddNacosAspNet(builder.Configuration);
builder.Services.AddControllers();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", () =>
{
return Results.Ok("user svc 9002");
});
});
app.Run("http://*:9002");
2.3、yarp网关,也可以把网关注册到服务中心统一管理,下图为无注册到服务中心情况
using global::Nacos.V2.DependencyInjection;
using Yarp.ReverseProxy.Configuration;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddNacosV2Naming(x =>
{
x.ServerAddresses = new System.Collections.Generic.List<string> { "http://localhost:8848/" };
x.Namespace = "yarp";
// swich to use http or rpc
x.NamingUseRpc = false;
});
builder.Services.AddReverseProxy()
.AddNacosServiceDiscovery(
groupNames: "DEFAULT_GROUP",
percount:100,
enableAutoRefreshService: true,
autoRefreshPeriod: 30);
var app = builder.Build();
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/yarp", (IProxyConfigProvider provider) =>
{
var res = provider.GetConfig();
return Results.Ok(res);
});
endpoints.MapReverseProxy();
});
app.Run("http://*:9099");
3、启动服务和网关,在nacos服务中心查看
4、查看服务详情并测试
4.1访问 http://localhost:9099/yarp 服务详细如下
{
"routes": [{
"routeId": "DEFAULT_GROUP@@usersvc-route",
"match": {
"methods": null,
"hosts": null,
"path": "/usersvc/{**catch-all}",
"queryParameters": null,
"headers": null
},
"order": null,
"clusterId": "DEFAULT_GROUP@@usersvc",
"authorizationPolicy": null,
"corsPolicy": null,
"metadata": null,
"transforms": [{
"PathRemovePrefix": "/usersvc"
}]
}, {
"routeId": "DEFAULT_GROUP@@ordersvc-route",
"match": {
"methods": null,
"hosts": null,
"path": "/ordersvc/{**catch-all}",
"queryParameters": null,
"headers": null
},
"order": null,
"clusterId": "DEFAULT_GROUP@@ordersvc",
"authorizationPolicy": null,
"corsPolicy": null,
"metadata": null,
"transforms": [{
"PathRemovePrefix": "/ordersvc"
}]
}],
"clusters": [{
"clusterId": "DEFAULT_GROUP@@usersvc",
"loadBalancingPolicy": "RoundRobin",
"sessionAffinity": null,
"healthCheck": null,
"httpClient": null,
"httpRequest": null,
"destinations": {
"http://10.15.69.27:9002": {
"address": "http://10.15.x.x:9002",
"health": null,
"metadata": {}
}
},
"metadata": null
}, {
"clusterId": "DEFAULT_GROUP@@ordersvc",
"loadBalancingPolicy": "RoundRobin",
"sessionAffinity": null,
"healthCheck": null,
"httpClient": null,
"httpRequest": null,
"destinations": {
"http://10.15.69.27:9001": {
"address": "http://10.15.x.x:9001",
"health": null,
"metadata": {}
}
},
"metadata": null
}],
"changeToken": {
"hasChanged": false,
"activeChangeCallbacks": true
}
}
4.2 通过网关访问访问服务
Yarp官网:YARP Documentation