问题来源:
因为在项目中需要获取微信的access_token ,access_token是公众号的全局唯一接口调用凭据,公众号调用各接口时都需使用access_token。开发者需要进行妥善保存。access_token的存储至少要保留512个字符空间。access_token的有效期目前为2个小时,需定时刷新,重复获取将导致上次获取的access_token失效。
所以需要一个线程,来定时获取和更新access_token
一 新建 TokenThread 线程
package com.hmzj.callcenterim.thread; import com.hmzj.callcenterim.dto.AccessToken; import com.hmzj.callcenterim.enums.WeixinEnum; import com.hmzj.callcenterim.utils.WeixinUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; /** * 定时获取和更新access_token * * @author Yangqi.Pang * @version V0.0.1 */ @Service @Slf4j @RefreshScope public class TokenThread implements Runnable{ private RedisTemplate<String, String> redisTemplate; @Autowired public TokenThread(RedisTemplate<String, String> redisTemplate) { this.redisTemplate = redisTemplate; } @Override public void run() { while (true) { try { AccessToken accessToken = WeixinUtil.getAccessToken(WeixinEnum.APP_ID.getValue(), WeixinEnum.APP_SECRET.getValue()); if (accessToken != null) { if (accessToken.getToken() != null) { redisTemplate.opsForValue().set("accessToken", accessToken.getToken()); log.info("获取的accessToken为"+accessToken.getToken()); } } if (null != accessToken.getToken()) { // 休眠7000秒 Thread.sleep((accessToken.getExpiresIn() - 3000) * 1000); } else { // 如果access_token为null,60秒后再获取 Thread.sleep(3600 * 1000); } } catch (InterruptedException e) { try { Thread.sleep(60 * 1000); } catch (InterruptedException e1) { log.error("{}", e1); } log.error("{}", e); } } } }
二 配置监听器
package com.hmzj.callcenterim; import com.hmzj.callcenterim.thread.TokenThread; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * spring boot 容器加载后自动监听 * 执行 tokenThread 线程 * * @author Yangqi.pang * @version V0.0.1 */ @Component public class MyThreadRunner implements CommandLineRunner { @Autowired private TokenThread tokenThread; @Override public void run(String... args) { new Thread(tokenThread).start(); } }
原文地址:https://www.cnblogs.com/pangyangqi/p/9473754.html
时间: 2024-11-05 18:50:07