1- using Microsoft . EntityFrameworkCore . Metadata ;
1+ using Azure ;
2+ using Microsoft . EntityFrameworkCore . Metadata ;
23using Microsoft . EntityFrameworkCore . Metadata . Internal ;
34using Microsoft . Extensions . Caching . Distributed ;
45using Microsoft . Extensions . Options ;
@@ -13,8 +14,11 @@ public class RedisCacheService(IDistributedCache cache, IOptions<AppSettings> op
1314 : ICacheProvider
1415{
1516
16- private readonly AsyncCircuitBreakerPolicy < bool > circuitBreakerPolicy = Policy < bool > . HandleResult ( false )
17- . CircuitBreakerAsync ( 2 , TimeSpan . FromSeconds ( 30 ) ) ;
17+ private readonly AsyncCircuitBreakerPolicy < bool > setCacheCircuitBreaker = Policy < bool > . HandleResult ( false )
18+ . CircuitBreakerAsync ( 1 , TimeSpan . FromSeconds ( 60 ) ) ;
19+
20+ private readonly AsyncCircuitBreakerPolicy < string > getCacheCircuitBreaker = Policy < string > . HandleResult ( ( r ) => { return r is null ; } )
21+ . CircuitBreakerAsync ( 1 , TimeSpan . FromSeconds ( 60 ) ) ;
1822
1923 private readonly IDistributedCache _cache = cache ;
2024 private readonly AppSettings _options = options . Value ;
@@ -27,9 +31,9 @@ public async Task<bool> Set(string key, string value)
2731
2832 public async Task < bool > Set ( string key , string value , DateTime expirationDate )
2933 {
30- if ( circuitBreakerPolicy . CircuitState is CircuitState . Open )
34+ if ( setCacheCircuitBreaker . CircuitState is CircuitState . Open )
3135 return false ;
32- return await circuitBreakerPolicy . ExecuteAsync ( async ( ) =>
36+ return await setCacheCircuitBreaker . ExecuteAsync ( async ( ) =>
3337 {
3438 try
3539 {
@@ -51,13 +55,18 @@ public async Task<bool> Set(string key, string value, DateTime expirationDate)
5155
5256 public async Task < string > Get ( string key )
5357 {
54- try
55- {
56- return await _cache . GetStringAsync ( key ) ;
57- }
58- catch
59- {
58+ if ( getCacheCircuitBreaker . CircuitState is CircuitState . Open )
6059 return null ;
61- }
60+ return await getCacheCircuitBreaker . ExecuteAsync ( async ( ) =>
61+ {
62+ try
63+ {
64+ return await _cache . GetStringAsync ( key ) ;
65+ }
66+ catch ( RedisConnectionException )
67+ {
68+ return null ;
69+ }
70+ } ) ;
6271 }
6372}
0 commit comments