博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java本地缓存CRUD测试,LocalCache出自简书
阅读量:6966 次
发布时间:2019-06-27

本文共 6873 字,大约阅读时间需要 22 分钟。

hot3.png

LocalCache:

/** * Created by lis on 17/5/2. */@Componentpublic class LocalCache implements Serializable{    private static final long serialVersionUID = 1L;    /**     * 默认有效时长,单位:秒     */    private static final int DEFUALT_TIMEOUT = 3600;    private static final long SECOND_TIME = 1000;    private static final Map
map; private static final Timer timer; /** * 初始化 */ static { timer = new Timer(); map = new ConcurrentHashMap<>(); } /** * 私有构造函数,工具类不允许实例化 */ private LocalCache() { } /** * 清除缓存任务类 */ static class CleanWorkerTask extends TimerTask { private String key; public CleanWorkerTask(String key) { this.key = key; } public void run() { LocalCache.remove(key); } } /** * 增加缓存 * * @param key * @param value */ public static void put(String key, Object value) { map.put(key, value); timer.schedule(new CleanWorkerTask(key), DEFUALT_TIMEOUT); } /** * 增加缓存 * * @param key * @param value * @param timeout 有效时长 */ public static void put(String key, Object value, int timeout) { map.put(key, value); timer.schedule(new CleanWorkerTask(key), timeout * SECOND_TIME); } /** * 增加缓存 * * @param key * @param value * @param expireTime 过期时间 */ public static void put(String key, Object value, Date expireTime) { map.put(key, value); timer.schedule(new CleanWorkerTask(key), expireTime); } /** * 批量增加缓存 * * @param m */ public static void putAll(Map
m) { map.putAll(m); for (String key : m.keySet()) { timer.schedule(new CleanWorkerTask(key), DEFUALT_TIMEOUT); } } /** * 批量增加缓存 * * @param m */ public static void putAll(Map
m, int timeout) { map.putAll(m); for (String key : m.keySet()) { timer.schedule(new CleanWorkerTask(key), timeout * SECOND_TIME); } } /** * 批量增加缓存 * * @param m */ public static void putAll(Map
m, Date expireTime) { map.putAll(m); for (String key : m.keySet()) { timer.schedule(new CleanWorkerTask(key), expireTime); } } /** * 获取缓存 * * @param key * @return */ public static Object get(String key) { return map.get(key); } /** * 查询缓存是否包含key * * @param key * @return */ public static boolean containsKey(String key) { return map.containsKey(key); } /** * 删除缓存 * * @param key */ public static void remove(String key) { map.remove(key); } /** * 删除缓存 * * @param o */ public static void remove(Object o) { map.remove(o); } /** * 返回缓存大小 * * @return */ public static int size() { return map.size(); } /** * 获取所有缓存数据 * * @return Map */ public static Map
getAllCacheData(){ return map; } /** * 清除所有缓存 * * @return */ public static void clear() { if (size() > 0) { map.clear(); } timer.cancel(); }}

 

本地缓存CRUD测试

CacheController:

import cn.jiguang.utils.DateUtils;import cn.jiguang.utils.LocalCache;import com.alibaba.fastjson.JSON;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.util.CollectionUtils;import org.springframework.util.StringUtils;import org.springframework.web.bind.annotation.*;import java.util.Date;import java.util.Map;/** * @desc: 测试缓存 * @author: zengxc * @date: 2018/3/22 */@RequestMapping(value = "/cache")@RestControllerpublic class CacheController {        private static final Logger LOG = LoggerFactory.getLogger(CacheController.class);    @Autowired    private LocalCache localCache;    @RequestMapping(method = RequestMethod.POST)    public ResponseEntity
insertCache(@RequestBody Map
map){ try { if (!CollectionUtils.isEmpty(map)){ map.forEach((k,v)-> { localCache.put(k, v, DateUtils.getNextDay(new Date())); }); } LOG.info("request param map:{} cache:{}", JSON.toJSONString(map), JSON.toJSONString(localCache.getAllCacheData())); return ResponseEntity.status(HttpStatus.CREATED).body(null); } catch (Exception e) { LOG.error("exception info:{}", e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } @RequestMapping(method = RequestMethod.GET) public ResponseEntity
getAllCacheData(@RequestParam(value = "key", required = false) String key){ try { if (!StringUtils.isEmpty(key)){ LOG.info("get cache value:{}", JSON.toJSONString(localCache.get(key))); return ResponseEntity.status(HttpStatus.OK).body(localCache.get(key)); }else { LOG.info("get cache value:{}", JSON.toJSONString(localCache.getAllCacheData())); return ResponseEntity.ok(localCache.getAllCacheData()); } } catch (Exception e) { LOG.error("exception info:{}", e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } @RequestMapping(method = RequestMethod.PUT) public ResponseEntity
updateCache(String key, @RequestBody Object value){ try { localCache.put(key, value); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (Exception e) { LOG.error("exception info:{}", e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); } @RequestMapping(method = RequestMethod.DELETE) public ResponseEntity
deleteCache(@RequestParam("key") String key){ try { localCache.remove(key); return ResponseEntity.status(HttpStatus.NO_CONTENT).build(); } catch (Exception e) { LOG.error("exception info:{}", e.getMessage()); } return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build(); }}

DateUtils工具类:

/** * @desc: * @author: zengxc * @date: 2018/3/23 */public class DateUtils {    /**     * 获取当前系统时间的下一天     * @param date     * @return     */    public static Date getNextDay(Date date) {        Calendar calendar = Calendar.getInstance();        calendar.setTime(date);        calendar.add(Calendar.DAY_OF_MONTH, 1);        date = calendar.getTime();        return date;    }}

 

转载于:https://my.oschina.net/u/3744350/blog/1649999

你可能感兴趣的文章
使用Volley上传头像图片
查看>>
用tbox实现内存检测
查看>>
用真机做远程调试的两种方式
查看>>
抽象类和方法
查看>>
细节:js 原型对象与for-in 方法枚举的问题
查看>>
性能优化总结
查看>>
优麒麟 19.04 即将发布,华为、阿里云、重大、360四大境像站鼎力支持!
查看>>
分布式文件系统 go-fastdfs v1.2.7 发布,增加 Nginx 配置模版
查看>>
JavaScript的setTimeout和setInterval的深入理解
查看>>
工具 - etl file references
查看>>
图像编辑器 GIMP 2.10.10 发布,性能改进
查看>>
repmgr 4.3 发布,PostgreSQL 复制与故障转移管理工具
查看>>
十年再出发:阿里云智能战略加速的“四级火箭” ...
查看>>
阿里云RPA(机器人流程自动化)干货系列之六:客户端安装及激活 ...
查看>>
Alibaba Cluster Data 开放下载:270 GB 数据揭秘你不知道的阿里巴巴数据中心 ...
查看>>
Decision Tree
查看>>
四万高手过招,这份阿里全球数学竞赛试题你真的不要看吗 ...
查看>>
进行移动端Unity开发,针对引擎PowerVR性能建议
查看>>
linux gcc Makefile
查看>>
SpringBoot-Security-用户权限分配-配置验证规则
查看>>