[从0到1搭建ABP微服务] - 搭建WebApp网关服务

简介

微服务的架构体系是由许多颗粒的服务组合而成,这些服务均负责各自的业务独立运行,使用网关可以将这些服务的接口进行聚合对外发布统一的网关API地址即可。本篇将介绍ABP网关服务的搭建,ABP网关不仅转发API接口,还提供了微服务权限的聚合。

新建项目

在Gateways目录中创建一个新的 asp.net core 项目 WebAppGateway.Host
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第1张图片

空项目结构如下:
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第2张图片

发布本地微服务NuGet包

微服务架构不同于单体应用架构开发,单体应用中我们可以对项目工程直接添加引用,微服务中无法跨服务添加引用,所以通常会有一个本地的包管理器进行项目版本管理来添加相应服务版本的nuget包。

发布Business包

在Business解决方案中选择Business.Domain配置如下
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第3张图片

Business.Application.Contracts和Business.HttpApi同上配置,重新生成解决方案

上传NuGet包

打开proget包管理添加Business.HttpApi 1.0.0包

搭建ProGet管理器可以参考这篇文章:https://www.cnblogs.com/william-xu/p/12083885.html

安装模块组件

在空项目中安装 .net core、ef core、ids4、abp等官方组件和其他服务nuget包。
PM> Install-Package Serilog.AspNetCore
PM> Install-Package Serilog.Sinks.File
PM> Install-Package Serilog.Sinks.Elasticsearch
PM> Install-Package Serilog.Sinks.Async
PM> Install-Package Swashbuckle.AspNetCore
PM> Install-Package Ocelot
PM> Install-Package IdentityServer4.AccessTokenValidation
PM> Install-Package Microsoft.Extensions.Caching.StackExchangeRedis
PM> Install-Package Microsoft.AspNetCore.DataProtection.StackExchangeRedis
PM> Install-Package Volo.Abp.AspNetCore.MultiTenancy
PM> Install-Package Volo.Abp.Autofac
PM> Install-Package Volo.Abp.EntityFrameworkCore.SqlServer
PM> Install-Package Volo.Abp.Identity.HttpApi
PM> Install-Package Volo.Abp.PermissionManagement.EntityFrameworkCore
PM> Install-Package Volo.Abp.PermissionManagement.HttpApi
PM> Install-Package Volo.Abp.SettingManagement.EntityFrameworkCore
PM> Install-Package Volo.Abp.TenantManagement.EntityFrameworkCore
PM> Install-Package Volo.Abp.TenantManagement.HttpApi

配置Module

在项目根目录下添加WebAppGatewayHostModule.cs
注册认证方式、swagger、redis等服务,代码如下:

    public class WebAppGatewayHostModule: AbpModule
    {
        private const string DefaultCorsPolicyName = "Default";

        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            var configuration = context.Services.GetConfiguration();
            var hostingEnvironment = context.Services.GetHostingEnvironment();

            ConfigureAuthentication(context, configuration);
            ConfigureSql();
            ConfigureRedis(context, configuration, hostingEnvironment);
            ConfigureCors(context, configuration);
            ConfigureSwaggerServices(context);
            context.Services.AddOcelot(context.Services.GetConfiguration());
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var app = context.GetApplicationBuilder();

            app.UseCorrelationId();
            app.UseVirtualFiles();
            app.UseRouting();
            app.UseCors(DefaultCorsPolicyName);
            app.UseAuthentication();
            app.UseMultiTenancy();
            app.UseAuthorization();

            app.UseSwagger();
            app.UseSwaggerUI(options =>
            {
                options.SwaggerEndpoint("/swagger/v1/swagger.json", "Business Service API");
            });

            app.MapWhen(
                ctx => ctx.Request.Path.ToString().StartsWith("/api/abp/") ||
                       ctx.Request.Path.ToString().StartsWith("/Abp/"),
                app2 =>
                {
                    app2.UseRouting();
                    app2.UseMvcWithDefaultRouteAndArea();
                }
            );

            app.UseOcelot().Wait();
            app.UseAbpSerilogEnrichers();
        }

        private void ConfigureAuthentication(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddAuthentication("Bearer")
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = configuration["AuthServer:Authority"];
                    options.RequireHttpsMetadata = true;
                    options.ApiName = "BusinessService";
                });
        }

        private static void ConfigureSwaggerServices(ServiceConfigurationContext context)
        {
            context.Services.AddSwaggerGen(
                options =>
                {
                    options.SwaggerDoc("v1", new OpenApiInfo { Title = "Business Service API", Version = "v1" });
                    options.DocInclusionPredicate((docName, description) => true);
                });
        }

        private void ConfigureSql()
        {
            Configure(options =>
            {
                options.UseSqlServer();
            });
        }

        private void ConfigureRedis(
            ServiceConfigurationContext context,
            IConfiguration configuration,
            IWebHostEnvironment hostingEnvironment)
        {
            context.Services.AddStackExchangeRedisCache(options =>
            {
                options.Configuration = configuration["Redis:Configuration"];
            });

            if (!hostingEnvironment.IsDevelopment())
            {
                var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]);
                context.Services
                    .AddDataProtection()
                    .PersistKeysToStackExchangeRedis(redis, "DataProtection-Keys");
            }
        }

        private void ConfigureCors(ServiceConfigurationContext context, IConfiguration configuration)
        {
            context.Services.AddCors(options =>
            {
                options.AddPolicy(DefaultCorsPolicyName, builder =>
                {
                    builder
                        .WithOrigins(
                            configuration["App:CorsOrigins"]
                                .Split(",", StringSplitOptions.RemoveEmptyEntries)
                                .Select(o => o.RemovePostFix("/"))
                                .ToArray()
                        )
                        .WithAbpExposedHeaders()
                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                        .AllowAnyHeader()
                        .AllowAnyMethod()
                        .AllowCredentials();
                });
            });
        }
    }

启动

Ctrl+F5运行
进入swagger页面如下
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第4张图片

Identity、Tenant、Business接口文件均已显示:
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第5张图片

调试

网关服务接口测试

AbpApplicationConfiguration测试:
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第6张图片
请求成功并返回所有权限信息

联调

通过网关调用business服务接口
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第7张图片
成功请求但未授权
授权后测试
[从0到1搭建ABP微服务] - 搭建WebApp网关服务_第8张图片
请求成功并返回数据

代码地址:https://github.com/WilliamXu96/ABP-MicroService

文章目录:https://www.cnblogs.com/william-xu/p/12537155.html

你可能感兴趣的:([从0到1搭建ABP微服务] - 搭建WebApp网关服务)