Use Amazon ElastiCache for Redis with ASP.NET Core¶
This recipe adds Redis-backed caching to an ASP.NET Core application on Elastic Beanstalk. It uses StackExchange.Redis and the environment property pattern for endpoint discovery.
Prerequisites¶
- Running .NET Elastic Beanstalk environment in a VPC.
- Existing ElastiCache for Redis cluster or replication group.
- Network access from application instances to the Redis endpoint.
What You'll Build¶
You will build:
- Environment properties for the Redis endpoint.
- ASP.NET Core registration for Redis connectivity.
- A lightweight cache test endpoint.
Steps¶
- Set the Redis endpoint in environment properties.
- Add the client package.
- Register a singleton multiplexer.
builder.Services.AddSingleton<IConnectionMultiplexer>(_ =>
ConnectionMultiplexer.Connect(builder.Configuration["REDIS_ENDPOINT"]!));
- Add a test endpoint.
app.MapGet("/cache-check", async (IConnectionMultiplexer redis) =>
{
var database = redis.GetDatabase();
await database.StringSetAsync("guide:health", "ok");
var value = await database.StringGetAsync("guide:health");
return Results.Ok(new { redis = value.ToString() });
});
- Deploy and test.
flowchart LR
A[Elastic Beanstalk App] --> B[Security Group Rule]
B --> C[Redis Endpoint]
D[REDIS_ENDPOINT Property] --> A Verification¶
Run these checks after deployment:
Expected outcomes:
- The application resolves the Redis endpoint.
- Cache read and write operations succeed.
- Logs show no connection timeout or network errors.