当前位置: 首页> 文旅> 艺术 > Map缓存token

Map缓存token

时间:2025/7/10 2:30:01来源:https://blog.csdn.net/qq_41080067/article/details/140945012 浏览次数:0次

Map缓存Token 记录过期时间

public String getToken() {AccessTokenSingleton atsl = AccessTokenSingleton.getInstance();Map<String, String> map = atsl.getMap();String accessToken = map.get("access_token");String time = map.get("time");Long nowDate = new Date().getTime();if (null != accessToken && null != time && nowDate - Long.parseLong(time) < 7200000) {log.error("look time:" + time + "; [北森] access_token" + accessToken);// 从缓存中读取accessToken数据return accessToken;} else {System.out.println("到期");// 获取tokenString tokenUrl = "https://get/token";Map<String, Object> params = new HashMap<String, Object>();params.put("grant_type", "client_credentials");params.put("app_key", "7B61AE4");params.put("app_secret", "60537D07A1D945D7A70DFF4D2");String sendJson = BizJsonUtils.toJson(params);HttpRequest post = HttpUtil.createPost(tokenUrl);post.body(sendJson);try (HttpResponse execute = post.execute()) {if (!execute.isOk()) {throw new BizException("接口异常:" + execute);}String body = execute.body();JSONObject resJSON = JSONUtil.parseObj(body);Object access_token = resJSON.get("access_token");String errorCode = resJSON.get("error_code")==null?"":resJSON.get("error_code").toString();if (CFCUtils.isEmpty(access_token)||errorCode.equals("500010")) {String msg = resJSON.get("error_description") == null ? "" : String.valueOf(resJSON.get("error_description"));throw new BizException(msg);}Map<String, Object> responseMap = new HashMap<>();responseMap.put("access_token", access_token);accessToken = String.valueOf(responseMap.get("access_token"));map.put("time", String.valueOf(nowDate));map.put("access_token", accessToken);} catch (Exception e) {log.error("接口异常:{}", e.getMessage());throw new BizException(e.getMessage());}return accessToken;}}

单例设计模式AccessTokenSingleton 缓存token

 static class AccessTokenSingleton {// 缓存accessToken 和 过期时间的 mapprivate Map<String, String> map = new HashMap<String, String>();private AccessTokenSingleton() {}private static AccessTokenSingleton single = null;public static AccessTokenSingleton getInstance() {if (null == single) {single = new AccessTokenSingleton();}return single;}public Map<String, String> getMap() {return map;}public void setMap(Map<String, String> map) {this.map = map;}}
关键字:Map缓存token

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: