写一个史上最菜b的管理微信token的框架

首先是不想每个项目都用定时器去管理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的几种方式,我感觉我的更适合微服务吧,各有利弊

http://www.cnblogs.com/fengzheng/p/5027630.html 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值