【微信开发】getAccessToken 和 getJsapi_ticket缓存支持

时间:2022-04-27
本文章向大家介绍【微信开发】getAccessToken 和 getJsapi_ticket缓存支持,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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

示例: 

/**
	 * 获取access_token
	 * 
	 * @updateDate 2015年8月3日23:22:39 增加对缓存的处理
	 * @return
	 * @throws Exception
	 */
	public static String getAccessToken(String appId, String appSecret)
			throws Exception {
		String accessToken = (String) CacheUtils.get("wxCache", "accessToken");
		if (StringUtils.isBlank(accessToken)
				|| StringUtils.isEmpty(accessToken)) {
			String jsonStr = HttpKit.get(ACCESSTOKEN_URL.concat("&appid=")
					+ appId + "&secret=" + appSecret);
			Map<String, Object> map = JSONObject.parseObject(jsonStr);
			accessToken = map.get("access_token").toString();
			CacheUtils.put("wxCache", "accessToken", accessToken);
		}
		return accessToken;
	}
/**
	 * 获得jsapi_ticket(有效期7200秒)
	 * 
	 * @updateDate 2015年8月4日00:00:46 z 增加对缓存的
	 * @param accessToken
	 * @return
	 * @throws InterruptedException
	 * @throws ExecutionException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 * @throws IOException
	 * @throws NoSuchProviderException
	 */
	public static JSONObject getTicket(String accessToken)
			throws InterruptedException, ExecutionException,
			NoSuchAlgorithmException, KeyManagementException, IOException,
			NoSuchProviderException {
		String jsonStr = (String) CacheUtils.get("wxCache", "jsapi_ticket");
		if (StringUtils.isBlank(jsonStr) || StringUtils.isEmpty(jsonStr)) {
			jsonStr = HttpKit.get(JSAPI_TICKET.concat(accessToken));
			CacheUtils.put("wxCache", "jsapi_ticket", jsonStr);
		}
		return JSONObject.parseObject(jsonStr);
	}

 ehcache.xml

<cache name="wxCache" 
maxElementsInMemory="100" 
eternal="false" 
timeToLiveSeconds="6000" 
overflowToDisk="true"/>