Java获取公众号的access_token,将accessToken缓存到全局,并设置指定时间内失效重新获取

Java中,获取公众号的access_token,将accessToken缓存到全局,并设置指定时间内失效,重新获取时,可以获取到新的access_token

封装方法如下:

public String appid="";
public String secret="";
private static String AccessToken="";
private static Date TokenTime = null;

public String getAccessToken() throws Exception{
	Date temDate = Calendar.getInstance().getTime();
	 if ((TokenTime == null) || temDate.after(TokenTime)){
		  Map map= WeixinUtils.getAccessToken(appid,secret);
		  Date localDate = Calendar.getInstance().getTime();
		  Integer localInteger = Integer.valueOf(300);
		  TokenTime=DateUtils.addSeconds(localDate, localInteger.intValue());
		  AccessToken=map.get("access_token").toString();
	 }
	return AccessToken;
}
正在加载评论...