用hutool做本地缓存的工具类
gradle中引入hutool依赖
1 | implementation group: 'cn.hutool' , name: 'hutool-all' , version: '5.8.4' |
本地缓存工具类
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 | package com.demo.devops.common.cache; import cn.hutool.cache.CacheUtil; import cn.hutool.cache.impl.TimedCache; import cn.hutool.core.date.DateUnit; /** * @createTime 2022年07月30日 14:50:00 */ public class LocalCache { /** * 默认缓存时长 */ private static final long DEFAULT_TIMEOUT = 5 *DateUnit.MINUTE.getMillis(); /** * 默认清理间隔时间 */ private static final long CLEAN_TIMEOUT = 5 * DateUnit.MINUTE.getMillis(); /** * 缓存对象 */ private static final TimedCache TIMED_CACHE = CacheUtil.newTimedCache(DEFAULT_TIMEOUT); static { //启动定时任务 TIMED_CACHE.schedulePrune(CLEAN_TIMEOUT); } public static void set(String key, Object value) { TIMED_CACHE.put(key, value); } public static void set(String key, Object value, long expire) { TIMED_CACHE.put(key, value, expire); } /** * 获取并重新计算过期时间 */ public static Object getWithUpdateLastAccess(String key) { return TIMED_CACHE.get(key); } /** * 获取 * * @param key * @return */ public static Object get(String key) { return TIMED_CACHE.get(key, false ); } public static Set keySet() { return TIMED_CACHE.keySet(); } public static void remove(String key) { TIMED_CACHE.remove(key); } public static void clear() { TIMED_CACHE.clear(); } public static class Constants { public static final String DICT_LIST_PREFIX = "dict:list:" ; public static final String DICT_ONE_PREFIX = "dict:one:" ; public static final String DICT_MAP_PREFIX = "dict:map:" ; public static final String SCRIPT = "script:" ; } } |
关于hutools工具包的常用方法
近期接触的一个项目用到了hutools工具框架,以前没有接触该框架,发现该工具框架真是强大,是真香啊!所以把我项目中用到的工具类的使用情况记录下。
HttpUtil类
1、发送get请求【方式一特点:直接发送get请求】
1 2 3 4 5 6 | url += "LSL" ; String repsStr = HttpUtil.get(String.format(url)); //发送get请求,并获取response JSONObject jsonObject = JSON.parseObject(repsStr); JSONObject data = jsonObject.getJSONObject( "data" ); String userName = data.getString( "userName" ); |
2、发送get请求【方式二特点:添加报文头在发送get请求】
1 2 3 4 5 6 7 8 9 10 | url += "LSL" ; cn.hutool.http.HttpRequest httpq = HttpUtil.createGet(url); //创建get请求 Map headerMap = new HashMap; headerMap.put( "author" , "mjx" ); httpq.addHeaders(headerMap); //添加header String reps = httpq.execute().body(); //发送get请求,获取response JSONObject jsonObject = JSON.parseObject(reps ); JSONObject data = jsonObject.getJSONObject( "data" ); String userName = data.getString( "userName" ); |
以上为个人经验,希望能给大家一个参考,也希望大家多多支持IT俱乐部。