Moonglade

Modern Markdown blogging with AI-powered localization and search.

Tag: Redis


Implementing API Rate Limiting with Redis in Admin.Core

This article introduces the configuration and principles of implementing IP rate limiting in the ZhonTai Admin.Core framework based on AspNetCoreRateLimit and Redis. First, rate limiting must be enabled in `appconfig.json` and `cacheconfig.json`, with Redis specified as the storage backend to support multi-instance distributed environments. Rate limiting rules are defined in `appsettings.json`, supporting differentiated strategies for global endpoints and specific interfaces (such as login). Key configurations include enabling endpoint rate limiting, avoiding request stacking, and correctly setting the real IP header. The working principle involves the middleware generating Redis keys based on IP and path for counting; if the limit is exceeded, a 429 status code is returned, and the frontend prompts the user. The article specifically points out that the middleware registration order must place `UseIpRateLimiting` after `UseStaticFiles` to prevent static file requests from triggering rate limiting. Additionally, the article provides steps for manually integrating this component in environments other than Admin.Core, and mentions the built-in rate limiting mechanism in .NET 7 as an alternative solution, recommending that developers already using this framework directly leverage the built-in features to simplify development.

Views 312
.NET Admin.Core AspNetCore RateLimiting Redis WebApi

StackExchange.Redis Disconnection Pitfalls

This article summarizes common pitfalls and solutions for StackExchange.Redis connection interruptions and reconnection failures. The primary issue is that the default configuration has `abortConnect` set to `true`, which prevents automatic recovery after a disconnection. To enable automatic reconnection, you must set `abortConnect=false` in the connection string. Second, reconnection failures may still occur under high load. It is recommended to catch `RedisConnectionException` and manually rebuild the `ConnectionMultiplexer` instance. Regarding the issue in Linux environments where reconnection can take up to 15 minutes after a disconnection, the root cause is that the kernel parameter `tcp_retries2` has a default value that is too large. You can adjust it to `5` using the `sysctl` command to accelerate TCP layer release. Finally, it is emphasized that `ConnectionMultiplexer` must be used as a singleton. Creating a new connection for every request is strictly prohibited, as it can lead to a connection explosion. It is recommended to register it as a singleton service in dependency injection.

Views 180
.NET BestPractices C# Redis StackExchange.Redis Troubleshooting