บทนำ
Redis เป็น Key-value Store ในหน่วยความจำ (In-memory) ที่เร็ว ใช้กันอย่างแพร่หลายสำหรับ Caching, Session Storage, Message Brokering และ Pub/Sub Communication ใน Modern Applications มัน Lightweight, Performant และ Developer-friendly ทำให้เป็น Go-to Choice สำหรับการสร้าง Scalable Systems
ถ้าคุณกำลังพัฒนาใน .NET Core และต้องการผสานรวม Redis เข้าแอปพลิเคชัน บทความนี้จะแสดงวิธีใช้ StackExchange.Redis Library เพื่อทำ Basic Redis Operations
สำหรับผู้ทำงานบน Windows Systems สามารถใช้ Redis-compatible Server เพื่อรัน Redis โดยไม่ต้องใช้ Linux หรือ Containerization
ทำไมต้อง Redis?
Redis ให้ Benefits หลายอย่างเมื่อผสานกับ .NET Core Application
- Caching: เก็บข้อมูลที่เข้าถึงบ่อย เพื่อปรับปรุง Response Times และลด Database Workloads
- Session Management: จัดการ User Sessions อย่างมีประสิทธิภาพใน Distributed Systems
- Real-Time Events: ใช้ Redis Pub/Sub สำหรับ Real-time Functionality เช่น Notifications หรือ Event-driven Communication
- High Performance: ทำงานใน Memory ให้ Low-latency Data Access
- Scalable: รองรับ Clustering และ Sharding สร้างขึ้นมาสำหรับ Scalability
การตั้งค่า Redis (Setting Up Redis)
ใช้ Redis
เพื่อเชื่อมต่อ .NET Core App กับ Redis คุณสามารถรัน Redis ได้ทั้ง:
- Command-Line Installation: ใช้ Tools เช่น Docker รัน Redis บน Linux หรือ Windows
- Pre-Configured Windows Alternative: ถ้าคุณบน Windows คุณสามารถใช้ Redis-compatible Server เป็น Drop-in Replacement สำหรับการรัน Redis แบบ Native
หมายเหตุ. เพื่อความเรียบง่าย บทช่วยสอนนี้สมมติ Redis รัน Local บน localhost:6379
สร้าง .NET Core Application กับ Redis
ในตัวอย่างนี้ เราจะสร้าง .NET Core Console Application ที่ทำ Redis Operations ต่อไปนี้
- Connect ไป Redis Server
- Basic Key-Value Operations (Set, Get, Delete)
- Demo Key Expiration และ Validation
ขั้นตอนที่ 1. สร้าง .NET Core Project
-
เปิด Terminal และสร้าง Project ใหม่
dotnet new RedisIntegrationDemo -
ติดตั้ง StackExchange.Redis Package สำหรับ Redis Connectivity
dotnet add package StackExchange.Redis
ขั้นตอนที่ 2. เขียน Code
นี่คือ Full Implementation ใน Program.cs
using System;
using StackExchange.Redis;
using System.Threading.Tasks;
namespace RedisIntegrationDemo {
class Program {
// Connection string for Redis
private const string RedisConnectionString = "localhost:6379";
async static Task Main(string[] args) {
Console.WriteLine("Connecting to Redis...");
// Connect to Redis
var redis = await ConnectionMultiplexer.ConnectAsync(RedisConnectionString);
Console.WriteLine("Connected to Redis successfully.\n");
// Access the Redis database
IDatabase db = redis.GetDatabase();
// Perform Redis operations
Console.WriteLine("Performing Redis operations...");
// 1. Set key-value pair
string key = "SampleKey";
string value = "Hello from Redis!";
await db.StringSetAsync(key, value);
Console.WriteLine($"Set: {key} => {value}");
// 2. Get the value for the key
string savedValue = await db.StringGetAsync(key);
Console.WriteLine($"Get: {key} => {savedValue}");
// 3. Set an expiration for the key
TimeSpan expiryTime = TimeSpan.FromSeconds(10);
await db.KeyExpireAsync(key, expiryTime);
Console.WriteLine($"Set expiration for {key}: {expiryTime.TotalSeconds} seconds");
// 4. Check key existence after expiration
Console.WriteLine("\nWaiting for the key to expire...");
await Task.Delay(12000); // Wait 12 seconds
bool exists = await db.KeyExistsAsync(key);
Console.WriteLine($"Key Exists After Expiration: {key} => {exists}");
// Close the connection
redis.Close();
Console.WriteLine("\nAll Redis operations completed.");
}
}
}
ขั้นตอนที่ 3. Run Application
เพื่อ Execute Application
dotnet run
Expected Output
โปรแกรมจะ Connect Redis, ทำ Basic Key-Value Operations และ Validate Key Expiration คุณควรเห็น Output ประมาณนี้

Redis ทำงานกับ .NET Core อย่างไร?
นี่คือสิ่งที่ Application ทำทีละขั้นตอน
- Connect ไป Redis Server ด้วย ConnectionMultiplexer ซึ่งจัดการ Connection Pooling และ Server Communication
- Basic Commands:
- StringSetAsync: Set Key-Value Pair ใน Redis
- StringGetAsync: Get Value ของ Key
- KeyExpireAsync: Set Expiration Time สำหรับ Key
- KeyExistsAsync: Check ถ้า Key Exists
- จัดการ Temporary In-memory Storage ของ Data พร้อม Expiration
ถ้าคุณทำงานใน Windows Environment และไม่ต้องการ Install Native Redis Instance หรือใช้ Docker คุณสามารถใช้ Redis-compatible Server เป็น Alternative ได้
การตั้งค่า Redis-compatible Server
- Install Redis-compatible Server สำหรับ Windows
- ติดตั้งแล้ว Server มักรันบน localhost:6379 โดย Default เหมือน Redis
- Application ของคุณไม่ต้องการ Code Changes ใดๆ เพื่อทำงานกับ Redis-compatible Server
การใช้ Redis-compatible Server อนุญาตให้ Redis Functionality รัน Native บน Windows โดยไม่พึ่งพา Containers หรือ Virtualized Environments
ข้อดีของการใช้ Redis ใน .NET Core
- Performance: Redis ทำงานเต็มที่ใน Memory ให้ Extremely Low Latency
- Ease of Use: Simplified API สำหรับ Key-Value Needs พื้นฐาน พร้อม Data Structures เพิ่มเติม เช่น Lists, Sets, Hashes
- Flexibility: Redis ใช้ได้หลายวัตถุประสงค์ (Caching, Message Queues, Pub/Sub)
- Scalability: Redis รองรับ Clustering และ High Availability สำหรับ Scale ตาม Demand
สรุป
การผสานรวม Redis เข้า .NET Core Application ช่วยให้คุณสร้าง High-quality, Performant Systems ที่จัดการ Demanding Workloads ได้ ด้วย StackExchange.Redis Library คุณสามารถโต้ตอบกับ Redis ได้ Seamlessly
เริ่มด้วยการ Implement Redis สำหรับ Simple Caching หรือ Session Management และขยายการใช้งานไปสู่ Pub/Sub และ Real-time Data Needs ใน Distributed .NET Core Applications ของคุณ
Happy Coding และ Scaling!