wanshenmean
3 天以前 5e851678cc02257bbbd179446de36082430ca5bc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
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;
        }
    }
}