在使用Hangfire排队和处理后台作业时,我能够导致发生可重现的内存不足异常。
这些作业是简单的Console.WriteLine
调用,所以我不希望堆内存增加它的方式。
我是否配置不正确或者我应该考虑提交问题?
结果(VMMap)
使用 Redis 作为 Jobs 的后备存储:
- 开始时,总堆 = 29,088K;
- 在 5,000 个工作岗位之后,938,672K;
- 6,000 个工作岗位,1,056,004K;
- 7,000 个工作岗位,1,219,296K;
- 8,000 个工作,堆值不存在;
- 在 100 多个作业中,
iisexpress.exe
实例崩溃。
使用 SQL 存储的限制要高得多 ~= 15,000 个作业。
设置
- 空的 ASP.NET 项目;
- 为 IIS 托管和 Hangfire 安装 Owin 软件包;
- 启动类和控制器。
套餐
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Hangfire.Core" version="1.6.6" targetFramework="net452" />
<package id="Hangfire.Pro" version="1.4.7" targetFramework="net452" />
<package id="Hangfire.Pro.PerformanceCounters" version="1.4.7" targetFramework="net452" />
<package id="Hangfire.Pro.Redis" version="2.0.2" targetFramework="net452" />
<package id="Hangfire.SqlServer" version="1.6.6" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Owin" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="1.0.0" targetFramework="net452" />
<package id="Microsoft.Net.Compilers" version="1.0.0" targetFramework="net452" developmentDependency="true" />
<package id="Microsoft.Owin" version="3.0.1" targetFramework="net452" />
<package id="Microsoft.Owin.Host.SystemWeb" version="3.0.1" targetFramework="net452" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net452" />
<package id="Owin" version="1.0" targetFramework="net452" />
<package id="StackExchange.Redis" version="1.1.606" targetFramework="net452" />
</packages>
控制器
public class DefaultController : ApiController
{
static int _;
[HttpPost]
public void Post(int count = 1000)
{
for (var i = 0; i < count; ++i)
{
BackgroundJob.Enqueue(() => Console.WriteLine(_));
++_;
}
}
}
启动
static class AppSettings
{
internal static bool HangfireUseRedis => true;
internal static int RedisDatabase => 0;
internal static string RedisConnection => "localhost:6379";
internal static string SqlConnection => "Data Source=(localdb)\\v11.0;Initial Catalog=Hangfire";
}
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
config.Routes.MapHttpRoute(
name: "Default",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
if (AppSettings.HangfireUseRedis)
{
var redisOptions = new RedisStorageOptions
{
Database = AppSettings.RedisDatabase,
Prefix = "Foobar:"
};
GlobalConfiguration.Configuration.UseRedisStorage(AppSettings.RedisConnection, redisOptions);
}
else
{
GlobalConfiguration.Configuration.UseSqlServerStorage(AppSettings.SqlConnection);
}
JobHelper.SetSerializerSettings(new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All });
app.UseHangfireServer();
app.UseHangfireDashboard();
app.UseWebApi(config);
}
}