using Microsoft.Extensions.Logging;
|
using Microsoft.Extensions.Options;
|
using WIDESEAWCS_RedisService.Connection;
|
using WIDESEAWCS_RedisService.Options;
|
|
namespace WIDESEAWCS_RedisService.Counter
|
{
|
public class RedisCounterService : ICounterService
|
{
|
private readonly IRedisConnectionManager _connectionManager;
|
private readonly RedisOptions _options;
|
private readonly ILogger<RedisCounterService> _logger;
|
|
public RedisCounterService(
|
IRedisConnectionManager connectionManager,
|
IOptions<RedisOptions> options,
|
ILogger<RedisCounterService> logger)
|
{
|
_connectionManager = connectionManager;
|
_options = options.Value;
|
_logger = logger;
|
}
|
|
private string BuildKey(string key) => $"{_options.KeyPrefix}counter:{key}";
|
|
public long Increment(string key, long value = 1)
|
{
|
return _connectionManager.GetDatabase().StringIncrement(BuildKey(key), value);
|
}
|
|
public long Decrement(string key, long value = 1)
|
{
|
return _connectionManager.GetDatabase().StringDecrement(BuildKey(key), value);
|
}
|
|
public long GetCount(string key)
|
{
|
var val = _connectionManager.GetDatabase().StringGet(BuildKey(key));
|
return val.IsNullOrEmpty ? 0 : (long)val;
|
}
|
|
public bool Reset(string key)
|
{
|
return _connectionManager.GetDatabase().KeyDelete(BuildKey(key));
|
}
|
|
public long IncrementWithExpiry(string key, TimeSpan expiry, long value = 1)
|
{
|
var db = _connectionManager.GetDatabase();
|
var fullKey = BuildKey(key);
|
var result = db.StringIncrement(fullKey, value);
|
if (result == value)
|
db.KeyExpire(fullKey, expiry);
|
return result;
|
}
|
}
|
}
|