如何使用2个不同的连接字符串读和写在postgre与CQRS?



在我们的项目中,我们使用。net 5.0与CQRS和postgre。我们所有的应用都是容器化的,在kubernetes上运行。我们有硕士研究生。从节点配置pgpool(用于写),对于读,它直接从从节点读取,但pgpool配置在主节点之前。

是否可以配置为CQRS (MediatR)使用一个连接读和写的另一个连接吗?

我的DI配置如下:

services.AddDbContext<DataContext>(opt =>
{
opt.EnableDetailedErrors();
opt.UseLazyLoadingProxies();
opt.UseNpgsql(configuration.GetConnectionString("TaikunConnection"),
options =>
{
options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
options.EnableRetryOnFailure();
options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
});
});
services.AddScoped<IDataContext>(provider => provider.GetService<DataContext>());
var builder = services.AddIdentityCore<User>()
.AddEntityFrameworkStores<DataContext>();
var identityBuilder = new IdentityBuilder(builder.UserType, builder.Services);
identityBuilder.AddSignInManager<SignInManager<User>>();
identityBuilder.AddUserManager<UserManager<User>>();

您可以使用2种不同的数据库上下文:

services.AddDbContext<DataWriteContext>(opt =>
{
opt.EnableDetailedErrors();
opt.UseLazyLoadingProxies();
opt.UseNpgsql(configuration.GetConnectionString("TaikunConnectionForWrite"),
options =>
{
options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
options.EnableRetryOnFailure();
options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
});
});
services.AddDbContext<DataReadContext>(opt =>
{
opt.EnableDetailedErrors();
opt.UseLazyLoadingProxies();
opt.UseNpgsql(configuration.GetConnectionString("TaikunConnectionForRead"),
options =>
{
options.MigrationsAssembly(typeof(DataContext).Assembly.FullName);
options.EnableRetryOnFailure();
options.CommandTimeout((int)TimeSpan.FromMinutes(10).TotalSeconds);
});
});

最新更新