zhaolei
2020-11-20 921de2254ff5712a44ed8575ee8efe34252f6603
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
#if !NET45
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Options;
#else
using System.Web;
#endif
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
 
namespace Prow.Cache
{
    /// <summary>
    /// Cache 内部默认实现类
    /// </summary>
    internal class DefaultCache : ICache
    {
        private readonly ConcurrentDictionary<string, Lazy<AutoExpireCacheEntry<object>>> _cachePool = new ConcurrentDictionary<string, Lazy<AutoExpireCacheEntry<object>>>();
        private readonly HttpClient _client;
        private CacheOptions _cacheOptions;
        public const string HttpClientName = "CacheList";
#if !NET45
        private readonly IHttpContextAccessor _accessor;
        /// <summary>
        /// ICache 实例
        /// </summary>
        public static ICache? Instance { get; private set; }
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public DefaultCache(IOptionsMonitor<CacheOptions> options, IHttpContextAccessor httpContextAccessor, IHttpClientFactory factory)
        {
            _client = factory.CreateClient(HttpClientName);
            _accessor = httpContextAccessor;
            options.OnChange(op =>
            {
                _cachePool.Clear();
                CorsClear(new List<string>() { "*" });
                _cacheOptions = op;
            });
            _cacheOptions = options.CurrentValue;
            Instance = this;
        }
#else
        /// <summary>
        /// 默认构造函数
        /// </summary>
        public DefaultCache()
        {
            _client = new HttpClient();
            _cacheOptions = CacheSection.GetOptions();
            _client.DefaultRequestHeaders.Connection.Add("keep-alive");
        }
#endif
 
        /// <summary>
        /// 通过指定 Key 获得配置缓存元素
        /// </summary>
        /// <param name="key">缓存真正使用的 Key</param>
        /// <param name="profileKey">配置文件中的 Key</param>
        /// <returns>CacheOption 实例</returns>
        private CacheOption RetrieveCacheOptionByKey(string key, string? profileKey)
        {
            CacheOption? option = null;
            if (_cacheOptions.Enabled) option = _cacheOptions.CacheItems.FirstOrDefault(item => item.Key == (profileKey ?? key));
            if (option == null) option = new CacheOption() { Enabled = false, Key = profileKey ?? key };
            return option;
        }
 
        /// <summary>
        /// 获取或者添加缓存方法
        /// </summary>
        /// <typeparam name="T">缓存类型</typeparam>
        /// <param name="key">缓存键值</param>
        /// <param name="valueFactory">生成值的回调方法返回值</param>
        /// <param name="profileKey">为空时,使用缓存Key</param>
        /// <returns></returns>
        public T GetOrAdd<T>(string key, Func<string, T> valueFactory, string? profileKey = null) => InternalGetOrAddOrUpdate(key, valueFactory, op => _cachePool.GetOrAdd(key, k => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, valueFactory(k)))), profileKey);
 
        /// <summary>
        /// 获取或者添加缓存方法
        /// </summary>
        /// <typeparam name="T">缓存类型</typeparam>
        /// <param name="option">ICacheOption 实例</param>
        /// <param name="valueFactory">创建缓存值回调方法</param>
        /// <returns></returns>
        public T GetOrAdd<T>(ICacheOption option, Func<string, T> valueFactory) => InternalGetOrAddOrUpdate(option, valueFactory, op => _cachePool.GetOrAdd(op.Key, k => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, valueFactory(k)))));
 
        /// <summary>
        /// 添加或者更新缓存方法
        /// </summary>
        /// <typeparam name="T">缓存类型</typeparam>
        /// <param name="key">缓存键值</param>
        /// <param name="valueFactory">创建缓存值回调方法</param>
        /// <param name="updateFactory">更新缓存值回调方法</param>
        /// <param name="profileKey">为空时,使用缓存Key</param>
        /// <returns></returns>
        public T AddOrUpdate<T>(string key, Func<string, T> valueFactory, Func<string, T, T> updateFactory, string? profileKey = null) => InternalGetOrAddOrUpdate(key, valueFactory, op => _cachePool.AddOrUpdate(key, k => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, valueFactory(k))), (k, c) => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, updateFactory(k, (T)c.Value.Value)))), profileKey);
 
        /// <summary>
        /// 添加或者更新缓存方法
        /// </summary>
        /// <typeparam name="T">缓存类型</typeparam>
        /// <param name="option">ICacheOption 实例</param>
        /// <param name="valueFactory">创建缓存值回调方法</param>
        /// <param name="updateFactory">更新缓存值回调方法</param>
        /// <returns></returns>
        public T AddOrUpdate<T>(ICacheOption option, Func<string, T> valueFactory, Func<string, T, T> updateFactory) => InternalGetOrAddOrUpdate(option, valueFactory, op => _cachePool.AddOrUpdate(op.Key, k => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, valueFactory(k))), (k, c) => new Lazy<AutoExpireCacheEntry<object>>(() => CreateCacheEntry(k, op, updateFactory(k, (T)c.Value.Value)))));
 
        private T InternalGetOrAddOrUpdate<T>(string key, Func<string, T> valueFactory, Func<ICacheOption, Lazy<AutoExpireCacheEntry<object>>> callback, string? profileKey = null)
        {
            var option = RetrieveCacheOptionByKey(key, profileKey);
            return option.Enabled ? InternalGetOrAddOrUpdate(option, valueFactory, callback) : valueFactory(key);
        }
 
#nullable disable
        private T InternalGetOrAddOrUpdate<T>(ICacheOption option, Func<string, T> valueFactory, Func<ICacheOption, Lazy<AutoExpireCacheEntry<object>>> callback)
        {
            // -1 表示永久缓存
            if (option.Interval < 1 && option.Interval != -1) return valueFactory(option.Key);
            var entry = callback(option);
            if (entry.Value?.Value == null) { ClearByKey(option.Key); return default; }
            if (option.SlidingExpiration) entry.Value.Reset();
            return (T)entry.Value.Value;
        }
 
        private AutoExpireCacheEntry<object> CreateCacheEntry(string key, ICacheOption option, object value)
        {
            return new AutoExpireCacheEntry<object>(value, option.Interval, _ => ClearByKey(key)) { Desc = option.Desc };
        }
 
        /// <summary>
        /// 通过指定 Key 获取缓存方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key">指定 Key</param>
        /// <returns>缓存内的值</returns>
        public T Get<T>(string key)
        {
            return _cachePool.TryGetValue(key, out var item) ? (T)item.Value.Value : default;
        }
#nullable restore
 
        /// <summary>
        /// 缓存总数
        /// </summary>
        /// <returns></returns>
        public int Count => _cachePool.Count;
 
        /// <summary>
        /// 清除指定 key 集合方法
        /// </summary>
        /// <param name="keys"></param>
        public void Clear(IEnumerable<string> keys)
        {
            keys.ToList().ForEach(Clear);
        }
 
        /// <summary>
        /// 清除指定 key 方法
        /// </summary>
        /// <param name="key">结尾支持通配符*</param>
        public void Clear(string? key = null)
        {
            if (string.IsNullOrEmpty(key))
            {
                _cachePool.Clear();
                return;
            }
#nullable disable
            if (key.EndsWith("*", StringComparison.OrdinalIgnoreCase))
                _cachePool.Keys.Where(k => k.StartsWith(key.TrimEnd('*'), StringComparison.OrdinalIgnoreCase)).ToList().ForEach(ClearByKey);
            else
                ClearByKey(key);
#nullable restore
        }
 
        private void ClearByKey(string key)
        {
            if (_cachePool.TryRemove(key, out var d))
            {
                d.Value.Dispose();
            }
        }
 
        /// <summary>
        /// 跨域清除指定 key 集合缓存方法
        /// </summary>
        /// <param name="keys"></param>
        public void CorsClear(IEnumerable<string> keys)
        {
            if (!_cacheOptions.Enabled) return;
 
            // 得到配置文件 CacheManagerCors 小节数据
            // 循环多站点
            _cacheOptions.CorsItems.Where(item => item.Enabled && !item.Self).AsParallel().ForAll(async ele =>
            {
                // 多个 Key 请求一次
                try
                {
                    var url = string.Empty;
                    var request = new HttpRequestMessage();
#if !NET45
                    var httpReq = _accessor.HttpContext?.Request;
                    if (httpReq == null) return;
                    var baseUrl = $"{httpReq.Scheme}://{httpReq.Host}{httpReq.PathBase}";
#else
                    var httpReq = HttpContext.Current.Request;
                    if (httpReq == null) return;
                    var baseUrl = $"{httpReq.Url.Scheme}://{httpReq.Url.Authority}";
#endif
                    url = (ele.Url?.Any(c => c == ':') ?? false) ? ele.Url ?? "" : $"{baseUrl}/{ele.Url}";
                    var cookie = httpReq.Headers["Cookie"];
                    request.Headers.Add("Cookie", cookie.ToString());
                    request.RequestUri = new Uri($"{url}?cacheKey={string.Join("|", keys)}");
                    await _client.SendAsync(request);
                }
                catch { }
            });
        }
 
        /// <summary>
        /// ToList 类型转化
        /// </summary>
        /// <returns></returns>
        public IEnumerable<ICacheItem> ToList()
        {
            return _cachePool.Select(item => new CacheItem(item.Key)
            {
                Interval = item.Value.Value?.Period ?? 0,
                Desc = item.Value.Value?.Desc,
                Value = item.Value.Value?.Value?.GetType().Name,
                ElapsedSeconds = (int)DateTimeOffset.Now.Subtract(item.Value.Value?.CreateTime ?? DateTimeOffset.Now).TotalSeconds
            }).Where(item => item.Interval > 0) ?? new CacheItem[0];
        }
 
        /// <summary>
        /// 获取 缓存所有键值集合
        /// </summary>
        public IEnumerable<string> Keys
        {
            get { return _cachePool.Keys; }
        }
 
        /// <summary>
        /// 获取 所有跨域缓存配置项集合
        /// </summary>
        public IEnumerable<ICacheCorsItem> CorsSites { get { return _cacheOptions.Enabled ? _cacheOptions.CorsItems.Where(item => item.Enabled) : Enumerable.Empty<ICacheCorsItem>(); } }
    }
}