BirdsiteLive/src/BirdsiteLive.Twitter/CachedTwitterService.cs

52 lines
1.6 KiB
C#
Raw Normal View History

2021-01-18 05:05:00 +01:00
using System;
using BirdsiteLive.Twitter.Models;
using Microsoft.Extensions.Caching.Memory;
namespace BirdsiteLive.Twitter
{
2021-02-03 04:49:37 +01:00
public interface ICachedTwitterUserService : ITwitterUserService
{
void PurgeUser(string username);
}
public class CachedTwitterUserService : ICachedTwitterUserService
2021-01-18 05:05:00 +01:00
{
private readonly ITwitterUserService _twitterService;
2021-01-18 05:05:00 +01:00
private MemoryCache _userCache = new MemoryCache(new MemoryCacheOptions()
{
SizeLimit = 5000
});
private MemoryCacheEntryOptions _cacheEntryOptions = new MemoryCacheEntryOptions()
.SetSize(1)//Size amount
//Priority on removing when reaching size limit (memory pressure)
.SetPriority(CacheItemPriority.High)
// Keep in cache for this time, reset time if accessed.
.SetSlidingExpiration(TimeSpan.FromHours(24))
// Remove from cache after this time, regardless of sliding expiration
2021-02-03 07:04:32 +01:00
.SetAbsoluteExpiration(TimeSpan.FromDays(7));
2021-01-18 05:05:00 +01:00
#region Ctor
public CachedTwitterUserService(ITwitterUserService twitterService)
2021-01-18 05:05:00 +01:00
{
_twitterService = twitterService;
}
#endregion
public TwitterUser GetUser(string username)
{
if (!_userCache.TryGetValue(username, out TwitterUser user))
{
user = _twitterService.GetUser(username);
2021-01-27 09:27:04 +01:00
if(user != null) _userCache.Set(username, user, _cacheEntryOptions);
2021-01-18 05:05:00 +01:00
}
return user;
}
public void PurgeUser(string username)
{
_userCache.Remove(username);
}
2021-01-18 05:05:00 +01:00
}
}