java——本地缓存(hutool)/分布式缓存(Redis)

时间:2025-03-12 09:42:03
package test01; import cn.hutool.cache.CacheUtil; import cn.hutool.cache.impl.TimedCache; import cn.hutool.core.util.StrUtil; import cn.hutool.http.HttpUtil; import cn.hutool.json.JSONUtil; import com.shylFm.web.util.Redis.RedisCache; import org.springframework.beans.factory.annotation.Autowired; import java.util.concurrent.TimeUnit; public class Main { private TimedCache<Object, Object> cache = CacheUtil.newTimedCache(7200 * 1000); /** * 本地缓存 * * @return String */ public String WXgetAccessToken() { String accessToken = String.valueOf(cache.get("accessToken")); if (StrUtil.isEmptyOrUndefined(accessToken)) { // 请求获取accessToken String appid = ""; String secret = ""; String data_str = HttpUtil.get("/cgi-bin/token?grant_type=client_credential&apptoken operator">+ appid + "&secret=" + secret); accessToken = JSONUtil.parseObj(data_str).getStr("access_token"); cache.put("accessToken", accessToken); } return accessToken; } @Autowired public RedisCache redisCache; /** * redis分布式缓存 * * @return String */ public String redisGetAccessToken() { String accessToken = String.valueOf(redisCache.getCacheObject("accessToken")); if (StrUtil.isEmptyOrUndefined(accessToken)) { // 请求获取accessToken String appid = ""; String secret = ""; String data_str = HttpUtil.get("/cgi-bin/token?grant_type=client_credential&apptoken operator">+ appid + "&secret=" + secret); accessToken = JSONUtil.parseObj(data_str).getStr("access_token"); redisCache.setCacheObject("accessToken", accessToken, 7200 * 1000, TimeUnit.MILLISECONDS); } return accessToken; } }