Skip to content

Instantly share code, notes, and snippets.

@skalahonza
Created February 4, 2021 20:08
Show Gist options
  • Save skalahonza/a889336f819a34fd59b79b0939a78cac to your computer and use it in GitHub Desktop.
Save skalahonza/a889336f819a34fd59b79b0939a78cac to your computer and use it in GitHub Desktop.
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