Created
May 11, 2024 18:16
-
-
Save orlys/dcc4e2fbba3483349d5a528d61f34965 to your computer and use it in GitHub Desktop.
計算線上人數用中介層
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Http; | |
using System.Threading.Tasks; | |
public class OnlineUserCounterMiddleware | |
{ | |
private RequestDelegate _next; | |
private static int s_onlineUserCount; | |
public OnlineUserCounterMiddleware( | |
RequestDelegate next) | |
{ | |
_next = next; | |
} | |
public async Task InvokeAsync(HttpContext context) | |
{ | |
// 僅限單機,多機請用 Redis 處理,但邏輯一樣 | |
var currentOnlineUserCount = Interlocked.Increment(ref s_onlineUserCount); | |
context.Items["OnlineUser"] = currentOnlineUserCount; | |
await _next(context); | |
Interlocked.Decrement(ref s_onlineUserCount); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment