Skip to content

Commit dee9dba

Browse files
committed
use minimal API for kestrel toy project
1 parent 1c6b59e commit dee9dba

File tree

3 files changed

+34
-64
lines changed

3 files changed

+34
-64
lines changed

toys/KestrelRedisServer/KestrelRedisServer.csproj

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
11
<Project Sdk="Microsoft.NET.Sdk.Web">
22

33
<PropertyGroup>
4-
<TargetFramework>net6.0</TargetFramework>
4+
<TargetFramework>net8.0</TargetFramework>
55
<NoWarn>$(NoWarn);CS1591</NoWarn>
6+
<Nullable>enable</Nullable>
7+
<ImplicitUsings>enable</ImplicitUsings>
68
</PropertyGroup>
79

810
<ItemGroup>

toys/KestrelRedisServer/Program.cs

Lines changed: 31 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,38 @@
1-
using Microsoft.AspNetCore;
1+
using KestrelRedisServer;
22
using Microsoft.AspNetCore.Connections;
3-
using Microsoft.AspNetCore.Hosting;
3+
using StackExchange.Redis.Server;
44

5-
namespace KestrelRedisServer
5+
var server = new MemoryCacheRedisServer();
6+
7+
var builder = WebApplication.CreateBuilder(args);
8+
builder.Services.AddSingleton<RespServer>(server);
9+
builder.WebHost.ConfigureKestrel(options =>
610
{
7-
public static class Program
8-
{
9-
public static void Main(string[] args) => CreateWebHostBuilder(args).Build().Run();
11+
// HTTP 5000 (test/debug API only)
12+
options.ListenLocalhost(5000);
1013

11-
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
12-
WebHost.CreateDefaultBuilder(args)
13-
.UseKestrel(options =>
14-
{
15-
// Moved to SocketTransportOptions.UnsafePreferInlineScheduling = true;
16-
//options.ApplicationSchedulingMode = SchedulingMode.Inline;
14+
// this is the core of using Kestrel to create a TCP server
15+
// TCP 6379
16+
options.ListenLocalhost(6379, builder => builder.UseConnectionHandler<RedisConnectionHandler>());
17+
});
1718

18-
// HTTP 5000
19-
options.ListenLocalhost(5000);
19+
var app = builder.Build();
2020

21-
// TCP 6379
22-
options.ListenLocalhost(6379, builder => builder.UseConnectionHandler<RedisConnectionHandler>());
23-
}).UseStartup<Startup>();
21+
// redis-specific hack - there is a redis command to shutdown the server
22+
_ = server.Shutdown.ContinueWith(static (t, s) =>
23+
{
24+
try
25+
{ // if the resp server is shutdown by a client: stop the kestrel server too
26+
if (t.Result == RespServer.ShutdownReason.ClientInitiated)
27+
{
28+
((IServiceProvider)s!).GetService<IHostApplicationLifetime>()?.StopApplication();
29+
}
2430
}
25-
}
31+
catch { /* Don't go boom on shutdown */ }
32+
}, app.Services);
33+
34+
// add debug route
35+
app.Run(context => context.Response.WriteAsync(server.GetStats()));
36+
37+
// run the server
38+
await app.RunAsync();

toys/KestrelRedisServer/Startup.cs

Lines changed: 0 additions & 45 deletions
This file was deleted.

0 commit comments

Comments
 (0)