[C#] .netCore + redis caching

Distributed caching in ASP.NET Core

Macus.y
1 min readMay 4, 2021

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 อย่างง่ายๆเพื่อเป็นแนวทางพัฒนาต่อไปครับ

  1. 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

Users.cs

4.Create UsersController.cs

UsersController.cs

5.Configuration & Inject IUsersService and HttpClient in Startup.cs

เพิ่ม services.AddDistributedRedisCache
services.AddScoped<IUsersService, UsersService>(); services.AddScoped<HttpClient, HttpClient>();
ใน ConfigureServices method

Startup.cs

6.Run Api

$ dotnet run

เข้าไปที่ https://localhost:5001/users
แล้วจะได้ผลลัพธ์แบบนี้ การ แสดงผลในครั้งแรกจะ มีความช้านิดหนึ่ง แต่ครั้งต่อๆไปจะเร็วขึ้นเพราะว่า เป็นการเรียกใช้ข้อมูลจาก Redis 🌹🌹

https://localhost:5001/users

Source Code : distributed-caching-redis
Ref : docs.microsoft

--

--

Macus.y
Macus.y

Written by Macus.y

“Many of life’s failures are people who did not realize how close they were to success when they gave up.”– Thomas A. Edison 😇😇😇

No responses yet