.NET Core framework for rapid development separated front and rear ends (Core.3.0 + AntdVue)

.NET Core framework for rapid development separated front and rear ends (Core.3.0 + AntdVue)

table of Contents

introduction

Time really fast, blink of an eye again later this year. Recall that this year, followed by the open source released Colder.Fx.Net.AdminLTE (254Star) , Colder.Fx.Core.AdminLTE (335Star) , DotNettySocket (82Star) , IdHelper (47Star) , these frameworks and components are in line with reality , pragmatic attitude and strive to improve development efficiency (myself are the first user), now a good response. But with the constant changes in the front and back-end technology, especially the front-end, the current environment has front and rear ends are completely separate-based development model, under this environment and the inevitable trend, the traditional MVC looks a little behind the times . In this context, a front and rear end of the separation of .NET development framework is particularly necessary, which would set a target upgrade framework: the front and rear ends of the splitter .

First select the back-end technology, from the current data, .NET Core development is much faster than the .NET Framework, the most simple analysis is Colder.Fx.Core.AdminLTE released later than Colder.Fx.Net.AdminLTE, but the stars did come from behind and 30% more than the former, and this gap is growing, the analysis points and face can be seen in the large number of .NET developers to learn the enthusiasm and positive attitude, not some people think so unbearable ( go its own way, whatever others may say ). On the environment and actively embrace Microsoft's open source, to develop .NET Core, it can be said that the future is bright. Therefore the backend decided to use the .NET Core3.0 , not waste energy to support the .NET Framework.

Then the front-end technology choice, the preferred choice are the three js framework, but also proceed from reality, Vue relative to other terms more easy to use, and features no less, and won a variety of large and small companies like, if chosen to say flaw, that is not support for TS, but the upcoming release Vue3.0 certainly change this defect. After selecting the Vue, and UI framework is chosen, more options here, and I chose Ant Design Vue, the reason is simple and convenient, very consistent with my design.

After the completion of the technology selection will go to research and development, because the front-end I compare dish, it is necessary to start from scratch Vue2.x family bucket, from the beginning to now experienced almost three months, within expectations. In fact, to learn and to use front-end Vue2.x family bucket is not difficult, it is quite easy to use, so this is not my brother to separate the front and rear end development experience of playing a vaccination record, not to retreat, to go upstream, learning endless.

Some may be more directly rude brother, I too BBB nagging, directly on the address below
Code (GitHub): https://github.com/Coldairarrow/Colder.Admin.AntdVue
document (GitHub): HTTPS: // GitHub. com / Coldairarrow / Colder.Admin.AntdVue / wiki
codes (code cloud images): https://gitee.com/Coldairarrow/Colder.Admin.AntdVue
document (code cloud images): https://gitee.com/Coldairarrow/ Colder.Admin.AntdVue / wikis
online preview address : http://coldairarrow.gitee.io/coler.antdvue.preview/#/Home/Introduce
because the server is Ali cloud server 86, the bandwidth of 1M little water, so the front-end deployment the code to cloud, and would like to thank code cloud , backend deployed in the cloud Ali 86 server CentOS7. The entire technology stack using the .NET Core Design Ant + + PostggreSQL Vue + CentOS7 Nginx + + + Dokcer Jenkins , loss of bladder deployed from the rapid development of the automated one-stop, open-source and free high-performance, high portability, high scalability ( small companies venture Selection + individual orders weapon )

Brief introduction

This framework .NET Core3.0 + Ant Design Vue Edition

This framework is designed to greatly improve development efficiency

Use technology stack:
backend: The .NET Core platform, ASP.NET Core3.0, C # language (using reflection and other senior technical), Entity FrameworkCore (database ORM framework).
Using the data storage pattern, abstract database operations (CRUD etc.), transaction processing, and support for distributed transaction processing (cross library)
support database separate read and write, and sub-sub-table database transaction (only supports single-table operation, does not support multiple sheets) full use of Autofac as IOC container, oriented programming interface, full decoupling
integrated a variety of tools and libraries to expand operations
database: supports SqlServer, PostgreSQL, MySQL, Oracle (framework uses a simple factory, factory method abstract factory, can easily replace the database) , Redis as a distributed cache
front-end: Vue2.x family bucket + Ant Design Vue, which integrates common components, and strive to facilitate project development.

Specific technical implementation:
project uses completely separated front and rear ends mode and strict hierarchical model, greatly increasing the degree of polymerization, reduced coupling,
improved code robustness, maintainability.
Before and after the client is authenticated by JWT, operational data through the data interface, unified use of JSON as a data format, and use the default interface interface signature algorithm to ensure safety.

Detailed Functional Architecture Part:
Rapid Development: This function is the core framework, by selecting the database tables, and to automatically generate physical layer, business logic, controller, Vue file corresponding to the front page, without writing code to generate a basic CRUD operations.
Interface Key Management: Key management interface, the interface if the rule signed on, the front-end interfaces need to be able to properly access the back-end signature interface.
Rights Management: Using the basic RBAC access control, supports operating authority, permissions, and data interfaces authority

The main features and characteristics of the frame as follows

Features A detailed description
User login User login, password changes
User Management System User Management System
Angle color management 1 Role Management
Sector Management Sector management, multi-level natural
authority management Use RBAC permissions system, role-based rights management, support permissions menu, operating authority (button authority), interfaces authorization, data authorization
System Log Support colorful console, file, database and ElasticSearch logging, global exception frame automatically capture, multi-level record
Rapid Development Generating direct physical layer, business logic, and the controller layer Vue front page code via a database, can be achieved without coding CURD
Database operations package EF models based storage, packaging commonly used CURD, supports single distributed database things and things
Multi-database support EF-based storage model to support the major mainstream relational database (SQLServer, MySQL, PostgreSQL and Oracle)
Super portability Abstract Factory database encapsulation layer operation, switching database 0 code changes
Support soft-deleted A key switch delete mode, and delete the soft delete physical support of business operations transparent
Cache Support Support system comes Redis cache and cache package user interface, easy to use
Completely separated front and rear ends Use Vue2.x family barrel distal + Ant Design Vue, interface simple and beautiful, component-based development
Integrated JWT verification JWT use as an authentication framework, get rid of Cookie Oliver, distributed no pressure to expand
Integration of external interfaces Signature Algorithm Framework of external interfaces can be turned super strict signature verification (non-repudiation, anti-counterfeiting, anti-repeated call) to protect the security of the system
Page responsive The front is a single-page application, without iframe, the major mainstream browser support Friendly
expand Various other help libraries and plug-ins

The relevant version see the following table:

.NET version Front-end UI address
Core3.0 Ant Design View https://github.com/Coldairarrow/Colder.Admin.AntdVue
Core2.2 AdminLTE https://github.com/Coldairarrow/Colder.Fx.Core.AdminLTE
.NET4.72 AdminLTE https://github.com/Coldairarrow/Colder.Fx.Net.AdminLTE
.NET4.52 Easyui https://github.com/Coldairarrow/Coldairarrow.Fx.Net.Easyui.GitHub
Core2.1 Easyui https://github.com/Coldairarrow/Coldairarrow.Fx.Core.Easyui.GitHub
.NET4.0 Easyui https://github.com/Coldairarrow/Coldairarrow.Fx.Net40.Easyui.GitHub

Background effect is shown below:
MG22Bd.png

Environment to build

Development environment:

Operating System: Windows 10
back-end development tools: Visual Studio 2019+
front-end development tools: Visual Studio Code, installation nodejs , the Yarn
SDK: install .NET Core SKD 3.0 and above
database: SQLServer2008 R2 and above

Construction of the underlying database:

  • Create a database
    directory "/ docs / initialization file" in the required database information
    MGo70U.png
    to manually create the database, and then execute the corresponding SQL script to

  • Configuring the connection string
    open Colder.Admin.AntdVue solution src directory, as shown below

MGTuB8.png

As shown in FIG expand sequentially 05.Coldairarrow.Api / appsettings.json, the configuration database connection strings, name without modification, connectionString above to create a database (if not clear your own database connection string search Baidu Tutorial)

Database design specifications

由于本框架支持自动生成代码的核心功能,此功能是根据数据库的表结构来生成代码的
因此规定每张表都有一个主键,列名为Id,类型为字符串,实际添加数据时默认使用SnowflakeId(雪花Id,Twitter设计的分布式趋势自增Id,若不清楚请自行百度相关资料),表中的每个列都需要有描述信息(建议这样操作,若不按照这个标准则需要一些额外的改动才能够成功运行)。每张表都需要Id、CreateTime、CreatorId、CreatorRealName这几个必带字段

MG7p2n.png

运行

后端:打开解决方案=>还原nuget包=>配置数据库=>运行(05.Coldairarrow.Web设为启动项目)
后台成功运行后会自动打开swagger
MGHcTO.png
前端: 确保已安装nodejsyarn
用VS Code 打开文件夹src\Coldairarrow.Web
MGHEOP.png
输入命令:yarn
输入命令:yarn run serve
成功运行后即可打开登录页面
MGH56I.png
输入账号:Admin,密码:123456进入后台主页
MG22Bd.png

使用教程

全局配置

在01.Coldairarrow.Util中的GlobalSwitch类中,设置了各个参数,其中RunModelDatabaseType需要重点关注一下,其它参数请看注释。

快速开发

此功能为本框架的核心功能,能够自动生产完整的可运行代码,具体使用如下:

  • 配置数据源

首选需要有数据库源,因为代码生成是根据数据库表来生成的。
菜单:开发=>数据库连接
MYpg8P.png
若列表中没有目标数据源,则添加数据库连接
MYphDg.png
数据连接名、连接字符串、数据库类型即可。添加完成后即可看到连接字符串信息。

  • 生成代码

有了数据库连接之后,即可进行代码生成。
菜单:开发=>代码生成

MYpb80.png

选择数据库,然后勾选需要生成代码的数据库表,点击生成代码会弹出生成选项(这里演示勾选 Base_BuildTest,其余表全是系统基础表,不要勾选,否则会被覆盖,导致异常,请勾选自己的业务表进行生成):

MYi3M6.png

生成选项中可以选择需要生成的类型,默认生成全部:实体层、业务层、接口层(即控制器)和页面(Vue前端页面代码)。
生成区域请输入业务模块名(例如系统叫Base_Manage),请按具体业务填入(必填)
这里示例填写TestManage,点击生成按钮,即可完成代码生成。生成后的代码在项目解决方案中,将代码文件包括进入项目

默认生成后的文件会被自动包括到解决方案中,若没有则需要点击显示所有文件按钮,即可看到生成后的新文件

生成的实体层、业务逻辑层、控制器层代码:
MYiWJs.png
MYFAfA.png
前端生成的代码:
MYiXWR.png

后端代码添加后需要重新编译下(F7),编译后好可以看到有新的接口
MYQYcD.png
前端生成代码后会自动保存并编译(别的文件修改保存也会自动编译,毕竟编译一次挺慢的),不放心可以Ctrl+C停止,然后再yarn run serve重新运行

代码生成完毕,但是要展示到菜单上需要进行配置,并且所有业务菜单都是动态的(权限控制)
打开菜单:系统管理=>权限管理=>新建
MYPsUJ.png
MYFUmT.png
菜单名:即需要显示的菜单名
上级菜单:菜单是多级树状的,可以放在某个菜单下面
类型:可以选择菜单或页面,这里是具体的页面,所以选页面
路径:页面的路径,菜单可以不配置,这里配置为/TestManage/Base_BuildTest/List,这里设置规则为:views文件夹为根路径(即"/"),向下展开依次为/TestManage/Base_BuildTest/List,最后真正的列表页为List.vue文件,表单页为EditForm.vue文件
是否需要权限:若为“否”,则此页面不限制权限,即所有人都能看
图标:菜单显示图标,具体到开发=>图标选择页进行选择
排序:若需要需要对菜单进行排序则设置,默认0,类型为int
页面权限:页面拥有的权限(权限值唯一,作为操作权限即接口权限的依据),详见权限管理

确认保存,然后刷新整个页面(F5),即可看到全新生成的菜单“生成测试”
MYkvqK.png
MYAFxI.png
MYAVqf.png

整个代码生成过程,无需编写代码即可完成一张表的CRUD,当然需要根据具体业务中进行相应的修改,本次示例中字段比较少,但是当一张表的字段很多时,那么此功能能够将开发效率提高几个档次。

管理员登录

MGH56I.png
默认超级管理员账号为:Admin
密码为:123456

系统用户管理

管理系统登录的用户
菜单:系统=>用户管理
点击右侧设置权限

系统角色管理

管理系统角色,角色是权限的载体,合理分配角色有利于权限管理
菜单:系统=>角色管理
操作中可以设置角色的权限,详情见 <权限管理> 模块

权限管理

一般情况下,后台管理系统多少会涉及权限管理,因此本框架提供了一个灵活、高效、简洁的权限管理系统。

首先,权限分为两种,即操作权限数据权限,其中操作权限主要包括菜单权限和按钮权限,在角色编辑表单中,给角色勾选需要的权限即可,用户可以分配多个角色,继承所有角色的权限。
MYET39.png
如上图,按需勾选,有人会疑问为什么只有增、改和删的权限而没有查的权限,其实这里考虑到了当勾选“用户管理”时,就已经默认拥有“查”的权限了,这里再设置“查”权限岂不是多此一举,可以根据实际业务需求添加诸如申请、审核等权限,灵活应用。
这里的树状是和菜单一一对应的,勾选哪些菜单就拥有哪些菜单

下面介绍下最常用的按钮权限
MYVTIS.png

如上图,在需要控制权限的按钮使用v-if="hasPerm('Base_User.Add')",表示只有当用户拥有权限值Base_User.Add才显示此按钮,权限值就是权限表单中配置的权限值

这里的按钮级权限控制只能够在前端控制操作入口,若系统对安全性要求较高,则需要控制接口权限
MYZNo8.png

如上图,在需要权限控制的接口加上ApiPermission特性即可,参数也为权限值,只有拥有此权限才能访问此接口

数据权限比较复杂,若采用纯SQL方式,那么会更加复杂,本框架全程采用EF作为ORM框架,通过对IQueryable< T >进行过滤,即可完成数据权限控制,详细使用方式见用户管理

更详细的使用方式,请参考源代码中的用户管理模块(菜单权限、操作权限、数据权限、联表查询、业务层AOP等使用方式均可参考此模块)

接口秘钥管理

作为对外接口签名的AppId和AppSecret管理
菜单:系统=>接口秘钥管理

系统日志

菜单:系统=>系统日志

单库事务

使用方式如下:

BaseBusiness<Base_UnitTest> _baseBus  = new BaseBusiness<Base_UnitTest>();
/*RunTransaction传入执行具体数据库操作的Action,操作中若出现异常会自动回滚事务,业务只需根据返回的transActionRes进行处理,返回类型为元组(bool Success, Exception ex),Success表示事务是否成功,ex为事务失败异常信息*/
var transActionRes = _baseBus.RunTransaction(() =>
{
    var newData = _newData.DeepClone();
    newData.Id = Guid.NewGuid().ToString();
    newData.UserId = IdHelper.GetId();
    newData.UserName = IdHelper.GetId();
    _baseBus.Insert(_newData);
    _baseBus.Insert(newData);
});

跨库事务

使用方式如下:

//第一个数据库
IRepository _bus1 = DbFactory.GetRepository();
//另一个数据库
IRepository _bus2 = DbFactory.GetRepository("BaseDb_Test");
_bus1.DeleteAll<Base_UnitTest>();
_bus2.DeleteAll<Base_UnitTest>();
Base_UnitTest data1 = new Base_UnitTest
{
    Id = Guid.NewGuid().ToString(),
    UserId = "1",
    UserName = Guid.NewGuid().ToString()
};
Base_UnitTest data2 = new Base_UnitTest
{
    Id = data1.Id,
    UserId = "1",
    UserName = Guid.NewGuid().ToString()
};
Base_UnitTest data3 = new Base_UnitTest
{
    Id = Guid.NewGuid().ToString(),
    UserId = "2",
    UserName = Guid.NewGuid().ToString()
};

new Action(() =>
{
    //创建并执行事务,使用方式与单库一致
    var succcess = DistributedTransactionFactory.GetDistributedTransaction(_bus1, _bus2)
        .RunTransaction(() =>
        {
            _bus1.ExecuteSql("insert into Base_UnitTest(Id) values('10') ");
            _bus1.Insert(data1);
            _bus1.Insert(data2);
            _bus2.Insert(data1);
            _bus2.Insert(data3);
        });
    Assert.AreEqual(succcess.Success, false);
    Assert.AreEqual(_bus1.GetIQueryable<Base_UnitTest>().Count(), 0);
    Assert.AreEqual(_bus2.GetIQueryable<Base_UnitTest>().Count(), 0);
})();

读写分离分库分表

本框架支持数据库读写分离分库分表(即Sharding),并且支持主流关系型数据库(SQLServer、Oracle、MySQL、PostgreSQL),理论上只要EF支持那么本框架支持。
由于技术原因以及结合实际情况,目前本框架仅支持单表的Sharding,即支持单表的CRUD、分页、统计(数量、最大值、最小值、平均值),支持跨库(表分散在不同的数据库中,不同类型数据库也支持)。具体如何使用如下:

  • Sharding配置
    首先、要进行分库分表操作,那么必要的配置必不可少。配置代码如下:
ShardingConfigBootstrapper.Bootstrap()
    //添加数据源
    .AddDataSource("BaseDb", DatabaseType.SqlServer, dbBuilder =>
    {
        //添加物理数据库
        dbBuilder.AddPhsicDb("BaseDb", ReadWriteType.ReadAndWrite);
    })
    //添加抽象数据库
    .AddAbsDb("BaseDb", absTableBuilder =>
    {
        //添加抽象数据表
        absTableBuilder.AddAbsTable("Base_UnitTest", tableBuilder =>
        {
            //添加物理数据表
            tableBuilder.AddPhsicTable("Base_UnitTest_0", "BaseDb");
            tableBuilder.AddPhsicTable("Base_UnitTest_1", "BaseDb");
            tableBuilder.AddPhsicTable("Base_UnitTest_2", "BaseDb");
        }, new ModShardingRule("Base_UnitTest", "Id", 3));
    });

上述代码中完成了Sharding的配置:
ShardingConfigBootstrapper.Bootstrap()在一个项目中只能执行一次,所以建议放到Application_Start中(ASP.NET Core中的Startup)
AddDataSource是指添加数据源,数据源可以看做抽象数据库,一个数据源包含了一组同类型的物理数据库,即实际的数据库。一个数据源至少包含一个物理数据库,多个物理数据库需要开启主从复制或主主复制,通过ReadWriteType(写、读、写和读)参数来指定数据库的操作类型,通常将写库作为主库,读库作为从库。同一个数据源中的物理数据库类型相同,表结构也相同。
配置好数据源后就可以通过AddAbsDb来添加抽象数据库,抽象数据库中需要添加抽象数据表。如上抽象表Base_UnitTest对应的物理表就是Base_UnitTest_0、Base_UnitTest_1与Base_UnitTest_2,并且这三张表都属于数据源BaseDb。分表配置当然需要分表规则(即通过一种规则找到具体数据在哪张表中)。
上述代码中使用了最简单的取模分片规则
源码如下:

可以看到其使用方式及优缺点。
另外还有一致性HASH分片规则

雪花Id的mod分片规则

上述的分片规则各有优劣,都实现IShardingRule接口,实际上只需要实现FindTable方法即可实现自定义分片规则。
实际使用中个人推荐使用雪花Id的mod分片规,这也是为什么前面数据库设计规范中默认使用雪花Id作为数据库主键的原因(PS,之前版本使用GUID作为主键被各种嫌弃,这次看你们怎么说)

  • 使用方式
    配置完成,下面开始使用,使用方式非常简单,与平常使用基本一致
    首先获取分片仓储接口IShardingRepository
IShardingRepository _db = DbFactory.GetRepository().ToSharding();

然后即可进行数据操作:

Base_UnitTest _newData  = new Base_UnitTest
{
    Id = Guid.NewGuid().ToString(),
    UserId = "Admin",
    UserName = "超级管理员",
    Age = 22
};
List<Base_UnitTest> _insertList = new List<Base_UnitTest>
{
    new Base_UnitTest
    {
        Id = Guid.NewGuid().ToString(),
        UserId = "Admin1",
        UserName = "超级管理员1",
        Age = 22
    },
    new Base_UnitTest
    {
        Id = Guid.NewGuid().ToString(),
        UserId = "Admin2",
        UserName = "超级管理员2",
        Age = 22
    }
};
//添加单条数据
_db.Insert(_newData);
//添加多条数据
_db.Insert(_insertList);
//清空表
_db.DeleteAll<Base_UnitTest>();
//删除单条数据
_db.Delete(_newData);
//删除多条数据
_db.Delete(_insertList);
//删除指定数据
_db.Delete<Base_UnitTest>(x => x.UserId == "Admin2");
//更新单条数据
_db.Update(_newData);
//更新多条数据
_db.Update(_insertList);
//更新单条数据指定属性
_db.UpdateAny(_newData, new List<string> { "UserName", "Age" });
//更新多条数据指定属性
_db.UpdateAny(_insertList, new List<string> { "UserName", "Age" });
//更新指定条件数据
_db.UpdateWhere<Base_UnitTest>(x => x.UserId == "Admin", x =>
{
    x.UserId = "Admin2";
});
//GetList获取表的所有数据
var list=_db.GetList<Base_UnitTest>();
//GetIQPagination获取分页后的数据
var list=_db.GetIShardingQueryable<Base_UnitTest>().GetPagination(pagination);
//Max
var max=_db.GetIShardingQueryable<Base_UnitTest>().Max(x => x.Age);
//Min
var min=_db.GetIShardingQueryable<Base_UnitTest>().Min(x => x.Age);
//Average
var min=_db.GetIShardingQueryable<Base_UnitTest>().Average(x => x.Age);
//Count
var min=_db.GetIShardingQueryable<Base_UnitTest>().Count();
//事务,使用方式与普通事务一致
bool succcess = _db.RunTransaction(() =>
{
    _db.Insert(_newData);
    var newData2 = _newData.DeepClone();
    _db.Insert(newData2);
}).Success;
Assert.AreEqual(succcess, false);

上述操作中表面上是操作Base_UnitTest表,实际上却在按照一定规则使用Base_UnitTest_0~2三张表,使分片对业务操作透明,极大提高开发效率
具体使用方式请参考单元测试源码:
"\src\Coldairarrow.UnitTests\DataRepository\ShardingTest.cs"

常见疑问

如何进行联表查询

框架使用EF+LINQ进行联表操作,核心在于对IQueryable< T >的使用,另可网上搜EF+LINQ的相关教程。

示例如下:
Base_User表左连接Base_Department表获取DepartmentName属性

//定义数据模型类
public class Base_UserTestDTO : Base_User
{
    public string DepartmentName { get; set; }
}

//即BaseBusiness中的Service
var db = DbFactory.GetRepository();
Expression<Func<Base_User, Base_Department, Base_UserTestDTO>> select = (a, b) => new Base_UserTestDTO
{
    DepartmentName = b.Name
};
select = select.BuildExtendSelectExpre();
var q = from a in db.GetIQueryable<Base_User>().AsExpandable()
        join b in db.GetIQueryable<Base_Department>() on a.DepartmentId equals b.Id into ab
        from b in ab.DefaultIfEmpty()
        select @select.Invoke(a, b);
//筛选
var where = LinqHelper.True<Base_UserTestDTO>();
where = where.And(x => x.UserName == "Admin");

//筛选并获取分页数据
var list = q.Where(where).GetPagination(new Pagination()).ToList();

源码可参考Base_UserBusiness.GetDataList

如何切换数据库类型

在01.Coldairarrow.Util项目中的GlobalSwitch,将DatabaseType改为需要的即可,对应的数据库连接字符串当然也要改为对应数据库的
MYK1bR.png

如何使用多个数据库

To override the parent class constructor in a particular BaseBusiness Business class, according to their own needs to rewrite the corresponding constructor, and the need to ensure that the database connection string has been added

MYMFzD.png

MYMVLd.png

If you need to use multiple databases, or need multi-threaded database operation, you need to use
MYMsOJ.png

Epilogue

Welcome to this framework, if it feels good, your mind than

Github welcome Stars: https://github.com/Coldairarrow

Welcome to Point Park Chan blog: https://www.cnblogs.com/coldairarrow/

QQ group 2: 579 202 910
Personal QQ: 862520575 ( welcome technical support and business cooperation, providing .NET Core + Linux + Nginx + jenkins + git package of integrated continuous rapid development platform )

It will be rapid development framework for the continuous improvement and maintenance, hoping to help to you

If you have any questions or need technical support, please contact me.

------ learning never-ending, never-cap technology, the code is art ------

Guess you like

Origin www.cnblogs.com/coldairarrow/p/11870993.html