[C#] .netCore + redis caching
When cached data is distributed, the data:
- Is coherent (consistent) across requests to multiple servers.
- Survives server restarts and app deployments.
- Doesn’t use local memory.
ขออนุญาติแนะนำการทำ Distributed caching ด้วย Redis อย่างง่ายๆเพื่อเป็นแนวทางพัฒนาต่อไปครับ
- Run Redis Container
$ docker run -d -p 6379:6379 -v /root/redis/data:/data -v /root/redis/redis.conf:/usr/local/etc/redis/redis.conf --name redis --restart=always redis:latest redis-server /usr/local/etc/redis/redis.conf
2.Create web api & add Microsoft.Extensions.Caching.Redis package
$ dotnet new webapi -o distributed-caching-redis
$ cd distributed-caching-redis
$ dotnet add package Microsoft.Extensions.Caching.Redis
3.Create Users.cs
ใน File Users.cs เพิ่ม IUserService, UserService และ DTO Class
ใน Function GetUsersAsync จะมีการ Call Rest Api เพื่อเรียกข้อมูลUser และในขั้นตอนนี้ เราจะ ทำการ Caching Data
4.Create UsersController.cs
5.Configuration & Inject IUsersService and HttpClient in Startup.cs
เพิ่ม services.AddDistributedRedisCache
services.AddScoped<IUsersService, UsersService>(); services.AddScoped<HttpClient, HttpClient>();
ใน ConfigureServices method
6.Run Api
$ dotnet run
เข้าไปที่ https://localhost:5001/users
แล้วจะได้ผลลัพธ์แบบนี้ การ แสดงผลในครั้งแรกจะ มีความช้านิดหนึ่ง แต่ครั้งต่อๆไปจะเร็วขึ้นเพราะว่า เป็นการเรียกใช้ข้อมูลจาก Redis 🌹🌹
Source Code : distributed-caching-redis
Ref : docs.microsoft