至尊魔君 發表於 2023-9-5 21:43:00

基于ASP.NET ZERO,开发SaaS版供应链管理系统

<h1 id="前言">前言</h1>
<p>2018年下半年,公司决定开发一款SaaS版行业供应链管理系统,经过选型,确定采用ABP(ASP.NET Boilerplate)框架。为了加快开发效率,购买了商业版的 ASP.NET ZERO(以下简称ZERO),选择<strong>ASP.NET Core + Angular</strong>的SPA框架进行系统开发(ABP.IO届时刚刚起步,还很不成熟,因此没有选用)。</p>
<p>关于ABP与ZERO,园子里已经有诸多介绍,因此不再赘述。本文侧重介绍我们基于ZERO框架开发系统过程中进行的一些优化、调整、扩展部分的内容,方便有需要的园友们了解或者参考。</p>
<h1 id="系统架构">系统架构</h1>
<p>系统在2020年7月发布上线(部署在阿里云上),目前有超过500家企业/团队/个人注册体验,感兴趣的园友可以在此系统的着陆网站 scm.plus 注册一个免费账号体验一下,欢迎大家的批评与建议。</p>
<p><img src="https://img2024.cnblogs.com/blog/161009/202401/161009-20240129101011999-139339813.png"></p>
<p>ZERO框架总体上来说还是不错的,可以快速的上手,集成的通用功能(版本、租户、角色、用户、设置等)初期都可以直接使用,但还达不到直接发布使用的水准,需要经过诸多的优化调整扩展后才能发布上线。</p>
<h1 id="a-后端aspnet-core部分">A 后端(ASP.NET Core)部分</h1>
<h3 id="0移除不需要的功能chatsignalrdynamicpropertygraphqlidentityserver4">0、移除不需要的功能:Chat、SignalR、DynamicProperty、GraphQL、IdentityServer4。</h3>
<p>基于系统功能定位,移除的这些不需要的功能,使系统尽可能的精简。</p>
<h3 id="1migrations内移除designercs">1、Migrations内移除Designer.cs。</h3>
<p>在我们的开发环境内,经过测试与验证,使用mysql数据库时候,可以安全移除add-migration时候生成的庞大的Designer.cs文件。移除Designer.cs文件时候,需要把该文件内的DbContext与Migration声明语句移到对应的migration.cs文件内:</p>
<pre><code>

public partial class Upgraded_To_Abp_8_3 : Migration
{
   //...
}
</code></pre>
<h3 id="2替换必要的功能包确保系统后端可以部署到linux环境">2、替换必要的功能包,确保系统后端可以部署到linux环境:</h3>
<ul>
<li>使用SkiaSharp替换System.Drawing.Common;</li>
<li>使用EPPlus替换NPOI。</li>
</ul>
<h3 id="3停用系统默认的外部登录-facebookgooglemicrosofttwitter等添加微信扫码与小程序登录">3、停用系统默认的外部登录( Facebook、Google、Microsoft、Twitter等),添加微信扫码与小程序登录。</h3>
<h3 id="4停用系统默认的支付选项-paypalstripe等添加支付宝alipay支付">4、停用系统默认的支付选项( Paypal、Stripe等),添加支付宝(Alipay)支付。</h3>
<h3 id="5excel文件上传zero默认没有实现需要自行添加excel文件的上传与导入功能">5、Excel文件上传,ZERO默认没有实现,需要自行添加Excel文件的上传与导入功能:</h3>
<ul>
<li>Excel文件上传后先缓存该文件;</li>
<li>创建一个后台Job(HangFire)执行Excel文件的读取、处理等;</li>
<li>Job发送执行后的结果(消息通知)。</li>
</ul>
<pre><code>

public async Task&lt;JsonResult&gt; ImportFromExcel()
{
    try
    {
      var jobArgs = await DoImportFromExcelJobArgs(AbpSession.ToUserIdentifier());

      var queueState = new EnqueuedState(GetJobQueueName());
      IBackgroundJobClient hangFireClient = new BackgroundJobClient();
      hangFireClient.Create&lt;ImportTxxxsToExcelJob&gt;(x =&gt; x.ExecuteAsync(jobArgs), queueState);

      return Json(new AjaxResponse(new { }));
    }
    catch (Exception ex)
    {
      return Json(new AjaxResponse(new ErrorInfo(ex.Message)));
    }
}
</code></pre>
<h3 id="6图片与文件上传存储zero的默认实现是保存上传的图片文件到数据库内需要改造存储到oss中">6、图片与文件上传存储,ZERO的默认实现是保存上传的图片文件到数据库内,需要改造存储到OSS中:</h3>
<ul>
<li>使用MD5哈希前缀,生成OSS文件对象的名称(含path),提高OSS并发性能:</li>
</ul>
<pre><code>private static string GetOssObjName(int? tenantId, Guid id, bool isThumbnail)
{
    string tid = (tenantId ?? 0).ToString();
    string ext = isThumbnail ? "thu" : "ori"; //thu - 缩略图、ori - 原图/原文件
    string hashStr = BitConverter.ToString(MD5.HashData(Encoding.UTF8.GetBytes(tid)), 0).Replace("-", string.Empty).ToLower();

    return $"{hashStr[..4]}/{tid}/{id}.{ext}";
}
</code></pre>
<ul>
<li>若OSS未启用或者上传失败,则直接存储到数据库中:</li>
</ul>
<pre><code>public async Task SaveAsync(BinaryObject file)
{
    if (file?.Bytes == null) { return; }

    //1、OSS上传,成功后直接返回
    if (OssPutObject(file.TenantId, file.Id, file.Bytes, isThumbnail: false)) { return; }

    //2、若OSS未启用或者上传失败,则直接上传到数据库中
    await _binaryObjectRepository.InsertAsync(file);
}
</code></pre>
<ul>
<li>获取时候遵循一样的逻辑:若OSS未启用或者获取不到,则直接自数据库中获取;自数据库获取成功后要同步数据库中记录到OSS中。</li>
</ul>
<h3 id="7webhook功能需要改造支持推送数据到第三方接口如企业微信群钉钉群聚水潭api等">7、Webhook功能,需要改造支持推送数据到第三方接口,如:企业微信群、钉钉群、聚水潭API等:</h3>
<ul>
<li>重写WebhookManager的SignWebhookRequest方法;</li>
<li>重写DefaultWebhookSender的CreateWebhookRequestMessage、AddAdditionalHeaders、SendHttpRequest方法;</li>
<li>缓存Webhook Subscription:</li>
</ul>
<pre><code>private SCMWebhookCacheItem SetAndGetCache(int? tenantId, string keyName = "SubscriptionCount")
{
   int tid = tenantId ?? 0; var cacheKey = $"{keyName}-{tid}";

   return _cacheManager.GetSCMWebhookCache().Get(cacheKey, () =&gt;
   {
      int count = 0;
      var names = new Dictionary&lt;string, List&lt;WebhookSubscription&gt;&gt;();

      UnitOfWorkManager.WithUnitOfWork(() =&gt;
      {
            using (UnitOfWorkManager.Current.SetTenantId(tenantId))
            {
                if (_featureChecker.IsEnabled(tid, "SCM.H"))            //Feature 核查
                {
                  var items = _webhookSubscriptionRepository.GetAllList(e =&gt; e.TenantId == tenantId &amp;&amp; e.IsActive == true);
                  count = items.Count;

                  foreach (var item in items)
                  {
                        if (string.IsNullOrWhiteSpace(item.Webhooks)) { continue; }
                        var whNames = JsonHelper.DeserializeObject&lt;string[]&gt;(item.Webhooks); if (whNames == null) { continue; }
                        foreach (string whName in whNames)
                        {
                            if (names.ContainsKey(whName))
                            {
                              names.Add(item.ToWebhookSubscription());
                            }
                            else
                            {
                              names.Add(whName, new List&lt;WebhookSubscription&gt; { item.ToWebhookSubscription() });
                            }
                        }
                  }
                }
            }
      });

      return new SCMWebhookCacheItem(count, names);
    });
}
</code></pre>
<h3 id="8在webhostmodule中设定只有一台server执行后台work避免多台server重复执行">8、在WebHostModule中设定只有一台Server执行后台Work,避免多台Server重复执行:</h3>
<pre><code>public override void PostInitialize()
{
    //...

    string defaultEndsWith = _appConfiguration["Job:DefaultEndsWith"];
    if (string.IsNullOrWhiteSpace(defaultEndsWith)) { defaultEndsWith = "01"; }
    if (AppVersionHelper.MachineName.EndsWith(defaultEndsWith))
    {
      var workManager = IocManager.Resolve&lt;IBackgroundWorkerManager&gt;();

      workManager.Add(IocManager.Resolve&lt;SubscriptionExpirationCheckWorker&gt;());
      workManager.Add(IocManager.Resolve&lt;SubscriptionExpireEmailNotifierWorker&gt;());
      workManager.Add(IocManager.Resolve&lt;SubscriptionPaymentsCheckWorker&gt;());
      workManager.Add(IocManager.Resolve&lt;ExpiredAuditLogDeleterWorker&gt;());
      workManager.Add(IocManager.Resolve&lt;PasswordExpirationBackgroundWorker&gt;());
    }

    //...
}
</code></pre>
<h3 id="9限流功能zero默认没有实现通过添加aspnetcoreratelimit中间件集成限流功能">9、限流功能,ZERO默认没有实现,通过添加<strong>AspNetCoreRateLimit</strong>中间件集成限流功能:</h3>
<ul>
<li>采用<strong>客户端ID(ClientRateLimiting)</strong>进行设置;</li>
<li>重写<strong>RateLimitConfiguration</strong>的<strong>RegisterResolvers</strong>方法,添加定制化的<strong>ClientIpHeaderResolveContributor</strong>:存在客户端ID则优先获取,反之获取客户端的IP:</li>
</ul>
<pre><code>    public class RateLimitConfigurationExtensions : RateLimitConfiguration
    {
      //...
      public override void RegisterResolvers()
      {
            ClientResolvers.Add(new ClientIpHeaderResolveContributor(SCMConsts.TenantIdCookieName));
      }
    }

    public class ClientIpHeaderResolveContributor : IClientResolveContributor
    {
      private readonly string _headerName;

      public ClientIpHeaderResolveContributor(string headerName)
      {
            _headerName = headerName;   
      }

      public Task&lt;string&gt; ResolveClientAsync(HttpContext httpContext)
      {
            IPAddress clientIp = null;

            var headers = httpContext?.Request?.Headers;
            if (headers != null &amp;&amp; headers.Count &gt; 0)
            {
                if (headers.ContainsKey(_headerName))                               //0 scm_tid
                {
                  string clientId = headers.ToString();
                  if (!string.IsNullOrWhiteSpace(clientId))
                  {
                        return Task.FromResult(clientId);
                  }
                }

                try
                {
                  if (headers.ContainsKey("X-Real-IP"))                           //1 X-Real-IP
                  {
                        clientIp = IpAddressUtil.ParseIp(headers["X-Real-IP"].ToString());
                  }
                  
                  if (clientIp == null &amp;&amp; headers.ContainsKey("X-Forwarded-For")) //2 X-Forwarded-For
                  {
                        clientIp = IpAddressUtil.ParseIp(headers["X-Forwarded-For"].ToString());
                  }
                }
                catch {}

                clientIp ??= httpContext?.Connection?.RemoteIpAddress;             //3 RemoteIpAddress
            }

            return Task.FromResult(clientIp?.ToString());
      }
    }
</code></pre>
<h1 id="b-前端angular部分">B 前端(Angular)部分</h1>
<h3 id="0类似后端移除不需要的功能chatsignalrdynamicproperty等">0、类似后端,移除不需要的功能:Chat、SignalR、DynamicProperty等。</h3>
<h3 id="1拆分精简service-proxiests文件">1、拆分精简<strong>service-proxies.ts</strong>文件:</h3>
<ul>
<li>ZERO使用NSwag生成前端的TypeScript代码文件<strong>service-proxies.ts</strong>,全部模块的都生成到一个文件内,导致该文件非常庞大,最终编译生成的main.js接近4MB;</li>
<li>按系统执行层次,拆分<strong>service-proxies.ts</strong>为多个文件,精简其中的共用代码,调整module的调用、拆分、懒加载等,最终大幅度减少了main.js的大小(目前是587KB)。</li>
</ul>
<h3 id="2优化表格组件primeng-table实现客户端表格使用状态的本地存储表格列宽列顺序列显示隐藏列固定分页设定等">2、优化表格组件<strong>primeng table</strong>,实现客户端表格使用状态的本地存储:表格列宽、列顺序、列显示隐藏、列固定、分页设定等。</h3>
<h3 id="3实现客户端的卡片视图功能">3、实现客户端的卡片视图功能。</h3>
<h3 id="4集成ng-lazyload-image实现图片展示的懒加载">4、集成<strong>ng-lazyload-image</strong>,实现图片展示的懒加载。</h3>
<h3 id="5集成ngx-markdown实现markdown格式的在线帮助">5、集成<strong>ngx-markdown</strong>,实现markdown格式的在线帮助。</h3>
<h3 id="6业务组件设置为独立组件changedetectionstrategy设置为onpush">6、业务组件设置为独立组件,ChangeDetectionStrategy设置为OnPush:</h3>
<pre><code>@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
    templateUrl: './txxxs.component.html',
    standalone: true,
    imports: [...]
})
export class TxxxsComponent extends AppComponentBase {
    ...
    constructor(
      injector: Injector,
      changeDetector: ChangeDetectorRef,
    ) {
      super(injector);
      setInterval(() =&gt; { changeDetector.markForCheck(); }, AppConsts.ChangeDetectorMS);
    }
    ...
}
</code></pre>
<h3 id="7仪表盘升级为工作台除了可以添加图表外也可以添加业务组件独立组件">7、仪表盘升级为工作台,除了可以添加图表外,也可以添加业务组件(独立组件)。</h3>
<h3 id="8路由直接链接业务组件实现懒加载">8、路由直接链接业务组件,实现懒加载:</h3>
<pre><code>import { Route } from '@angular/router';
export default [
    { path: 'p120303/t12030301s', loadComponent: () =&gt; import('./t12030301s.component').then(c =&gt; c.T12030301sComponent), ... },
    { path: 'p120405/t12040501s', loadComponent: () =&gt; import('./t12040501s.component').then(c =&gt; c.T12040501sComponent), ... },
    { path: 'p120405/t12040502s', loadComponent: () =&gt; import('./t12040502s.component').then(c =&gt; c.T12040502sComponent), ... },
] as Route[];
</code></pre>
<h3 id="9通过webpackinclude减少打包后的文件数量使用webpackchunkname设定打包后的文件名">9、通过<strong>webpackInclude</strong>,减少打包后的文件数量;使用<strong>webpackChunkName</strong>设定打包后的文件名:</h3>
<pre><code>function registerLocales(
    resolve: (value?: boolean | Promise&lt;boolean&gt;) =&gt; void,
    reject: any,
    spinnerService: NgxSpinnerService
) {
    if (shouldLoadLocale()) {
      let angularLocale = convertAbpLocaleToAngularLocale(abp.localization.currentLanguage.name);
      import(
            /* webpackInclude: /(en|en-GB|zh|zh-Hans|zh-Hant)\.mjs$/ */
            /* webpackChunkName: "angular-common-locales" */
            `/node_modules/@angular/common/locales/${angularLocale}.mjs`).then((module) =&gt; {
                registerLocaleData(module.default);
                resolve(true);
                spinnerService.hide();
            }, reject);
    } else {
      resolve(true);
      spinnerService.hide();
    }
}
</code></pre>
<h1 id="c-小程序vue3部分">C 小程序(Vue3)部分</h1>
<h3 id="后端部分已经实现小程序集成微信登录后端输出的语言文本与api等小程序都可以直接调用因此小程序的开发实现就相对比较容易只需要实现必要的ui界面即可">后端部分已经实现小程序集成微信登录,后端输出的语言文本与API等小程序都可以直接调用,因此小程序的开发实现就相对比较容易,只需要实现必要的UI界面即可。</h3>
<ul>
<li>小程序采用 <strong>uni-app(vue3)</strong> 框架进行开发,整体效率较高。</li>
<li>有部分代码可以基于前端 <strong>Angular</strong> 的代码复制后稍加调整后即可使用。</li>
<li>目前只输出了微信小程序,方便同企业微信群内的消息推送一体化集成。</li>
<li>后端部分实现的Webhook功能,可以直接推送消息到企业微信群内,用户可以单击消息卡片,直接打开微信小程序内对应的页面,查看数据或者进行其他的维护操作。</li>
<li>小程序中需要在onLaunch中进行路由守卫(登录拦截),以处理通过分享单独页面或者企业微信群内通过消息卡片直接打开小程序页面的权限核查。</li>
</ul>
<h1 id="总结">总结</h1>
<h3 id="若没有优秀的工具框架支持开发saas化系统并不是一件容易的事基于abp框架使用zero工具极大的降低了开发saas化系统的门槛也促成了这套系统的实践与发布">若没有优秀的工具框架支持,开发SaaS化系统并不是一件容易的事。基于ABP框架,使用ZERO工具,极大的降低了开发SaaS化系统的门槛,也促成了这套系统的实践与发布。</h3>
<h3 id="本文简要介绍了我们实现这套系统中的一些要点供有需要的人了解参考就算是抛砖引玉吧">本文简要介绍了我们实现这套系统中的一些要点,供有需要的人了解参考,就算是抛砖引玉吧!</h3><br><br>
来源:https://www.cnblogs.com/freedyang/p/17679280.html
頁: [1]
查看完整版本: 基于ASP.NET ZERO,开发SaaS版供应链管理系统