1
+ using Microsoft . AspNetCore . OutputCaching ;
2
+ using ServiceStack . Redis ;
3
+
4
+ [ assembly: HostingStartup ( typeof ( BlazorOutputCaching . ConfigureOutputCache ) ) ]
5
+
6
+ namespace BlazorOutputCaching ;
7
+
8
+ public class ConfigureOutputCache : IHostingStartup
9
+ {
10
+ public void Configure ( IWebHostBuilder builder )
11
+ {
12
+ builder . ConfigureServices ( services =>
13
+ {
14
+ services . AddSingleton < IRedisClientsManager > ( c =>
15
+ new BasicRedisClientManager ( "localhost:6379" ) ) ;
16
+ services . AddSingleton < IOutputCacheStore , RedisOutputCacheStore > ( ) ;
17
+ } ) ;
18
+ }
19
+ }
20
+
21
+ public class RedisOutputCacheStore ( IRedisClientsManager redisManager ) : IOutputCacheStore
22
+ {
23
+ public async ValueTask < byte [ ] ? > GetAsync ( string key , CancellationToken cancellationToken )
24
+ {
25
+ await using var redis = await redisManager . GetClientAsync ( token : cancellationToken ) ;
26
+ var value = await redis . GetAsync < byte [ ] > ( key , cancellationToken ) ;
27
+ return value ;
28
+ }
29
+
30
+ public async ValueTask SetAsync ( string key , byte [ ] value , string [ ] ? tags , TimeSpan validFor , CancellationToken cancellationToken )
31
+ {
32
+ await using var redis = await redisManager . GetClientAsync ( token : cancellationToken ) ;
33
+
34
+ // First persist in normal cache hashset
35
+ await redis . SetAsync ( key , value , validFor , cancellationToken ) ;
36
+
37
+ if ( tags == null )
38
+ return ;
39
+ foreach ( var tag in tags )
40
+ {
41
+ await redis . AddItemToSetAsync ( $ "tag:{ tag } ", key , cancellationToken ) ;
42
+ }
43
+ }
44
+
45
+ public async ValueTask EvictByTagAsync ( string tag , CancellationToken cancellationToken )
46
+ {
47
+ await using var redis = await redisManager . GetClientAsync ( token : cancellationToken ) ;
48
+
49
+ var keys = await redis . GetAllItemsFromListAsync ( $ "tag:{ tag } ", cancellationToken ) ;
50
+
51
+ foreach ( var key in keys )
52
+ {
53
+ await redis . RemoveEntryAsync ( key ) ;
54
+ await redis . RemoveItemFromSetAsync ( $ "tag:{ tag } ", key , cancellationToken ) ;
55
+ }
56
+ }
57
+ }
0 commit comments