.NET Core 2 NLog Core HangFire Core

Startup.cs 2.9KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Microsoft.AspNetCore.Builder;
  6. using Microsoft.AspNetCore.Hosting;
  7. using Microsoft.Extensions.Configuration;
  8. using Microsoft.Extensions.DependencyInjection;
  9. using Microsoft.Extensions.Logging;
  10. using Microsoft.Extensions.Options;
  11. using Hangfire;
  12. using WebApplication1.Filter;
  13. using NLog.Extensions.Logging;
  14. using NLog.Web;
  15. using System.Transactions;
  16. using StackExchange.Redis;
  17. namespace WebApplication1
  18. {
  19. public class Startup
  20. {
  21. public Startup(IConfiguration configuration)
  22. {
  23. Configuration = configuration;
  24. }
  25. public IConfiguration Configuration { get; }
  26. // This method gets called by the runtime. Use this method to add services to the container.
  27. public void ConfigureServices(IServiceCollection services)
  28. {
  29. services.AddMvc();
  30. //添加 Hangfire 组件,并且指定使用 SQL Server 进行持久化存储
  31. services.AddHangfire(x => x.UseSqlServerStorage(Configuration.GetConnectionString("hangfire.sqlserver")));
  32. //添加 Hangfire 组件,并且指定使用 Redis 进行持久化存储
  33. services.AddHangfire(x =>
  34. {
  35. //从appsettings中获取 Redis 连接字符串
  36. x.UseRedisStorage(ConnectionMultiplexer.Connect(Configuration.GetConnectionString("hangfire.redis")));
  37. });
  38. //添加日志组件
  39. services.AddLogging();
  40. }
  41. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  42. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
  43. {
  44. if (env.IsDevelopment())
  45. {
  46. app.UseDeveloperExceptionPage();
  47. }
  48. app.UseMvc();
  49. #region HangFire
  50. //启动hangfire面板
  51. app.UseHangfireDashboard();
  52. //配置hangfire面板访问权限
  53. var options = new DashboardOptions
  54. {
  55. Authorization = new[] { new HangfireAuthorizationFilter() }
  56. };
  57. app.UseHangfireDashboard("/hangfire", options);
  58. //hangfire 配置项
  59. var jobOptions = new BackgroundJobServerOptions
  60. {
  61. Queues = new[] { "test", "default" },//队列名称,只能为小写
  62. WorkerCount = Environment.ProcessorCount * 5, //并发任务数
  63. ServerName = "hangfire1",//服务器名称
  64. };
  65. //启动Hangfire服务
  66. app.UseHangfireServer(jobOptions);
  67. #endregion
  68. #region NLog
  69. loggerFactory.AddNLog();//添加NLog
  70. env.ConfigureNLog("StaticConfig/nlog.config");//读取Nlog配置文件
  71. #endregion
  72. }
  73. }
  74. }