车神ne的博客

.Net技术分享站

导航

ABP vNext微服务架构详细教程——基础服务层

1. 创建服务

在除身份管理相关服务以外的其他业务服务中,我们不需要包含用户角色权限管理功能模块,ABP vNext框架为我们提供了模块模式,其默认模板不包含身份管理相关模块,更适合用于搭建普通的业务微服务。以产品管理服务为例,我们在解决方案目录中找到service目录,在其中创建productmanager目录,切换至该目录并启动cmd命令行。使用以下命令创建产品管理服务:

abp new Demo.ProductManager -t module --no-ui

其中-t module表示模块模式,--no-ui表示不使用UI界面,在ABP vNext框架Module模式下一直存在一个问题,创建时无法和Application一样使用-dbms参数设置数据库类型,而是使用默认的SQL Server数据库类型,这里我们的项目采用MySQL数据库,需要手动修改为MySQL,具体方法见下一章节。

因为我们身份认证服务采用统一的服务,所以我们在生成的模板中找到host目录下的ProductManager.IdentityServer项目文件夹并删除,数据库我们不使用MongoDB,所以可以将src目录下的ProductManager.MongoDB项目文件夹和test目录下的ProductManager.MongoDB.Tests项目文件夹删除。之后我们可以删除该项目根目录下database文件夹和除Demo.ProductManager.sln、common.props以外的所有文件,如果不需要对该项目进行单元测试,也可删除test文件夹。

清理后,跳转到总解决方案所在目录,使用解决方案构建工具将个产品管理服务所有项目添加到总解决方案,添加后效果如下:

 

2. 切换为MySQL数据库

将Module模式项目从SQL Server数据库更改为MySQL数据库步骤如下:

  1. 找到ProductManager.HttpApi.Host项目移除其Nuget引用中的Volo.Abp.EntityFrameworkCore.SqlServer,然后添加Nuget引用Volo.Abp.EntityFrameworkCore.MySQL,注意版本号和主项目ABP框架版本一致。
  2. 找到ProductManager.HttpApi.Host项目中的模块类ProductManagerHttpApiHostModule,将其特性DependsOn特性中引用的 typeof(AbpEntityFrameworkCoreSqlServerModule) 更改为 typeof(AbpEntityFrameworkCoreMySQLModule) 并将其命名空间引用 using Volo.Abp.EntityFrameworkCore.SqlServer; 改为 using Volo.Abp.EntityFrameworkCore.MySQL; 。将ConfigureServices方法的
    Configure<AbpDbContextOptions>(options => { options.UseSqlServer(); }); 改为 Configure<AbpDbContextOptions>(options => { options.UseMySQL(); });
  3. 找到ProductManager.HttpApi.Host项目中的ProductManagerHttpApiHostMigrationsDbContextFactory类,将其方法CreateDbContext中的 var builder = new DbContextOptionsBuilder<ProductManagerHttpApiHostMigrationsDbContext>() .UseSqlServer(configuration.GetConnectionString("ProductManager")); 改为以下代码(注意我的MySQL版本为5.7,具体版本号请依据个人情况修改):
    var builder = new DbContextOptionsBuilder<ProductManagerHttpApiHostMigrationsDbContext>()
      .UseMySql(configuration.GetConnectionString("ProductManager"),ServerVersion.Parse("5.7.28-mysql"));
  4. 修改Demo.ProductManager.HttpApi.Host项目的appsettings.json配置文件,和Application模式不同,我们会发现Module模式下ABP vNext框架提供的项目模板ConnectionStrings项会包含Default和ProductManager两个配置项。其中Default为ABP框架基础配置信息的数据库,身份管理服务已包含其所需的所有数据,所以我们将Default配置为和身份管理中心相同的数据库链接。ProductManger也就是和当前项目相同的数据库配置项,所指向的数据库为对当前模块领域实体持久化的数据库,需要在当前项目中配置和创建。
  5. 进入Demo.ProductManager.HttpApi.Host项目所在目录,执行数据迁移命令 dotnet-ef database update ,执行成功后查看数据库,发现已创建模块数据库,且仅包含__EFMigrationsHistory表,则数据库链接成功。

3.初始化运行

在Demo.ProductManager.Application、Demo.ProductManager.Application.Contracts、Demo.ProductManager.HttpApi三个项目中分别找到Samples文件夹并删除,这是ABP vNext提供的样例API,没有实际用途。

设置端口号为5010并允许IP地址访问,方式为在Demo.ProductManager.HttpApi.Host项目配置文件appsettings.json中添加配置项: "urls": "http://*:5010" 

上一章节我们已经配置了数据库链接字符串,我们继续编辑Demo.ProductManager.HttpApi.Host项目配置文件appsettings.json,设置Redis链接字符串。

启动Demo.ProductManager.HttpApi.Host项目并访问http://localhost:5010/swagger/index.html,可以正常显示Swagger页面,即启动成功。

4.产品管理API

4.1. 领域层

在Demo.ProductManager.Domain项目中添加Products文件夹(产品领域)并创建Product类(产品聚合根)代码如下:

using System;
using Volo.Abp.Domain.Entities;

namespace Demo.ProductManager.Products;

/// <summary>
/// 产品
/// </summary>
public class Product : AggregateRoot<Guid>
{
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 价格
    /// </summary>
    public float Price { get; set; }
}

4.2. 数据库创建

在Demo.ProductManager.EntityFrameworkCore项目中找到IProductManagerDbContext接口和ProductManagerDbContext类,分别添加 DbSet<Product> Products { get; set; } 和 public DbSet<Product> Products { get; set; } 属性并添加响应引用。

在Demo.ProductManager.EntityFrameworkCore项目中找到ProductManagerDbContextModelCreatingExtensions类中的ConfigureProductManager方法内添加以下内容:

builder.Entity<Product>(b =>
{
  b.ToTable(ProductManagerDbProperties.DbTablePrefix + "Products", ProductManagerDbProperties.DbSchema);
  b.ConfigureByConvention();
});

这里使用实体类默认设置,如果需要进行自定义修改,可自行编辑实体配置。

在Demo.ProductManager.HttpApi.Host项目所在目录中执行创建数据迁移语句:

dotnet-ef migrations Add BuildProduct

创建成功后执行数据迁移:

dotnet-ef database update

执行成功后,我们可以再ProductManager模块数据库中看到已新增数据库表Product,此表中除主键ID和我们自己定义的两个字段以外,如果Product继承自AggregateRoot,则会包含ExtraProperties和ConcurrencyStamp两个字段,分别为扩展属性和并发戳。若继承自Entity则默认不会包含这两个字段。

4.3. 应用层

为方便演示,本实例采用CrudAppService,对Product提供增删改查接口,具体实现方式如下:

在Demo.ProductManager.Application.Contracts项目中创建Products文件夹并在其中创建Dto文件夹。在Dto文件夹中存放产品管理的数据传输对象,这里增改查接口统一使用ProductDto,代码如下:

using System;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Entities;

namespace Demo.ProductManager.Products.Dto;

/// <summary>
/// 产品DTO
/// </summary>
public class ProductDto : EntityDto<Guid>, IHasConcurrencyStamp
{
    /// <summary>
    /// 名称
    /// </summary>
    public string Name { get; set; }

    /// <summary>
    /// 价格
    /// </summary>
    public float Price { get; set; }
    /// <summary>
    /// 并发戳
    /// </summary>
    public string ConcurrencyStamp { get; set; }
}

 

这里因为我们使用聚合根,修改数据时需要提供并发戳ConcurrencyStamp,但EntityDto中并未提供该字段,所以需继承IHasConcurrencyStamp接口。

在Demo.ProductManager.Application.Contracts项目Products文件夹下添加产品管理应用服务接口IProductAppService如下:

using System;
using Demo.ProductManager.Products.Dto;
using Volo.Abp.Application.Services;

namespace Demo.ProductManager.Products;

/// <summary>
/// 产品管理应用服务接口
/// </summary>
public interface IProductAppService : ICrudAppService<ProductDto, Guid>
{

}

 在Demo.ProductManager.Application项目中添加Products文件夹,添加应用服务类ProductAppService如下:

using System;
using Demo.ProductManager.Products.Dto;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;

namespace Demo.ProductManager.Products;

/// <summary>
/// 产品管理应用服务
/// </summary>
public class ProductAppService:CrudAppService<Product,ProductDto,Guid>,IProductAppService
{
    public ProductAppService(IRepository<Product, Guid> repository) : base(repository)
    {
        
    }
}

为方便多个领域下AutoMapper映射关系的管理,我在每个领域单独创建一个静态类,以扩展方法的方式编写当前领域的对象映射关系。例如在当前Products领域中,在Demo.ProductManager.Application项目中Products文件夹下添加静态类ProductAutoMapperProfile如下:

using Demo.ProductManager.Products.Dto;

namespace Demo.ProductManager.Products;

public static class ProductAutoMapperProfile
{
    public static void CreatProductMapper(this ProductManagerApplicationAutoMapperProfile profile)
    {
        profile.CreateMap<Product, ProductDto>();
        profile.CreateMap<ProductDto, Product>();
    }
}

之后,就可以在ProductManagerApplicationAutoMapperProfile类的ProductManagerApplicationAutoMapperProfile方法中增加以下代码:

this.CreatProductMapper();

通常情况,DTO和实体的字段并非完全一一对应,我们需要再映射过程中忽略映射关系的校验,具体方法为将ProductManagerApplicationModule类中ConfigureServices方法下  Configure<AbpAutoMapperOptions>(options => { options.AddMaps<ProductManagerApplicationModule>(validate: true); }); 这一句validate参数值改为false

4.4其他处理

ABP vNext框架Module模式模板默认未开启动态WebAPI,需要我们手动启用动态WebAPI,具体方式为在Demo.ProductManager.HttpApi.Host项目的ProductManagerHttpApiHostModule类ConfigureServices方法中添加以下代码:

Configure<AbpAspNetCoreMvcOptions>(options =>
{
  options
    .ConventionalControllers
    .Create(typeof(ProductManagerApplicationModule).Assembly);
});

通常情况,我们使用的仓储为ABP vNext框架提供的默认仓储实现,我们需要一次性添加所有默认仓储,具体方法为在Demo.ProductManager.EntityFrameworkCore项目中ProductManagerEntityFrameworkCoreModule类的ConfigureServices方法中,找到 context.Services.AddAbpDbContext<ProductManagerDbContext>(…… ,在其中添加options.AddDefaultRepositories();修改为:

context.Services.AddAbpDbContext<ProductManagerDbContext>(options =>
{
    /* Add custom repositories here. Example:
     * options.AddRepository<Question, EfCoreQuestionRepository>();
    */
    options.AddDefaultRepositories();
}); 

完成以上修改后,运行Demo.ProductManager.HttpApi.Host项目并打开http://localhost:5010/swagger/index.html,可显示Swagger页面并包含,Product相关增删改查接口,可通过Swagger页面完成测试。

posted on 2022-02-21 16:35  车神ne  阅读(2485)  评论(0编辑  收藏  举报