Skip to content

Commit ee4c788

Browse files
Complete Polly
1 parent 8d0a0c3 commit ee4c788

File tree

1 file changed

+21
-12
lines changed

1 file changed

+21
-12
lines changed

src/SwiftLink.Infrastructure/CacheProvider/RedisCacheProvider.cs

Lines changed: 21 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
using Microsoft.EntityFrameworkCore.Metadata;
1+
using Azure;
2+
using Microsoft.EntityFrameworkCore.Metadata;
23
using Microsoft.EntityFrameworkCore.Metadata.Internal;
34
using Microsoft.Extensions.Caching.Distributed;
45
using 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

Comments
 (0)