Map缓存token

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("到期");
            // 获取token
            String 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 和 过期时间的 map
        private 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;
        }
    }
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用以下代码来获取一个 token: ```java import java.util.Date; import java.util.HashMap; import java.util.Map; public class TokenManager { private static Map<String, Token> tokenCache = new HashMap<>(); public static String getToken(String clientId, String clientSecret) { String key = clientId + ":" + clientSecret; Token token = tokenCache.get(key); if (token != null && token.getExpiration().after(new Date())) { return token.getValue(); } else { // Perform token retrieval logic here // ... // Assuming the token retrieval logic returns a new token value and its expiration time String newTokenValue = "your_new_token_value"; Date expirationDate = new Date(System.currentTimeMillis() + 3600000); // 1 hour expiration Token newToken = new Token(newTokenValue, expirationDate); tokenCache.put(key, newToken); return newTokenValue; } } private static class Token { private String value; private Date expiration; public Token(String value, Date expiration) { this.value = value; this.expiration = expiration; } public String getValue() { return value; } public Date getExpiration() { return expiration; } } } ``` 这个例子中,`getToken` 方法接收一个 `clientId` 和 `clientSecret` 参数,用来生成一个唯一的 key。它会检查缓存中是否有有效的 token,如果有则返回缓存中的 token 值。如果没有或者缓存中的 token过期,则执行获取新 token 的逻辑,并将新的 token 保存到缓存中。 关于刷新 token缓存时间,上述代码中默认设置为 1 小时(3600000 毫秒)。你可以根据你的实际需求修改这个值。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值