首先是不想每个项目都用定时器去管理token,然后就想自己写个管理token的工具,所以用框架的方式去写了一个工具,或者说是一个工具类吧,随便怎么叫,反正用着舒服就行
@Configuration
public class WxCpConfiguration {
@Bean
@ConditionalOnMissingBean
public WxCpConfigStorage configStorage() {
WxCpInMemoryConfigStorage configStorage = new WxCpInMemoryConfigStorage();
configStorage.setCorpId("ssss");
configStorage.setSecret("ssss");
return configStorage;
}
@Bean
@ConditionalOnMissingBean
public WxCpService WxCpService(WxCpConfigStorage wxCpConfigStorage) {
WxCpService service = new WxCpServiceImpl();
service.setWxCpConfigStorage(wxCpConfigStorage);
return service;
}
}
springboot的配置,由于不需要其他的功能,所以只要这两个属性就足够了,
public abstract class WxCpServiceAbstractImpl implements WxCpService {
protected UserService userService;
protected WxCpConfigStorage configStorage;
//刷新token全局锁
protected final Object globalAccessTokenRefreshLock = new Object();
public String getAccessToken() {
long nowTime = System.currentTimeMillis();
long expiresTime = configStorage.getExpiresTime();
if(configStorage.getExpiresTime() < nowTime){
getAccessToken(false);
}
return configStorage.getAccessToken();
}
public String getAccessToken(boolean forceRefresh) {
synchronized (this.globalAccessTokenRefreshLock) {
String token = HttpClient.doGet("https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=" + configStorage.getCorpId() + "&corpsecret=" + configStorage.getSecret());
AccessToekn accessToekn = JSON.parseObject(token, AccessToekn.class);
System.out.println(accessToekn.toString());
configStorage.setExpiresTime(System.currentTimeMillis()+6500*1000);
configStorage.setAccessToken(accessToekn.getAccessToken());
configStorage.setCount(configStorage.getCount()+1);
return configStorage.getAccessToken();
}
}
public void setWxCpConfigStorage(WxCpConfigStorage wxConfigProvider) {
this.configStorage = wxConfigProvider;
}
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
上面是最主要的逻辑,全局锁更新token 判断过期时间,放内存里面,
然后。。。然后。。。然后。就没有了,哈哈哈。其实打算写了剩下的,不过我这边也用不到,网上有更好的工具,所以我也懒得写了
git源码:https://github.com/wanglei1234567/weChatCP
好了,最彩笔开源结束,感谢看我瞎几把写
下面是大佬写的管理token的几种方式,我感觉我的更适合微服务吧,各有利弊