姜友瑶
2022-05-04 ecd015fd9320ced39a5dc1942f20997f294f3016
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
package com.matrix.system.common.init;
 
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.matrix.core.tools.LogUtil;
import com.matrix.core.tools.StringUtils;
import com.matrix.system.common.bean.SysCacheValue;
import com.matrix.system.common.dao.SysCacheValueDao;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
 
import java.lang.reflect.Type;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
 
@Component
public class LocalCache implements ApplicationRunner {
 
    /*
     * 清理线程运行状态 0 未启动,1 已启动
     */
    private static int CLEAR_THREAD_STATUS = 0;
 
 
    private static ConcurrentMap<String, CacheValue> localCache = new ConcurrentHashMap(60);
 
    private static ConcurrentLinkedQueue<Long> deadCache = new ConcurrentLinkedQueue<>();
 
    @Autowired
    private SysCacheValueDao sysCacheValueDao;
 
    @Override
    public void run(ApplicationArguments args) {
        //初始化缓存
        List<SysCacheValue> sysCacheValues = sysCacheValueDao.selectByMap(null);
        if(CollUtil.isNotEmpty(sysCacheValues)){
            LogUtil.debug("初始化缓存");
            localCache.putAll(buildValues(sysCacheValues));
        }
        startClearThread();
        startSaveStoreThread();
    }
 
    private Map<String,CacheValue> buildValues(List<SysCacheValue> sysCacheValues) {
        Map<String,CacheValue> storeCache=new HashMap<>();
        sysCacheValues.forEach(e->{
            CacheValue cacheValue=new CacheValue();
            BeanUtil.copyProperties(e,cacheValue);
            storeCache.put(cacheValue.getCacheKey(),cacheValue);
        });
        return storeCache;
    }
 
    /**
     * 根据key匹配多个缓存值
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> Map<String, T> getValues(String key) {
        return localCache.entrySet().stream()
                .filter(item -> StringUtils.isMatch(key, item.getKey()))
                .map(Map.Entry::getValue)
                .filter(item -> Objects.nonNull(item.cacheValue))
                .collect(Collectors.toMap(CacheValue::getCacheKey, item -> JSONObject.parseObject(item.cacheValue, new TypeReference<T>(){})));
    }
 
    /**
     * 获取本地缓存
     *
     * @param key
     * @param <T>
     * @return
     *//*
    public static <T> T get(String key) {
        CacheValue value = localCache.get(key);
        if (Objects.nonNull(value)) {
            return JSONObject.parseObject(value.cacheValue, new TypeReference<T>(){});
        }
        return null;
    }
*/
    /**
     * 获取本地缓存,如果需要转换为List,Map类型的具体泛型使用本方法
     * @param key
     * @param typeReference
     * @param <T>
     * @return
     */
    public static <T> T get(String key,TypeReference typeReference) {
        CacheValue value = localCache.get(key);
        if (Objects.nonNull(value)) {
            return (T)JSONObject.parseObject(value.cacheValue, typeReference);
        }
        return null;
    }
 
    /**
     * 删除缓存
     *
     * @param key
     * @param <T>
     * @return
     */
    public static <T> T remove(String key) {
        CacheValue value = localCache.get(key);
        if (Objects.nonNull(value)) {
            deadCache.add(value.getId());
            return (T) value.cacheValue;
        }
        return null;
    }
 
    /**
     * 批量删除缓存
     *
     * @param key
     * @return
     */
    public static int batchRemove(String key) {
        int count = 0;
        Set<Map.Entry<String, CacheValue>> entries = localCache.entrySet();
        Iterator<Map.Entry<String, CacheValue>> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, CacheValue> next = iterator.next();
            if (StringUtils.isMatch(key, next.getKey())) {
                remove(next.getKey());
                count++;
            }
        }
        return count;
    }
 
    /**
     * 保存一个本地缓存
     *
     * @param key
     * @param value
     */
    public static void save(String key, Object value) {
        if (null != localCache.put(key, buildValue(key, value))) {
            LogUtil.debug("覆盖原有缓存{}", key);
        }
    }
 
    /**
     * 设置含过期时间的缓存
     *
     * @param key
     * @param value
     * @param timeOut 毫秒
     */
    public static void save(String key, Object value, long timeOut) {
        if (null != localCache.put(key, buildValue(key, value, timeOut))) {
            LogUtil.debug("覆盖原有缓存{}", key);
        }
 
    }
 
    /**
     * 重置缓存失效时间
     *
     * @param key
     */
    public static void resetExpire(String key) {
        Objects.requireNonNull(key);
        CacheValue value = localCache.get(key);
        if (Objects.nonNull(value)) {
            value.setCreateTime(System.currentTimeMillis());
        }
    }
 
    /**
     * 清理过期对象
     */
    private synchronized void startClearThread() {
        if (CLEAR_THREAD_STATUS == 0) {
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("demo-pool-%d").build();
            ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
            singleThreadPool.execute(() -> {
                CLEAR_THREAD_STATUS = 1;
                while (true) {
                    try {
                        Set<Map.Entry<String, CacheValue>> entries = localCache.entrySet();
                        Iterator<Map.Entry<String, CacheValue>> iterator = entries.iterator();
                        while (iterator.hasNext()) {
                            Map.Entry<String, CacheValue> next = iterator.next();
 
                            if (next.getValue().timeOut == 0) {
                                continue;
                            }
 
                            boolean isTimeOut = (System.currentTimeMillis() - next.getValue().getCreateTime().longValue()) > next.getValue().timeOut;
                            if (isTimeOut) {
                                CacheValue removed = remove(next.getKey());
                                LogUtil.debug("清除过期对象:{}", removed.cacheValue);
                            }
                        }
                        if(CollUtil.isNotEmpty(deadCache)){
                            LogUtil.debug("删除数据库中的缓存:{}",deadCache);
                            sysCacheValueDao.deleteBatchIds(deadCache);
                            deadCache.clear();
                        }
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        LogUtil.error("清理缓存线程异常停止", e);
                        CLEAR_THREAD_STATUS = 0;
                    }
                }
            });
 
 
        }
    }
 
    /**
     * 缓存对象写入磁盘
     */
    private synchronized void startSaveStoreThread() {
 
            ThreadFactory namedThreadFactory = new ThreadFactoryBuilder()
                    .setNameFormat("startSaveStoreThread-pool-%d").build();
            ExecutorService singleThreadPool = new ThreadPoolExecutor(1, 1,
                    0L, TimeUnit.MILLISECONDS,
                    new LinkedBlockingQueue<Runnable>(1), namedThreadFactory, new ThreadPoolExecutor.AbortPolicy());
            singleThreadPool.execute(() -> {
                try {
                    while (true){
                        Collection<CacheValue> values = localCache.values();
                        List<CacheValue> notSavedList = values.stream().filter(v -> !v.saved).collect(Collectors.toList());
                        if(CollUtil.isNotEmpty(notSavedList)){
                            List<String> collect = notSavedList.stream().map(e -> e.getCacheKey()).collect(Collectors.toList());
                            sysCacheValueDao.delete(new LambdaQueryWrapper<SysCacheValue>().in(SysCacheValue::getCacheKey,collect));
                            notSavedList.forEach(e->{
                                e.setSaved(true);
                                SysCacheValue sysCacheValue = buildSysCacheValue(e);
                                sysCacheValueDao.insert(sysCacheValue);
                                e.setId(sysCacheValue.getId());
                                LogUtil.debug("持久化缓存对象:{}",e.getCacheKey());
                            });
                        }
                        Thread.sleep(1000);
                    }
                } catch (Exception e) {
                    LogUtil.error("存储缓存对象线程异常停止", e);
                }
            });
 
 
    }
 
    private SysCacheValue buildSysCacheValue(CacheValue e) {
        SysCacheValue cacheValue=new SysCacheValue();
        BeanUtil.copyProperties(e,cacheValue);
        return  cacheValue;
    }
 
 
    private static CacheValue buildValue(String key, Object value) {
        return buildValue(key, value, 0);
    }
 
 
    private static CacheValue buildValue(String key, Object value, long timeOut) {
        CacheValue instances = new CacheValue();
        instances.createTime = System.currentTimeMillis();
        instances.cacheKey = key;
        instances.cacheValue = JSON.toJSONString(value);
        instances.timeOut = timeOut;
        return instances;
    }
 
 
    /**
     * 缓存对象
     */
    @Data
    static class CacheValue {
 
        private Long id ;
 
        /**
         * 过期时间,0 表示不过期,单位毫秒
         */
        private Long timeOut = 0L;
 
        /**
         * 缓存key
         */
        private String cacheKey;
        /**
         * 缓存值
         */
        private String cacheValue;
 
        /**
         * 缓存创建时间
         */
        private Long createTime;
 
        private boolean saved=false;
 
        private boolean live=true;
    }
 
 
}