added user caching

This commit is contained in:
Nicolas Constant 2021-01-17 23:05:00 -05:00
parent ee9951b98e
commit 22df5d2356
No known key found for this signature in database
GPG key ID: 1E9F677FB01A5688
3 changed files with 59 additions and 2 deletions

View file

@ -5,6 +5,7 @@
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.Extensions.Caching.Memory" Version="5.0.0" />
<PackageReference Include="TweetinviAPI" Version="4.0.3" /> <PackageReference Include="TweetinviAPI" Version="4.0.3" />
</ItemGroup> </ItemGroup>

View file

@ -0,0 +1,52 @@
using System;
using BirdsiteLive.Twitter.Models;
using Microsoft.Extensions.Caching.Memory;
namespace BirdsiteLive.Twitter
{
public class CachedTwitterService : ITwitterService
{
private readonly ITwitterService _twitterService;
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
.SetAbsoluteExpiration(TimeSpan.FromDays(30));
#region Ctor
public CachedTwitterService(ITwitterService twitterService)
{
_twitterService = twitterService;
}
#endregion
public TwitterUser GetUser(string username)
{
if (!_userCache.TryGetValue(username, out TwitterUser user))
{
user = _twitterService.GetUser(username);
_userCache.Set(username, user, _cacheEntryOptions);
}
return user;
}
public ExtractedTweet GetTweet(long statusId)
{
return _twitterService.GetTweet(statusId);
}
public ExtractedTweet[] GetTimeline(string username, int nberTweets, long fromTweetId = -1)
{
return _twitterService.GetTimeline(username, nberTweets, fromTweetId);
}
}
}

View file

@ -9,6 +9,7 @@ using BirdsiteLive.DAL.Contracts;
using BirdsiteLive.DAL.Postgres.DataAccessLayers; using BirdsiteLive.DAL.Postgres.DataAccessLayers;
using BirdsiteLive.DAL.Postgres.Settings; using BirdsiteLive.DAL.Postgres.Settings;
using BirdsiteLive.Models; using BirdsiteLive.Models;
using BirdsiteLive.Twitter;
using Lamar; using Lamar;
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Hosting;
@ -83,6 +84,9 @@ namespace BirdsiteLive
throw new NotImplementedException($"{dbSettings.Type} is not supported"); throw new NotImplementedException($"{dbSettings.Type} is not supported");
} }
services.For<ITwitterService>().DecorateAllWith<CachedTwitterService>();
services.For<ITwitterService>().Use<TwitterService>().Singleton();
services.Scan(_ => services.Scan(_ =>
{ {
_.Assembly("BirdsiteLive.Twitter"); _.Assembly("BirdsiteLive.Twitter");