Created
February 4, 2021 20:08
-
-
Save skalahonza/a889336f819a34fd59b79b0939a78cac to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class AzureTableStorageCache : IDistributedCache | |
{ | |
private readonly AzureTableStorageCacheOptions _options; | |
private readonly CloudTable _table; | |
public AzureTableStorageCache(IOptions<AzureTableStorageCacheOptions> options) | |
{ | |
_options = options.Value; | |
var tableClient = CloudStorageAccount.Parse(_options.ConnectionString).CreateCloudTableClient(); | |
_table = tableClient.GetTableReference(_options.TableName); | |
_table.CreateIfNotExists(); | |
} | |
public byte[] Get(string key) => | |
GetAsync(key).Result; | |
public async Task<byte[]> GetAsync(string key, CancellationToken token = default) | |
{ | |
var result = await _table.ExecuteAsync(TableOperation.Retrieve<CachedItem>(_options.PartitionKey, key), token); | |
var item = result.Result as CachedItem; | |
if (item.IsExpired) | |
{ | |
await RemoveAsync(key, token); | |
return null; | |
} | |
return item?.Data; | |
} | |
public void Refresh(string key) => | |
RefreshAsync(key).Wait(); | |
public Task RefreshAsync(string key, CancellationToken token = default) => | |
Task.CompletedTask; | |
public void Remove(string key) => | |
RemoveAsync(key).Wait(); | |
public Task RemoveAsync(string key, CancellationToken token = default) => | |
_table.ExecuteAsync(TableOperation.Delete(new CachedItem(_options.PartitionKey) | |
{ | |
RowKey = key, | |
ETag = "*" | |
}), token); | |
public void Set(string key, byte[] value, DistributedCacheEntryOptions options) => | |
SetAsync(key, value, options).Wait(); | |
public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options, CancellationToken token = default) => | |
_table.ExecuteAsync(TableOperation.InsertOrReplace(new CachedItem(_options.PartitionKey) | |
{ | |
RowKey = key, | |
ETag = "*", | |
Data = value, | |
AbsoluteExpiration = options.AbsoluteExpiration | |
}), token); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment