用hutool做本地缓存的工具类
gradle中引入hutool依赖
implementation group: 'cn.hutool', name: 'hutool-all', version: '5.8.4'
本地缓存工具类
package com.demo.devops.common.cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit;
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<String, Object> 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);
}
public static Object get(String key) {
return TIMED_CACHE.get(key, false);
}
public static Set<String> 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请求】
String url = "http://www.baidu.com/getUserInfo?user_id=";
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请求】
String url = "http://www.baidu.com/getUserInfo?user_id=";
url +="LSL";
cn.hutool.http.HttpRequest httpq = HttpUtil.createGet(url);//创建get请求
Map<String,String> 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");
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。