ABP微服务系列学习-搭建自己的微服务结构(四)
上篇我们实现了认证服务和网关服务,基本我们的基础服务已经完成了,接下来我们才需要做服务的数据迁移。
这里我们需要使用EF的CodeFirst模式。通过DotnetCli的命令去操作:
dotnet ef migrations add init
修改项目
编辑我们每个服务的EfCore项目的项目文件,添加Microsoft.EntityFrameworkCore.Tools的依赖,也可以通过VS的nuget包管理器安装。只有添加了这个依赖,我们才能使用dotnet ef命令。
在项目文件中添加如下内容:
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
只添加这个依赖还不行,若直接运行dotnet ef命令的话,会提示我们需要实现一个DbContextFactory类。
所以我们在每个服务的EFCore项目中都添加一个DbContextFactory类,类结构如下,每个服务对应修改一下名字即可
using System.IO;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Design;
using Microsoft.Extensions.Configuration;
using Volo.Abp;
namespace FunShow.AdministrationService.EntityFrameworkCore.EntityFrameworkCore
{
/* This class is needed for EF Core console commands
* (like Add-Migration and Update-Database commands)
* */
public class AdministrationServiceDbContextFactory : IDesignTimeDbContextFactory<AdministrationServiceDbContext>
{
private readonly string _connectionString;
/* This constructor is used when you use EF Core tooling (e.g. Update-Database) */
public AdministrationServiceDbContextFactory()
{
_connectionString = GetConnectionStringFromConfiguration();
}
/* This constructor is used by DbMigrator application */
public AdministrationServiceDbContextFactory([NotNull] string connectionString)
{
Check.NotNullOrWhiteSpace(connectionString, nameof(connectionString));
_connectionString = connectionString;
}
public AdministrationServiceDbContext CreateDbContext(string[] args)
{
AdministrationServiceEfCoreEntityExtensionMappings.Configure();
var builder = new DbContextOptionsBuilder<AdministrationServiceDbContext>()
.UseNpgsql(_connectionString, b =>
{
b.MigrationsHistoryTable("__AdministrationService_Migrations");
});
return new AdministrationServiceDbContext(builder.Options);
}
private static string GetConnectionStringFromConfiguration()
{
return BuildConfiguration()
.GetConnectionString(AdministrationServiceDbProperties.ConnectionStringName);
}
private static IConfigurationRoot BuildConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(
Path.Combine(
Directory.GetCurrentDirectory(),
$"..{Path.DirectorySeparatorChar}FunShow.AdministrationService.HttpApi.Host"
)
)
.AddJsonFile("appsettings.json", optional: false);
return builder.Build();
}
}
}
然后我们就可以执行dotnet ef migrations add init生成数据迁移文件了。
实现DbMigrator迁移程序
使用DbMigrator迁移程序可以一次性执行多个服务的迁移任务,当然我们也可以每个服务单独去执行dotnet ef database update这个命令,如果不嫌麻烦的话。
同时DbMigrator程序可以添加一些初始化数据的DataSeeder。
在前面我们DbMigrator只是创建了个项目,并没有实现功能,接下来我们就需要实现DbMigrator了。
第一步当然是修改项目文件添加我们的项目依赖,我们需要添加每个服务的EntityFrameworkCore和Application.Contracts项目,以及Shared.Hosting项目,当然最重要是需要Microsoft.EntityFrameworkCore.Tools,不然无法执行迁移命令。完整项目文件内容如下:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting" Version="7.0.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.1" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\FunShow.Shared.Hosting\FunShow.Shared.Hosting.csproj" />
<ProjectReference Include="..\..\services\administration\src\FunShow.AdministrationService.Application.Contracts\FunShow.AdministrationService.Application.Contracts.csproj" />
<ProjectReference Include="..\..\services\administration\src\FunShow.AdministrationService.EntityFrameworkCore\FunShow.AdministrationService.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\..\services\identity\src\FunShow.IdentityService.EntityFrameworkCore\FunShow.IdentityService.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\..\services\identity\src\FunShow.IdentityService.Application.Contracts\FunShow.IdentityService.Application.Contracts.csproj" />
<ProjectReference Include="..\..\services\logging\src\FunShow.LoggingService.EntityFrameworkCore\FunShow.LoggingService.EntityFrameworkCore.csproj" />
<ProjectReference Include="..\..\services\logging\src\FunShow.LoggingService.Application.Contracts\FunShow.LoggingService.Application.Contracts.csproj" />
</ItemGroup>
<ItemGroup>
<None Remove="appsettings.json" />
<Content Include="appsettings.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
<None Remove="appsettings.secrets.json" />
<Content Include="appsettings.secrets.json">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Content>
</ItemGroup>
</Project>
根据ABP的Console模板,我们需要添加一个HostedService文件和Module文件,当然也可以直接新建一个ABP的console模板来操作。
在module文件中添加DepensOn依赖
[DependsOn(
typeof(FunShowSharedHostingModule),
typeof(IdentityServiceEntityFrameworkCoreModule),
typeof(IdentityServiceApplicationContractsModule),
typeof(LoggingServiceEntityFrameworkCoreModule),
typeof(LoggingServiceApplicationContractsModule),
typeof(AdministrationServiceEntityFrameworkCoreModule),
typeof(AdministrationServiceApplicationContractsModule)
)]
public class FunShowDbMigratorModule : AbpModule
{
}
实现DbMigrationService
DbMigrationService负责执行我们的数据迁移文件以及初始化种子数据。完整的内容如下:
using FunShow.AdministrationService.EntityFrameworkCore;
using FunShow.IdentityService;
using FunShow.IdentityService.EntityFrameworkCore;
using FunShow.LoggingService.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.EntityFrameworkCore;
using Volo.Abp.Identity;
using Volo.Abp.MultiTenancy;
using Volo.Abp.TenantManagement;
using Volo.Abp.Uow;
namespace FunShow.DbMigrator;
public class FunShowDbMigrationService : ITransientDependency
{
private readonly ILogger<FunShowDbMigrationService> _logger;
private readonly ITenantRepository _tenantRepository;
private readonly IDataSeeder _dataSeeder;
private readonly ICurrentTenant _currentTenant;
private readonly IUnitOfWorkManager _unitOfWorkManager;
public FunShowDbMigrationService(
ILogger<FunShowDbMigrationService> logger,
ITenantRepository tenantRepository,
IDataSeeder dataSeeder,
ICurrentTenant currentTenant,
IUnitOfWorkManager unitOfWorkManager)
{
_logger = logger;
_tenantRepository = tenantRepository;
_dataSeeder = dataSeeder;
_currentTenant = currentTenant;
_unitOfWorkManager = unitOfWorkManager;
}
public async Task MigrateAsync(CancellationToken cancellationToken)
{
await MigrateHostAsync(cancellationToken);
await MigrateTenantsAsync(cancellationToken);
_logger.LogInformation("Migration completed!");
}
private async Task MigrateHostAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Migrating Host side...");
await MigrateAllDatabasesAsync(null, cancellationToken);
await SeedDataAsync();
}
private async Task MigrateTenantsAsync(CancellationToken cancellationToken)
{
_logger.LogInformation("Migrating tenants...");
var tenants =
await _tenantRepository.GetListAsync(includeDetails: true, cancellationToken: cancellationToken);
var migratedDatabaseSchemas = new HashSet<string>();
foreach (var tenant in tenants)
{
using (_currentTenant.Change(tenant.Id))
{
// Database schema migration
var connectionString = tenant.FindDefaultConnectionString();
if (!connectionString.IsNullOrWhiteSpace() && //tenant has a separate database
!migratedDatabaseSchemas.Contains(connectionString)) //the database was not migrated yet
{
_logger.LogInformation($"Migrating tenant database: {tenant.Name} ({tenant.Id})");
await MigrateAllDatabasesAsync(tenant.Id, cancellationToken);
migratedDatabaseSchemas.AddIfNotContains(connectionString);
}
//Seed data
_logger.LogInformation($"Seeding tenant data: {tenant.Name} ({tenant.Id})");
await SeedDataAsync();
}
}
}
private async Task MigrateAllDatabasesAsync(
Guid? tenantId,
CancellationToken cancellationToken)
{
using (var uow = _unitOfWorkManager.Begin(requiresNew: true, isTransactional: false))
{
await MigrateDatabaseAsync<AdministrationServiceDbContext>(cancellationToken);
await MigrateDatabaseAsync<IdentityServiceDbContext>(cancellationToken);
await MigrateDatabaseAsync<LoggingServiceDbContext>(cancellationToken);
await uow.CompleteAsync(cancellationToken);
}
_logger.LogInformation(
$"All databases have been successfully migrated ({(tenantId.HasValue ? $"tenantId: {tenantId}" : "HOST")}).");
}
private async Task MigrateDatabaseAsync<TDbContext>(
CancellationToken cancellationToken)
where TDbContext : DbContext, IEfCoreDbContext
{
_logger.LogInformation($"Migrating {typeof(TDbContext).Name.RemovePostFix("DbContext")} database...");
var dbContext = await _unitOfWorkManager.Current.ServiceProvider
.GetRequiredService<IDbContextProvider<TDbContext>>()
.GetDbContextAsync();
await dbContext
.Database
.MigrateAsync(cancellationToken);
}
private async Task SeedDataAsync()
{
await _dataSeeder.SeedAsync(
new DataSeedContext(_currentTenant.Id)
.WithProperty(IdentityDataSeedContributor.AdminEmailPropertyName,
IdentityServiceDbProperties.DefaultAdminEmailAddress)
.WithProperty(IdentityDataSeedContributor.AdminPasswordPropertyName,
IdentityServiceDbProperties.DefaultAdminPassword)
);
}
}
MigrateDatabaseAsync方法负责执行我们之前生成的迁移文件,SeedDataAsync则负责执行初始化我们项目中的种子数据。
后续添加更多的服务,我们只需要在MigrateAllDatabasesAsync中添加我们服务对应的DBContext文件即可。
初始化种子数据
上面说了DbMigrationService可以负责执行初始化种子数据。
根据我们需要添加一个DataSeedContributor和DataSeeder类。
这里我们初始化一下OpenIddict的种子数据。
using System.Threading.Tasks;
using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
namespace FunShow.DbMigrator;
public class OpenIddictDataSeedContributor : IDataSeedContributor, ITransientDependency
{
private readonly OpenIddictDataSeeder _openIddictDataSeeder;
public OpenIddictDataSeedContributor(OpenIddictDataSeeder openIddictDataSeeder)
{
_openIddictDataSeeder = openIddictDataSeeder;
}
public async Task SeedAsync(DataSeedContext context)
{
await _openIddictDataSeeder.SeedAsync();
}
}
主要是继承并实现IDataSeedContributor接口,这个接口会在DbMigrationService中获取并执行SeedAsync方法。
OpenIddictDataSeeder执行的初始化数据太多,这里就不贴代码了。主要就是读取配置文件的Applications和Resources初始化写进数据库。
编辑appsettings.json文件
在配置文件中添加数据库连接字符串和OpenIddict配置
{
"ConnectionStrings": {
"AdministrationService": "Host=localhost;Port=5432;User ID=postgres;password=myPassw0rd;Pooling=true;Database=FunShow_Administration;",
"IdentityService": "Host=localhost;Port=5432;User ID=postgres;password=myPassw0rd;Pooling=true;Database=FunShow_Identity;",
"LoggingService": "Host=localhost;Port=5432;User ID=postgres;password=myPassw0rd;Pooling=true;Database=FunShow_LoggingService;"
},
"OpenIddict": {
"Applications": {
"FunShow_Vue": {
"RootUrl": "http://localhost:4200"
},
"WebGateway": {
"RootUrl": "https://localhost:44325"
}
},
"Resources": {
"AccountService": {
"RootUrl": "https://localhost:44322"
},
"IdentityService": {
"RootUrl": "https://localhost:44388"
},
"AdministrationService": {
"RootUrl": "https://localhost:44367"
},
"LoggingService": {
"RootUrl": "https://localhost:45124"
}
}
}
}
到这我们的DbMigrator迁移程序也实现完了,后续添加新服务也只需要添加修改对应的地方,然后执行程序即可。
执行之后我们会生成3个数据库,里面也包含我们的种子数据。
到这我们基本完成了微服务的搭建。
ABP微服务系列学习-搭建自己的微服务结构(四)的更多相关文章
- springcloud微服务架构搭建
SpringCloud微服务框架搭建 一.微服务架构 1.1什么是分布式 不同模块部署在不同服务器上 作用:分布式解决网站高并发带来问题 1.2什么是集群 多台服务器部署相同应用构成一个集群 作用:通 ...
- SprngCloud微服务框架搭建(一)
参照来源 :https://blog.csdn.net/forezp/article/details/70148833 1.简介 目前来说,SpringCloud是比较完整的微服务解决方案框架.不像其 ...
- Spring Cloud 微服务中搭建 OAuth2.0 认证授权服务
在使用 Spring Cloud 体系来构建微服务的过程中,用户请求是通过网关(ZUUL 或 Spring APIGateway)以 HTTP 协议来传输信息,API 网关将自己注册为 Eureka ...
- 【spring colud】spring cloud微服务项目搭建【spring boot2.0】
spring cloud微服务项目搭建 =================================== 示例版本: 1.spring boot 2.0版本 2.开发工具 IntellJ IDE ...
- 简单Spring Cloud 微服务框架搭建
微服务是现在比较流行的技术,对于程序猿而言,了解并搭建一个基本的微服务框架是很有必要滴. 微服务包含的内容非常多,一般小伙伴们可以根据自己的需求不断添加各种组件.框架. 一般情况下,基本的微服务框架包 ...
- java架构之路-(微服务专题)初步认识微服务与nacos初步搭建
历史演变: 以前我们都是一个war包,包含了很多很多的代码,反正我开始工作的时候做的就是这样的项目,一个金融系统,代码具体多少行记不清楚了,内部功能超多,但是实际能用到的不多,代码冗余超大,每次部署大 ...
- 十一、Docker搭建部署SpringCloud微服务项目Demo
环境介绍 技术选型:SpringCloud&SpringCloud Alibaba&Docker 微服务模块划分: 员工模块:ems-employees 部门模块:ems-depart ...
- SpringCloudAlibaba 微服务讲解(二)微服务环境搭建
微服务环境搭建 我们这次是使用的电商项目的商品.订单.用户为案例进行讲解 2.1 案例准备 2.1.1 技术选型 maven :3.3.9 数据库:mysql 持久层:SpringData JPA S ...
- (3)go-micro微服务项目搭建
目录 一 微服务项目介绍 二 go-micro安装 1.拉取micro镜像 2.生成项目目录 三 项目搭建 使用DDD模式开发项目: 四 最后 一 微服务项目介绍 账户功能是每一个系统都绕不开的一部分 ...
- springCloud 微服务框架搭建入门(很简单的一个案例不喜勿扰)
Spring cloud 实现服务注册及发现 服务注册与发现对于微服务系统来说非常重要.有了服务发现与注册,你就不需要整天改服务调用的配置文件了,你只需要使用服务的标识符,就可以访问到服务. clou ...
随机推荐
- .net做一个基于ChatGpt的微信机器人吧~[全教程]
最近这个ChatGPT很火啊,看了B站上很多视频,自己非常手痒,高低自己得整一个啊,很多人都是把ChatGPT和微信结合在一起,正巧我是Wechaty框架的.net sdk贡献者,这不是一应俱全了吗? ...
- week_8
Andrew Ng 机器学习笔记 ---By Orangestar Week_7_Unsupervised Learning While supervised learning algorithms ...
- Hadoop详解(02)Hadoop集群运行环境搭建
Hadoop详解(02)Hadoop集群运行环境搭建 虚拟机环境准备 虚拟机节点数:3台 操作系统版本:CentOS-7.6-x86-1810 虚拟机 内存4G,硬盘99G IP地址分配 192.16 ...
- [WPF]鼠标移动到Button颜色改变效果设置
代码 <Style x:Key="Button_Menu" TargetType="{x:Type Button}"> <Setter Pro ...
- 【Vue3.0】关于 script setup 语法糖的用法
script setup - 简介 先来看一看官网关于 <script setup> 的介绍: 要彻底的了解 setup 语法糖,你必须先明确 setup() 这个 组合式API 官网中对 ...
- CentOS7.6系统安装和网络配置
CentOS7.6系统安装配置 前言:文章内容可能会因环境不同而有所差异,所谓集思广益说不定灵感就来了呢; 文章初衷旨在交流学习.记录个人成长,如果能帮助到您,那就点个赞噢. 环境说明: 1.本实验使 ...
- 保姆级手把手图文并茂教你配置MAC系统Flutter环境
Flutter 是什么 Flutter是Google开源的构建用户界面(UI)工具包,帮助开发者通过一套代码库高效构建多平台精美应用,支持移动.Web.桌面和嵌入式平台.Flutter 开源.免费,拥 ...
- 深入Typescript--01-使用roolup编译Typescript
Typescript是什么? TypeScript是Javascript的超集,遵循最新的ES5/ES6规范.Typescript扩展了Javascript语法. 为什么要用Typescript? 1 ...
- nodejs 升级后, vue+webpack 项目 node-sass 报错的解决方法
1.npm i node-sass -D 在错误提示里有给出了方案,重新构建 node-sass,命令如下: npm rebuild node-sass --force 如果执行完成后不报错,就可以了 ...
- 修改hosts文件需要vi命令
i 在光标前插入. 保存 按esc后 shift+: 输入wq! 保存