Guava缓存demo

    /**
     * 从缓存中获取AccessToken
     * @param type 冗余参数(没有填"")
     * @return
     */
    private static String getAccessToken(String type) {
        try {
            return accessTokenCache.get(type);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Guava缓存 将AccessToken缓存29天
     */
    private static LoadingCache<String,String> accessTokenCache = CacheBuilder.newBuilder()
            .expireAfterWrite(CATCH_TIME, TimeUnit.DAYS)
            .build(new CacheLoader<String, String>() {
                @Override
                public String load(String s) throws Exception {
                    String result = "";
                    //调用sendGetRequest方法发送url,并获取百度返回的结果json,处理结果
                    String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=APIKEY&client_secret=SECRETKEY";
                    String requsetURL = url.replaceAll("APIKEY",API_KEY).replaceAll("SECRETKEY",SECRET_KEY);
                    String response = sendPost(requsetURL,"");//发送请求
                    //JSON -> Map 使用fastjson工具类
                    Map<String,Object> map = JSON.parseObject(response, HashMap.class);
                    if(map != null && !map.isEmpty()){
                        result = map.get("access_token").toString();
                    }
                    return result;
                }
            });

  

猜你喜欢

转载自www.cnblogs.com/speily/p/9055732.html
今日推荐