Net6使用Yarp做网关

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 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值