Garnet First Step

드디어 시간이 나서 Garnet 을 시작해보기로 했습니다.
Cache db 를 사실 거의 안써봐서 굉장히 긴장했습니다.

Site
github : GitHub - microsoft/garnet: Garnet is a remote cache-store from Microsoft Research that offers strong performance (throughput and latency), scalability, storage, recovery, cluster sharding, key migration, and replication features. Garnet can work with existing Redis clients.
official Site : Hello from Garnet | Garnet

해당 사이트에서 받으시고 Site에서 보고 따라하시면 됩니다.

설치

cd garnet
dotnet restore
dotnet build -c Release

Test Suite 실행

dotnet test -c Release -f net8.0 -l “console;verbosity=detailed”

대략이러면 뭔가 엄청난것이 PC에 설치합니다.

설치가 끝나고 Instance 를 올립니다 ( 이때 default port 6379를 오픈하세요)

실행

cd main/GarnetServer
dotnet run -c Release -f net8.0

뭐 이러면 garnet 이 실행중이라는데 .. 앞으로 어떻게 해야할지 몰랐습니다.
접속을 위해서는 사이트에
Redis-cli 나 c#에서는 StackExchange.Redis Nuget 에서 참조를 하면 된다고 합니다.


여기서 garnet 을 설치했는데 도구는 redis를 쓰라고 하고 있군요 ;;;
그렇습니다. 그냥 redis 쓰시듯 그대로 쓰시면 된다고 합니다. ;;;

Redis 입장에서는 약간 얄미울것 같군요

그래서 c# console 프로젝트를 만들고

stackexchange를 Nuget 에서 참조했습니다.

sample 소스를 못찾아서 redis c# client 소스를 그대로 참고했습니다.

    public class GarnetStore
    {
        private ConnectionMultiplexer _redis;
        private IServer _server;
        private IDatabase _database;
        private readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions()
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
        };
        public GarnetStore(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; }
    }

뭐 대략 이런식으로 하고

    GarnetStore redis = new GarnetStore("192.168.0.11:6379");
    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}");
}

이렇게 하시면
image

garnet 에 데이타 잘빼고 가져옵니다 .

하기 전에는 굉장히 어렵고 두려웠는데 너무 쉽게 되서 의외였습니다.
그냥 기존 redis 사용자들은 도메인만 바꾸셔도 대충 될것 같습니다.

12개의 좋아요

저도 가넷 일부러한번 써보고 싶은데 말이죠 ㅋㅋ 쉽게 쓸 수 있다니 다행이군요!

3개의 좋아요

개인적으로는 garnet이 정말 좋았던게, linqpad나 C# script 같은 환경에서는 외부 프로세스 형태가 아닌 닷넷 런타임 안에 깊이 통합되어 실행되는 방식으로 동작하는게 정말 마음에 들었습니다.

그리고 운영 체제 수준의 파이프나 메모리 맵 파일보다 훨씬 쓰기 편하고 여러 언어를 지원하는 프로세스 간 통신 수단 (IPC)로 확장할 수 있다는 점도 매력적이라고 생각합니다.!

9개의 좋아요

저는 MSA 앱에서 redis 대신 garnet을 넣어서 테스트 해 보았습니다. 매끄럽게 잘 동작하고, 메모리 서버 역할도, 세션 DB 어뎁터로도 잘 동작했습니다. 중요한 건 다른 팀원들은 garnet을 사용 중이라는 걸 모르셨다는거죠 :rocket:. redis를 못 쓰는 상황이 온다면 바로 garnet으로 전환할 준비가 되어있습니다 :smiling_face:

11개의 좋아요