본문 바로가기
ASP.NET Core

.NET 6 API with Redis] 3. Model , Repository, Controller구성

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

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

 

1. Application architecture

2. Model

Platform.cs

using System.ComponentModel.DataAnnotations;

namespace RedisAPI.Models
{
    public class Platform
    {
        [Required]
        public string Id { get; set; } = $"platform:{Guid.NewGuid().ToString()}";
        [Required]
        public string Name { get; set; } = string.Empty;
    }
}

 

3. Repository

IPlatformRepo.cs

using RedisAPI.Models;

namespace RedisAPI.Data
{
    public interface IPlatformRepo
    {
        void CreatePlatform(Platform plat);
        Platform GetPlatformById(string id);
        IEnumerable<Platform> GetPlatforms();

    }

}

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);
            //redis-cli에서 사용했던, set command와 동일하다. 
        }

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

            var plat = db.StringGet(id);

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

            return null;
        }

        public IEnumerable<Platform> GetPlatforms()
        {
            throw new NotImplementedException();
        }
    }
}

Program.cs

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddSingleton<IConnectionMultiplexer>(opt => 
    ConnectionMultiplexer.Connect(builder.Configuration.GetConnectionString("RedisConnection")));

builder.Services.AddScoped<IPlatformRepo, RedisPlatformRepo>();

builder.Services.AddControllers();

4. Controller

PlatformsController.cs

using Microsoft.AspNetCore.Mvc;
using RedisAPI.Data;
using RedisAPI.Models;

namespace RedisAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class PlatformsController : ControllerBase
    {
        private readonly IPlatformRepo _repository;

        public PlatformsController(IPlatformRepo repository)
        {
            _repository = repository;
        }

        [HttpGet("{id}", Name="GetPlatformById")]
        public ActionResult <IEnumerable<Platform>> GetPlatformById(string id)
        {
            var platform = _repository.GetPlatformById(id);
            
            if (platform != null)
            {
                return Ok(platform);
            }

            return NotFound();
        }

        [HttpPost]
        public ActionResult <Platform> CreatePlatform(Platform platform)
        {
            _repository.CreatePlatform(platform);

            return CreatedAtRoute(nameof(GetPlatformById), new {Id = platform.Id}, platform);
        }
    }
}

PS C:\Users\admin\source\repos\RedisAPI\RedisAPI> dotnet run

프로젝트 실행하여 api 호출 테스트해보자. 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

redis-cli로 저장된 데이터를 확인해보자.

root@130a5acf8844:/data# redis-cli
127.0.0.1:6379> scan 0
1) "0"
2) 1) "platform:1bcd51db-c301-4e7d-914e-eebc294adc79"
   2) "platform:85271e45-0d46-4317-aa9c-2a36625528cf"
   3) "platform:3ef0a6ca-7070-4107-a905-26bfa4ee338b"
   4) "platform:f82d5fb2-8d97-453e-8fad-bc09766634a4"
   5) "platform:82be7e47-9e79-4291-b363-b3aedb939ee1"
   6) "platform:4fa05050-6c2d-4d9e-8f4e-2e0191b57799"
   7) "platform:869d5d6e-f755-4cbd-a6ba-8401777e68ac"
127.0.0.1:6379> get platform:1bcd51db-c301-4e7d-914e-eebc294adc79
"{\"Id\":\"platform:1bcd51db-c301-4e7d-914e-eebc294adc79\",\"Name\":\"Redis\"}"
728x90
반응형

댓글