在我的
ASP.NET Core
项目中,使用 PostgreSQL
作为数据库和 Entity Framework Core 进行数据访问,我遇到了一个反复出现的问题。我时常收到以下错误消息:
{"Message":"An error occurred while processing your request.","ExceptionMessage":"53300: too many connections for role \"yxyjmsin\"","ExceptionType":"Npgsql.PostgresException"}
{"Message":"An error occurred while processing your request.","ExceptionMessage":"An exception has been raised that is likely due to a transient failure.","ExceptionType":"System.InvalidOperationException"}
此错误似乎与打开的数据库连接数量过多有关。我尝试了各种配置和代码更改,但我仍然在努力找出根本原因并解决问题。
这就是我在我的
Program.cs
中添加dbcontext的方式
builder.Services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
var builder = new NpgsqlDataSourceBuilder(configuration.GetConnectionString("ElephantSQL"));
options.UseNpgsql(builder.ConnectionString, npgsqlOptions =>
{
npgsqlOptions.EnableRetryOnFailure();
npgsqlOptions.MaxBatchSize(5);
});
builder.MapEnum<UserRole>();
builder.MapEnum<OrderStatus>();
options.AddInterceptors(new TimeStampInterceptor());
options.UseNpgsql(builder.Build()).UseSnakeCaseNamingConvention();
});
"ConnectionStrings": {
"ElephantSQL": "Server=myServer;Port=5432;Username=yxyjmsin;Password=myPasswd;Database=myDb Pooling=true;"
},
在我的基础存储库中使用 applicationdbcontext
public async Task<TEntity> AddAsync(TEntity entity)
{
try
{
if (entity is User userEntity)
{
if (userEntity.Role != UserRole.Admin)
{
userEntity.Role = UserRole.Customer;
}
}
var entry = await _dbSet.AddAsync(entity);
await _applicationDbContext.SaveChangesAsync();
return entry.Entity;
}
catch (DbUpdateException ex)
{
Console.WriteLine("Base Repository exception.");
if (ex.InnerException != null)
{
Console.WriteLine("Inner exception: " + ex.InnerException.Message);
}
throw;
}
}
我在
ApplicationDbContext
文件中配置了数据库,但移至 Program.cs
,希望它能够解决暂时性问题,但事实并非如此。
我检查了
rolconnlimit
为 5,因此将 maxbatchsize
设置为 5。
我在数据库连接配置中启用了失败重试,并在控制台中注意到此错误: 异常数据:
Severity: FATAL
SqlState: 53300
MessageText: too many connections for role "yxyjmsin"
File: miscinit.c
Line: 734
Routine: InitializeSessionUserId
您能帮我解决代码中的这个问题吗?
预先感谢您的协助!
您的代码可能存在以下几个问题:
您的连接字符串似乎不太好。您之前错过了
;
Pooling=true
更改连接字符串以获得更多有关池的选项,例如:
Server=myServer;Port=5432;Username=yxyjmsin;Password=myPasswd;Database=myDb;Pooling=true;Min Pool Size=0;Max Pool Size=100;
如果这些不起作用,请尝试不使用池的连接字符串:
Server=myServer;Port=5432;Username=yxyjmsin;Password=myPasswd;Database=myDb;
并且也不使用批处理配置:
builder.Services.AddDbContext<ApplicationDbContext>((serviceProvider, options) =>
{
var configuration = serviceProvider.GetRequiredService<IConfiguration>();
var builder = new NpgsqlDataSourceBuilder(configuration.GetConnectionString("ElephantSQL"));
options.UseNpgsql(builder.ConnectionString, npgsqlOptions => npgsqlOptions.EnableRetryOnFailure(3));
builder.MapEnum<UserRole>();
builder.MapEnum<OrderStatus>();
options.AddInterceptors(new TimeStampInterceptor());
options.UseNpgsql(builder.Build()).UseSnakeCaseNamingConvention();
});