219 lines
6.0 KiB
C#
219 lines
6.0 KiB
C#
using Autofac;
|
|||
|
|
using Autofac.Extensions.DependencyInjection;
|
||
|
|
using Common;
|
||
|
|
using Common.Request;
|
||
|
|
using CommonService;
|
||
|
|
|
||
|
|
using FishRoomHost.Extension;
|
||
|
|
using FishRoomHost.Middleware;
|
||
|
|
using FishRoomService;
|
||
|
|
using FishRoomService.Hubs;
|
||
|
|
using FishRoomService.RoomService;
|
||
|
|
using JWTHelper;
|
||
|
|
using Microsoft.AspNetCore.Diagnostics.HealthChecks;
|
||
|
|
using Microsoft.AspNetCore.Http.Features;
|
||
|
|
using Microsoft.AspNetCore.SignalR;
|
||
|
|
using Microsoft.Extensions.Diagnostics.HealthChecks;
|
||
|
|
using Microsoft.Extensions.Options;
|
||
|
|
using MongoRepository.Config;
|
||
|
|
using NLog.Extensions.Logging;
|
||
|
|
using NLog.Web;
|
||
|
|
using RedisHelper;
|
||
|
|
using SharpAbp.Infrastructure.Api.Middleware;
|
||
|
|
using StackExchange.Redis;
|
||
|
|
using System.Text.Json;
|
||
|
|
using static Common.Utils.DateTimeTools;
|
||
|
|
|
||
|
|
Environment.SetEnvironmentVariable("SERVICE_NAME",
|
||
|
|
Environment.GetEnvironmentVariable("SERVICE_NAME")
|
||
|
|
?? System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name
|
||
|
|
?? "FishRoomHost");
|
||
|
|
Environment.SetEnvironmentVariable("INSTANCE_ID",
|
||
|
|
Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "default");
|
||
|
|
|
||
|
|
var builder = WebApplication.CreateBuilder(args);
|
||
|
|
|
||
|
|
// Add services to the container.
|
||
|
|
string instanceId = Environment.GetEnvironmentVariable("INSTANCE_ID") ?? "Unknown";
|
||
|
|
|
||
|
|
builder.Services.AddSingleton(sp => new AppInstanceId { Id = instanceId });
|
||
|
|
builder.Services.AddControllers();
|
||
|
|
builder.Logging.AddNLog();
|
||
|
|
builder.Host.UseNLog();
|
||
|
|
|
||
|
|
builder.Configuration.AddJsonFile(Path.Combine("Config", "system.json"), optional: true);
|
||
|
|
builder.Services.Configure<MongoDbSettings>(builder.Configuration.GetSection(nameof(MongoDbSettings)));
|
||
|
|
builder.Services.AddSingleton<IMongoDbSettings>(sp => sp.GetRequiredService<IOptions<MongoDbSettings>>().Value);
|
||
|
|
|
||
|
|
string redisConn = builder.Configuration.GetConnectionString("Redis");
|
||
|
|
if (string.IsNullOrWhiteSpace(redisConn))
|
||
|
|
{
|
||
|
|
var redisSection = builder.Configuration.GetSection("RedisConfig");
|
||
|
|
var host = redisSection["Host"];
|
||
|
|
var port = redisSection["Port"] ?? "6379";
|
||
|
|
var password = redisSection["Password"];
|
||
|
|
var database = redisSection["Database"] ?? "0";
|
||
|
|
|
||
|
|
if (string.IsNullOrWhiteSpace(host))
|
||
|
|
{
|
||
|
|
throw new InvalidOperationException("未找到 Redis 配置:请在 ConnectionStrings:Redis 或 RedisConfig 节中配置 Redis 地址。");
|
||
|
|
}
|
||
|
|
|
||
|
|
redisConn = $"{host}:{port}";
|
||
|
|
if (!string.IsNullOrEmpty(password))
|
||
|
|
redisConn += $",password={password}";
|
||
|
|
if (!string.IsNullOrEmpty(database))
|
||
|
|
redisConn += $",defaultDatabase={database}";
|
||
|
|
}
|
||
|
|
|
||
|
|
builder.Services.AddSingleton<IConnectionMultiplexer>(sp =>
|
||
|
|
{
|
||
|
|
return ConnectionMultiplexer.Connect(redisConn);
|
||
|
|
});
|
||
|
|
|
||
|
|
builder.Services.AddSignalR(hubOptions =>
|
||
|
|
{
|
||
|
|
hubOptions.MaximumReceiveMessageSize = 64 * 1024;
|
||
|
|
hubOptions.StreamBufferCapacity = 512;
|
||
|
|
hubOptions.ClientTimeoutInterval = TimeSpan.FromSeconds(60);
|
||
|
|
hubOptions.KeepAliveInterval = TimeSpan.FromSeconds(5);
|
||
|
|
|
||
|
|
hubOptions.AddFilter<MovementFilter>();
|
||
|
|
hubOptions.AddFilter<HubExceptionFilter>();
|
||
|
|
})
|
||
|
|
.AddJsonProtocol();
|
||
|
|
|
||
|
|
builder.Services.Configure<FormOptions>(x =>
|
||
|
|
{
|
||
|
|
x.MultipartBodyLengthLimit = 1024 * 1024 * 16;
|
||
|
|
});
|
||
|
|
|
||
|
|
|
||
|
|
builder.Services.AddMemoryCache();
|
||
|
|
builder.Services.AddControllers().AddJsonOptions(configure =>
|
||
|
|
{
|
||
|
|
configure.JsonSerializerOptions.Converters.Add(new DatetimeJsonConverter());
|
||
|
|
|
||
|
|
});
|
||
|
|
|
||
|
|
|
||
|
|
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||
|
|
builder.Services.AddSingleton<IHubSend<FishRoomHub>, HubSend<FishRoomHub>>();
|
||
|
|
builder.Services.AddSingleton<IRequestApi, RequestApi>();
|
||
|
|
builder.Services.AddAutoMapper(typeof(AutoMapperConfig));
|
||
|
|
|
||
|
|
builder.Services.AddHealthChecks()
|
||
|
|
.AddCheck("self", () => HealthCheckResult.Healthy(), tags: new[] { "self" });
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
builder.Services.AddCors(options =>
|
||
|
|
{
|
||
|
|
options.AddPolicy("Cors", policy =>
|
||
|
|
{
|
||
|
|
policy
|
||
|
|
.SetIsOriginAllowed(_ => true)
|
||
|
|
.AllowAnyHeader()
|
||
|
|
.AllowAnyMethod()
|
||
|
|
.AllowCredentials();
|
||
|
|
});
|
||
|
|
});
|
||
|
|
|
||
|
|
#region jwt
|
||
|
|
|
||
|
|
builder.Services.AddCustomJwt(builder.Configuration);
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
#region redis
|
||
|
|
|
||
|
|
builder.Services.AddRedisCacheSingleton(builder.Configuration);
|
||
|
|
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
|
||
|
|
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
|
||
|
|
{
|
||
|
|
builder.RegisterModule<AutofacModule>();
|
||
|
|
});
|
||
|
|
|
||
|
|
#region Cap
|
||
|
|
|
||
|
|
builder.Services.AddCap(builder.Configuration);
|
||
|
|
#endregion
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
var app = builder.Build();
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
// Configure the HTTP request pipeline.
|
||
|
|
if (app.Environment.IsDevelopment())
|
||
|
|
{
|
||
|
|
|
||
|
|
}
|
||
|
|
app.UseApiLogging();
|
||
|
|
app.UseRouting();
|
||
|
|
app.UseGlobalExceptionHandler();
|
||
|
|
|
||
|
|
|
||
|
|
app.UseStaticFiles();
|
||
|
|
app.UseCors("Cors");
|
||
|
|
app.UseAuthentication();
|
||
|
|
app.UseAuthorization();
|
||
|
|
|
||
|
|
app.MapHub<FishRoomHub>("/fishingroomhub", options =>
|
||
|
|
{
|
||
|
|
options.Transports = Microsoft.AspNetCore.Http.Connections.HttpTransportType.WebSockets;
|
||
|
|
});
|
||
|
|
|
||
|
|
|
||
|
|
app.MapControllers();
|
||
|
|
|
||
|
|
app.MapHealthChecks("/health", new HealthCheckOptions
|
||
|
|
{
|
||
|
|
Predicate = _ => true,
|
||
|
|
ResponseWriter = async (context, report) =>
|
||
|
|
{
|
||
|
|
context.Response.ContentType = "application/json";
|
||
|
|
var result = new
|
||
|
|
{
|
||
|
|
status = report.Status.ToString(),
|
||
|
|
checks = report.Entries.Select(e => new
|
||
|
|
{
|
||
|
|
name = e.Key,
|
||
|
|
status = e.Value.Status.ToString(),
|
||
|
|
description = e.Value.Description,
|
||
|
|
duration = e.Value.Duration.TotalMilliseconds
|
||
|
|
}),
|
||
|
|
totalDuration = report.TotalDuration.TotalMilliseconds
|
||
|
|
};
|
||
|
|
await context.Response.WriteAsync(JsonSerializer.Serialize(result));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
using (var scope = app.Services.CreateScope())
|
||
|
|
{
|
||
|
|
var logger = scope.ServiceProvider.GetRequiredService<ILogger<Program>>();
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var redis = scope.ServiceProvider.GetRequiredService<RedisService.IRedisService>();
|
||
|
|
if (redis.GetGameRoomAllList()?.Any() != true)
|
||
|
|
{
|
||
|
|
var roomService = scope.ServiceProvider.GetRequiredService<IFishingRoomService>();
|
||
|
|
await roomService.InitRoom();
|
||
|
|
}
|
||
|
|
|
||
|
|
}
|
||
|
|
catch (Exception ex)
|
||
|
|
{
|
||
|
|
logger.LogError(ex, "[Startup] 游戏房间初始化失败");
|
||
|
|
throw;
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
app.Run();
|
||
|
|
|