1- using Microsoft . Extensions . Caching . Distributed ;
1+ using Microsoft . EntityFrameworkCore . Metadata ;
2+ using Microsoft . EntityFrameworkCore . Metadata . Internal ;
3+ using Microsoft . Extensions . Caching . Distributed ;
24using Microsoft . Extensions . Options ;
5+ using Polly ;
6+ using Polly . CircuitBreaker ;
7+ using StackExchange . Redis ;
38using System . Text ;
49
510namespace SwiftLink . Infrastructure . CacheProvider ;
611
712public class RedisCacheService ( IDistributedCache cache , IOptions < AppSettings > options )
813 : ICacheProvider
914{
15+
16+ private readonly AsyncCircuitBreakerPolicy < bool > circuitBreakerPolicy = Policy < bool > . HandleResult ( false )
17+ . CircuitBreakerAsync ( 2 , TimeSpan . FromSeconds ( 30 ) ) ;
18+
1019 private readonly IDistributedCache _cache = cache ;
1120 private readonly AppSettings _options = options . Value ;
1221
@@ -18,25 +27,37 @@ public async Task<bool> Set(string key, string value)
1827
1928 public async Task < bool > Set ( string key , string value , DateTime expirationDate )
2029 {
21- try
22- {
23- DistributedCacheEntryOptions cacheEntryOptions = new ( )
30+ if ( circuitBreakerPolicy . CircuitState is CircuitState . Open )
31+ return false ;
32+ return await circuitBreakerPolicy . ExecuteAsync ( async ( ) =>
2433 {
25- SlidingExpiration = TimeSpan . FromHours ( _options . Redis . SlidingExpirationHour ) ,
26- AbsoluteExpiration = expirationDate ,
27- } ;
34+ try
35+ {
36+ DistributedCacheEntryOptions cacheEntryOptions = new ( )
37+ {
38+ SlidingExpiration = TimeSpan . FromHours ( _options . Redis . SlidingExpirationHour ) ,
39+ AbsoluteExpiration = expirationDate ,
40+ } ;
41+ var dataToCache = Encoding . UTF8 . GetBytes ( value ) ;
42+ await _cache . SetAsync ( key , dataToCache , cacheEntryOptions ) ;
43+ }
44+ catch ( RedisConnectionException )
45+ {
46+ return false ;
47+ }
48+ return true ;
49+ } ) ;
50+ }
2851
29- var dataToCache = Encoding . UTF8 . GetBytes ( value ) ;
30- await _cache . SetAsync ( key , dataToCache , cacheEntryOptions ) ;
31- return true ;
52+ public async Task < string > Get ( string key )
53+ {
54+ try
55+ {
56+ return await _cache . GetStringAsync ( key ) ;
3257 }
33- catch ( Exception e )
58+ catch
3459 {
35- //Log e
36- return false ;
60+ return null ;
3761 }
3862 }
39-
40- public async Task < string > Get ( string key )
41- => await _cache . GetStringAsync ( key ) ;
42- }
63+ }
0 commit comments