본문 바로가기
ASP.NET Core

.NET 6 API with Redis] 4. API using Hashes Data Type

by Fastlane 2022. 5. 18.
728x90
반응형

출처 : https://dotnetplaybook.com/redis-as-a-primary-database/

 

이제까지 Strings Data Type만 사용하여 api를 구현하였다. structure objects를 저장하는데 Strings보다는 Hashes가 더 알맞다. 

 

Strings

1 to 1 mapping between Key and Value

Set using SET

Returned using GET

 

Hashes

1 to multiple mapping between Key and Field / Value pairs

Stores Field / Value pairs

Set using HMSET

Get all items using HGETALL

Get individual items using HGET

 

 

Repository Pattern을 사용했기 때문에, Controller는 수정할 필요가 없다. 

RedisPlatformRepo.cs 파일만 수정해보자. 

using System.Text.Json;
using RedisAPI.Models;
using StackExchange.Redis;

namespace RedisAPI.Data
{
    public class RedisPlatformRepo : IPlatformRepo
    {
        private readonly IConnectionMultiplexer _redis;

        public RedisPlatformRepo(IConnectionMultiplexer redis)
        {
            _redis = redis;    
        }

        public void CreatePlatform(Platform plat)
        {
            if(plat == null)
            {
                throw new ArgumentOutOfRangeException(nameof(plat));
            }


            var db = _redis.GetDatabase();

            var serialPlat = JsonSerializer.Serialize(plat);

            //db.StringSet(plat.Id, serialPlat);

            db.HashSet("hashplatform", new HashEntry[]{new HashEntry(plat.Id, serialPlat)});
        }

        public Platform? GetPlatformById(string id)
        {
            var db = _redis.GetDatabase();

            //var plat = db.StringGet(id);

            var plat = db.HashGet("hashplatform", id);

            if (!string.IsNullOrEmpty(plat))
            {
                return JsonSerializer.Deserialize<Platform>(plat);
            }

            return null;
        }

        public IEnumerable<Platform?>? GetAllPlatforms()
        {
            var db = _redis.GetDatabase();

            var completeHash = db.HashGetAll("hashplatform");

            if(completeHash.Length > 0){
                var obj = Array.ConvertAll(completeHash, val => JsonSerializer.Deserialize<Platform>(val.Value)).ToList<Platform>();

                return obj;
            }
            
            return null;
        }
    }
}

 

728x90
반응형

댓글