ASP.NET WebAPI에서 캐시를 사용하고 싶다면 CacheOutput이라는 도구를 활용할 수 있습니다. 이 기사에서는 Redis를 통해 캐시를 구현하는 방법을 설명합니다.
기본 사용 방법
CacheOutput 애ต리뷰트
[Route("get")]
[CacheOutput(ClientTimeSpan = 60, ServerTimeSpan = 60)]
public IEnumerable<string> Get()
{
return new string[] { "홍길동", "이상무" };
}
쿼리 문자열을 제외한 키 사용
[Route("get")]
[CacheOutput(ServerTimeSpan = 50, ExcludeQueryStringFromCacheKey = true)]
public string Get(int userId)
{
return DateTime.Now.ToString();
}
Redis를 사용하기 위해 StackExchange.Redis 라이브러리를 설치합니다.
Install-Package StackExchange.Redis.StrongName
애플리케이션 컨테이너에 Redis 연결을 등록합니다.
var builder = new ContainerBuilder();
builder.Register(r =>
{
return ConnectionMultiplexer.Connect(DBSetting.Redis);
}).AsSelf().SingleInstance();
var container = builder.Build();
GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);
Redis 서비스를 통해 데이터를 가져오는 예제입니다.
public class RedisService : IRedisService
{
private readonly ConnectionMultiplexer _connectionMultiplexer;
public RedisService(ConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
}
public async Task<WebAPIResponse> GetData(string key)
{
try
{
var db = _connectionMultiplexer.GetDatabase();
return await db.StringGetAsync(key);
}
catch (Exception ex)
{
logger.Error(ex, "RedisService GetData Exception : " + ex.Message);
return new WebAPIResponse
{
IsError = false,
Msg = string.Empty,
Data = string.Empty
};
}
}
}
CacheOutput과 Redis의 통합
IApiOutputCache 인터페이스를 구현하여 Redis를 사용할 수 있습니다.
public interface IApiOutputCache
{
T GetData<T>(string key) where T : class;
object GetData(string key);
void Remove(string key);
void RemoveStartsWith(string key);
bool Contains(string key);
void SetData(string key, object data, DateTimeOffset expiration, string dependsOnKey = null);
}
Redis를 통해 캐시를 구현하는 예제입니다.
public class RedisCacheProvider : IApiOutputCache
{
private readonly ConnectionMultiplexer _connectionMultiplexer;
public RedisCacheProvider(ConnectionMultiplexer connectionMultiplexer)
{
_connectionMultiplexer = connectionMultiplexer;
}
public void SetData(string key, object data, DateTimeOffset expiration, string dependsOnKey = null)
{
throw new NotImplementedException();
}
public bool Contains(string key)
{
throw new NotImplementedException();
}
public object GetData(string key)
{
var db = _connectionMultiplexer.GetDatabase();
return db.StringGet(key);
}
public T GetData<T>(string key) where T : class
{
throw new NotImplementedException();
}
public void Remove(string key)
{
throw new NotImplementedException();
}
public void RemoveStartsWith(string key)
{
throw new NotImplementedException();
}
}
WebAPI 구성에 Redis 캐시를 등록합니다.
configuration.CacheOutputConfiguration().RegisterCacheOutputProvider(() => new RedisCacheProvider());
참고자료:
- Azure Redis Cache 둘러보기: https://msdn.microsoft.com/en-us/library/azure/dn798898.aspx
- ASP.NET 출력 캐시 제공자: https://msdn.microsoft.com/en-us/library/azure/dn798898.aspx
- Web API에서 캐시 사용 방법: https://msdn.microsoft.com/en-us/library/azure/dn690521.aspx