其他分享
首页 > 其他分享> > GUNS getAccessToken 和 getJsapi_ticket缓存支持

GUNS getAccessToken 和 getJsapi_ticket缓存支持

作者:互联网

AccessToken JsapiTicket 获取这个两个参数的接口每天都有上线,所以我们应该使用缓存把它们保存起来,减少对这两个接口的调用

示例:

public static String getAccessToken(String appId, String secret, String accessTokenUrl) {
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(MessageFormat.format(accessTokenUrl,appId,secret));

        try {
            String accessToken = (String) CacheUtil.get("wxCache", "accessToken");
            
            if (StringUtils.isBlank(accessToken) || StringUtils.isEmpty(accessToken)) {
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println(result);

                Map<String, Object> accessTokenMap = JSON.parseObject(result);
                accessToken = (String)accessTokenMap.get("access_token");

                CacheUtil.put("wxCache", "accessToken", accessToken);
            }
            return accessToken;
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return  null;
    }
public static String getTicket(String accessToken,String ticketUrl) {
        HttpClient client = HttpClients.createDefault();
        HttpGet get = new HttpGet(MessageFormat.format(ticketUrl,accessToken));

        try {
            String ticket = (String) CacheUtil.get("wxCache", "jsapi_ticket");
            
            if (StringUtils.isBlank(ticket) || StringUtils.isEmpty(ticket)) {
                HttpResponse response = client.execute(get);
                HttpEntity entity = response.getEntity();
                String result = EntityUtils.toString(entity, "UTF-8");
                System.out.println(result);

                Map<String, Object> jsApiTicketMap = JSON.parseObject(result);
                ticket = (String)jsApiTicketMap.get("ticket");

                CacheUtil.put("wxCache", "jsapi_ticket", ticket);
            }

            return ticket;
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return null;
    }

ehcache.xml

<!-- 微信access_token&ticket全局变量:定时更新-->
    <cache name="wxCache"
           maxElementsInMemory="100"
           eternal="false"
           timeToLiveSeconds="6000"
           overflowToDisk="true"/>
maxElementsInMemory="10000" 	//Cache中最多允许保存的数据对象的数量
external="false" 				//缓存中对象是否为永久的,如果是,超时设置将被忽略,对象从不过期 	
timeToLiveSeconds="3600"  		//缓存的存活时间,从开始创建的时间算起
timeToIdleSeconds="3600"  		//多长时间不访问该缓存,那么ehcache 就会清除该缓存 

标签:getJsapi,String,accessToken,get,缓存,result,ticket,GUNS
来源: https://blog.csdn.net/weixin_42590334/article/details/97279157