반응형
Redis 테스트에 사용할 C# 프로젝트를 생성해준다.
Nuget에서 redis로 검색하고 StackExchange.Redis를 설치한다.
사전 준비

레디스 데이터베이스 이용하기
간단하게 redis 데이터베이스에 접근할 수 있다.
IDatabase db = redis.GetDatabase();
GetDatabase() 메서드에서 반환된 오브젝트는 싸게 쓰고 버리는 오브젝트라서 별도로 저장하지 않아도 된다.
개별 서버들에 접근하기
유지보수 목적으로 특정 서버에 접속해야만 하는 상황이 발생할 수 있다.
IServer server = redis.GetServer("localhost", 6379);
GetServer() 메서드는 EndPoint 또는 IPAddress, Port등의 식별자를 받아서 오브젝트를 반환합니다. 반환된 오브젝트는 싸게 쓰고 버리는 오브젝트라서 별도로 저장하지 않아도 됩니다.
사용 방법
간단하다. 데이터베이스가 아니라 서버로 시작하라
// get the target server
var server = conn.GetServer(someServer);
// show all keys in database 0 that include "foo" in their name
foreach(var key in server.Keys(pattern: "*foo*")) {
Console.WriteLine(key);
}
// completely wipe ALL keys from database 0
server.FlushDatabase();
예제 코드
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text.Json; | |
using StackExchange.Redis; | |
namespace redisTest | |
{ | |
public class RedisStore | |
{ | |
private ConnectionMultiplexer _redis; | |
private IServer _server; | |
private IDatabase _database; | |
private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions() | |
{ | |
PropertyNamingPolicy = JsonNamingPolicy.CamelCase, | |
}; | |
public RedisStore(string connectionString) | |
{ | |
_redis = ConnectionMultiplexer.Connect(connectionString); | |
if (_redis == null) | |
{ | |
return; | |
} | |
if (!_redis.IsConnected) | |
{ | |
return; | |
} | |
_database = _redis.GetDatabase(); | |
var endpoint = _redis.GetEndPoints().Single(); | |
_server = _redis.GetServer(endpoint); | |
} | |
public List<RedisKey> GetKeys(string pattern) | |
{ | |
return _server.Keys(pattern: pattern).ToList(); | |
} | |
public void SetValue(RedisKey key, RedisValue value) | |
{ | |
_database.StringSet(key, value); | |
} | |
public string GetValue(RedisKey key) | |
{ | |
return _database.StringGet(key); | |
} | |
public bool JsonSet(string key, object value) | |
{ | |
string json = JsonSerializer.Serialize(value, _jsonSerializerOptions); | |
return _database.StringSet(key, json); | |
} | |
public T JsonGet<T>(string key) | |
{ | |
RedisValue redisValue = _database.StringGet(key); | |
if (redisValue.IsNullOrEmpty) | |
{ | |
return default(T); | |
} | |
return JsonSerializer.Deserialize<T>(redisValue, _jsonSerializerOptions); | |
} | |
} | |
public class MyClass | |
{ | |
public int value1 { get; set; } | |
public string value2 { get; set; } | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
RedisStore redis = new RedisStore("localhost:6379"); | |
// key, value로 저장 | |
redis.SetValue("test1", "ans-test1"); | |
// key로 value를 찾는다. | |
Console.WriteLine(redis.GetValue("test1")); | |
// value로 사용자 정의 클래스를 입력 | |
redis.JsonSet("test2", new MyClass() | |
{ | |
value1 = 1, | |
value2 = "test2" | |
}); | |
// key로 사용자 정의 클래스를 찾는다. | |
var resultMyClass = redis.JsonGet<MyClass>("test2"); | |
Console.WriteLine($"{resultMyClass.value1}, {resultMyClass.value2}"); | |
} | |
} | |
} |
'프로그래밍 > 데이터베이스' 카테고리의 다른 글
StackExchange.Redis Subscribe()로 구독하기 (0) | 2023.12.27 |
---|---|
Redis 자료구조(Data Structures) (11) | 2023.05.30 |
C# redis에서 Key들을 pattern으로 조회하기 (28) | 2023.05.25 |
트랜잭션 격리 수준(Transaction Isolation Level)에 대해서 (8) | 2023.05.10 |
SQL 실행 순서 알아보기 (2) | 2023.05.04 |
댓글