728x90
반응형
redis를 사용하기 위해 cloudstructes라는 라이브러리를 알아보자.
CloudStructures
.NET용 Redis클라이언트 라이브러리다.
StackExchange.Redis를 기반으로 더 편리한 API를 제공한다.
왜 사용할까?
일반 Redis 클라이언트 (StackExchange.Redis)를 직접사용한다면,
// 문자열 저장
await db.StringSetAsync("user:1:name", "John");
// 문자열 읽기
var name = await db.StringGetAsync("user:1:name");
이런식으로 사용하게 되지만,
// 타입 안전하게 저장
var redisString = new RedisString<string>(connection, "user:1:name");
await redisString.SetAsync("John");
// 타입 안전하게 읽기
var name = await redisString.GetAsync();
CloudStructures를 사용하면 타입 안정성, 자동 직렬화와 같은 이점을 얻을 수 있다.
이 중, 제일 편리해보이는건 자동 직렬화인것 같다.
설치
dotnet add package CloudStructures
CloudStructures를 설치해주자.
또는 .csproj 파일에
<ItemGroup>
<PackageReference Include="CloudStructures" Version="2.0.0" />
</ItemGroup>
를 직접 추가해줘도 된다.
기본 사용법
1. Redis 연결
appsettings.json에 Redis 정보를 넣어주자.
{
"ConnectionStrings": {
"Redis": "localhost:6379"
}
}
그리고, Program.cs에 Redis 연결 설정을 해주자.
using CloudStructures;
using StackExchange.Redis;
var builder = WebApplication.CreateBuilder(args);
// Redis 연결 설정
var redisConfig = new RedisConfig(
"default",
builder.Configuration.GetConnectionString("Redis")
);
builder.Services.AddSingleton(redisConfig);
//컨트롤러 사용
builder.Services.AddControllers();
var app = builder.Build();
app.MapControllers();
app.Run();
2. 컨트롤러 생성
Redis를 사용하기 위한 컨트롤러를 생성하자.
using CloudStructures;
using CloudStructures.Structures;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
[ApiController]
[Route("[controller]")]
public class RedisController : ControllerBase
{
private readonly RedisConnection _redisConnection;
public RedisController(RedisConnection redisConnection)
{
_redisConnection = redisConnection;
}
// 문자열 저장
[HttpPost("set")]
public async Task<IActionResult> Set([FromBody] SetRequest request)
{
// defaultExpiry를 null로 설정 (만료 시간 없음)
var redisString = new RedisString<string>(
_redisConnection,
(RedisKey)request.Key,
defaultExpiry: null
);
await redisString.SetAsync(request.Value);
return Ok("Saved");
}
// 문자열 읽기
[HttpGet("get/{key}")]
public async Task<IActionResult> Get(string key)
{
var redisString = new RedisString<string>(
_redisConnection,
(RedisKey)key,
defaultExpiry: null
);
var value = await redisString.GetAsync();
if (value.HasValue)
return Ok(new { Key = key, Value = value.Value });
return NotFound("Key not found");
}
}
public class SetRequest
{
public string Key { get; set; } = "";
public string Value { get; set; } = "";
}
이제 찬찬히 살펴보자.
Redis의 주요 구조체 종류
CloudStructures는 Redis 데이터 타입별로 구조체를 제공한다.
1. RedisString<T> - 문자열 저장
var redisString = new RedisString<string>(_redisConfig, "user:1:name");
await redisString.SetAsync("John");
var name = await redisString.GetAsync();
2. RedisHash<T> - 해시 저장
var redisHash = new RedisHash<string, string>(_redisConfig, "user:1");
await redisHash.SetAsync("name", "John");
await redisHash.SetAsync("age", "30");
var name = await redisHash.GetAsync("name");
3. RedisList<T> - 리스트 저장
var redisList = new RedisList<string>(_redisConfig, "messages");
await redisList.RightPushAsync("message1");
await redisList.RightPushAsync("message2");
var messages = await redisList.RangeAsync(0, -1);
4. RedisSet<T> - 집합 저장
var redisSet = new RedisSet<string>(_redisConfig, "tags");
await redisSet.AddAsync("tag1");
await redisSet.AddAsync("tag2");
var tags = await redisSet.MembersAsync();
5. RedisSortedSet<T> - 정렬된 집합 저장
var redisSortedSet = new RedisSortedSet<string>(_redisConfig, "leaderboard");
await redisSortedSet.AddAsync("player1", 100);
await redisSortedSet.AddAsync("player2", 200);
var topPlayers = await redisSortedSet.RangeByRankAsync(0, 9);
객체 저장 예시
위의 구조를 활용해서 데이터를 저장하는 과정을 예제를 통해 확인해보자.
public class User
{
public int Id { get; set; }
public string Name { get; set; } = "";
public string Email { get; set; } = "";
}
[HttpPost("user")]
public async Task<IActionResult> SaveUser([FromBody] User user)
{
// 객체를 자동으로 JSON으로 직렬화해서 저장
var redisString = new RedisString<User>(_redisConfig, $"user:{user.Id}");
await redisString.SetAsync(user);
return Ok("User saved");
}
[HttpGet("user/{id}")]
public async Task<IActionResult> GetUser(int id)
{
var redisString = new RedisString<User>(_redisConfig, $"user:{id}");
var user = await redisString.GetAsync();
if (user.HasValue)
return Ok(user.Value);
return NotFound();
}
TTL 설정
앞서, Redis는 제한된 공간을 사용하는 데이터베이스이기 때문에, 각 데이터에 TTL을 설정할 수 있다고 했다.
var redisString = new RedisString<string>(_redisConfig, "session:123");
// 10분 후 만료
await redisString.SetAsync("session-data", TimeSpan.FromMinutes(10));
// 또는
await redisString.SetAsync("session-data", expire: TimeSpan.FromMinutes(10));
728x90
반응형
'Study > GameServer' 카테고리의 다른 글
| [ASP.NET Core] 12. ZLogger (0) | 2025.12.05 |
|---|---|
| [ASP.NET Core] 10. Redis (0) | 2025.12.05 |
| [ASP.NET Core] 09. SQLKata (0) | 2025.12.05 |
| [ASP.NET Core] 08. .NET Core에 MySQL 연결 (1) | 2025.12.04 |
| [ASP.NET Core] 07. API 서버간 통신 때 HttpClientFactory 사용하기 (0) | 2025.12.04 |