Spring Boot中微信全局token的缓存实现
为什么要缓存token?
这里的token指的是微信JSAPI中基础支持的ACCESS_TOKEN,并非网页授权ACCESS_TOKEN。网页授权Token每天的调用次数没有限制,不需要缓存。
| 接口 | 每日限额 |
|---|---|
| 获取access_token | 2000 |
| 自定义菜单创建 | 1000 |
| 自定义菜单查询 | 10000 |
| 获取用户基本信息 | 5000000 |
| 获取网页授权access_token | 无 |
| 刷新网页授权access_token | 无 |
| 网页授权获取用户信息 | 无 |
从上面的表格我们可以看到,微信基础支持的token每天调用频次为2000次。而token的有效时间为7200s,当实现了token的全局缓存后,理论每天只需要调用12次。相反,2000次即使仅供微信分享回调,在有一定用户基础的项目中完全满足不了。
缓存方案
- 项目启动时开启一个定时器,每7180s执行一次Http请求,从微信获取最新的access_token并将redis中旧的access_token替换掉。
- 代码中有需要使用access_token时,直接从缓存中读取。
Spring Boot使用定时器
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import javax.annotation.Resource;
import org.apache.log4j.Logger;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import com.bjb.dao.impl.RedisTokenHelper;
import net.sf.json.JSONObject;
/**
* 全局定时器
* @author qiqj
*
*/
@Component
public class Scheduler {
private final Logger logger = Logger.getRootLogger();
@Resource
private RedisTokenHelper redisTokenHelper;
/**
* 定时获取access_token
* @throws SQLException
*/
@Scheduled(fixedDelay=7180000)
public void getAccessToken() throws SQLException{
logger.info("==============开始获取access_token===============");
String access_token = null;
String grant_type = "client_credential";
String AppId= WxPropertiseUtil.getProperty("appid");
String secret= WxPropertiseUtil.getProperty("secret");
String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type="+grant_type+"&appid="+AppId+"&secret="+secret;
try {
URL urlGet = new URL(url);
HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();
http.setRequestMethod("GET"); // 必须是get方式请求
http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
http.setDoOutput(true);
http.setDoInput(true);
http.connect();
InputStream is = http.getInputStream();
int size = is.available();
byte[] jsonBytes = new byte[size];
is.read(jsonBytes);
String message = new String(jsonBytes, "UTF-8");
JSONObject demoJson = JSONObject.fromObject(message);
//System.out.println("JSON字符串:"+demoJson);
access_token = demoJson.getString("access_token");
is.close();
logger.info("==============结束获取access_token===============");
} catch (Exception e) {
e.printStackTrace();
}
logger.info("==============开始写入access_token===============");
redisTokenHelper.saveObject("global_token", access_token);
logger.info("==============写入access_token成功===============");
}
}
读取配置文件工具类
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.Logger;
/**
* 读取微信配置文件 wxconfig.properties工具类
* @author qiqj
*
*/
public class WxPropertiseUtil {
private static Properties properties = new Properties();
protected static final Logger logger = Logger.getRootLogger();
static{
InputStream in = WxPropertiseUtil.class.getClassLoader().getResourceAsStream("wxconfig.properties");
try {
properties.load(in);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage());
}
}
public static String getProperty(String key){
return properties.getProperty(key);
}
public static void UpdateProperty(String key,String value){
properties.setProperty(key, value);
}
}
微信配置文件
appid=xxxx
secret=xxxxxx
Redis操作工具类
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;
/**
* 封装Redis存取Token对的工具类
* @author qiqj
*
*/
@Repository
public class RedisTokenHelper {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate<Object, Object> redisTemplate;
@Resource(name="stringRedisTemplate")
ValueOperations<String, String> ops;
@Resource(name="redisTemplate")
ValueOperations<Object, Object> objOps;
/**
* 键值对存储 字符串 :有效时间3分钟
* @param tokenType Token的key
* @param Token Token的值
*/
public void save(String tokenType,String Token){
ops.set(tokenType, Token, 180, TimeUnit.SECONDS);
}
/**
* 根据key从redis获取value
* @param tokenType
* @return String
*/
public String getToken(String tokenType){
return ops.get(tokenType);
}
/**
* redis 存储一个对象
* @param key
* @param obj
* @param timeout 过期时间 单位:s
*/
public void saveObject(String key,Object obj,long timeout){
objOps.set(key, obj,timeout,TimeUnit.SECONDS);
}
/**
* redis 存储一个对象 ,不过期
* @param key
* @param obj
*/
public void saveObject(String key,Object obj){
objOps.set(key, obj);
}
/**
* 从redis取出一个对象
* @param key
* @param obj
*/
public Object getObject(String key){
return objOps.get(key);
}
/**
* 根据Key删除Object
* @param key
*/
public void removeObject(String key){
redisTemplate.delete(key);
}
}
简单测试
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.transaction.annotation.Transactional;
import com.bjb.Application;
import com.bjb.dao.impl.RedisTokenHelper;
/**
* Junit单元测试类
* @author qiqj
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes=Application.class)
@WebAppConfiguration
@Transactional
public class JUnitTest {
private final Logger logger = Logger.getRootLogger();
@Resource
private RedisTokenHelper redisTokenHelper;
@Test
public void test(){
String access_token = (String) redisTokenHelper.getObject("global_token");
System.out.println("access_token:"+access_token);
}
}
Spring Boot中微信全局token的缓存实现的更多相关文章
- Spring Boot 中集成 Redis 作为数据缓存
只添加注解:@Cacheable,不配置key时,redis 中默认存的 key 是:users::SimpleKey [](1.redis-cli 中,通过命令:keys * 查看:2.key:缓存 ...
- Spring Boot2 系列教程(十三)Spring Boot 中的全局异常处理
在 Spring Boot 项目中 ,异常统一处理,可以使用 Spring 中 @ControllerAdvice 来统一处理,也可以自己来定义异常处理方案.Spring Boot 中,对异常的处理有 ...
- 在Spring Boot中添加全局异常捕捉提示
在一个项目中的异常我们我们都会统一进行处理的,那么如何进行统一进行处理呢? 全局异常捕捉: 新建一个类GlobalDefaultExceptionHandler, 在class注解上@Controll ...
- Spring Boot中使用缓存
Spring Boot中使用缓存 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决这一问题非常好的手段之一. 原始的使 ...
- Spring Boot中的缓存支持(一)注解配置与EhCache使用
Spring Boot中的缓存支持(一)注解配置与EhCache使用 随着时间的积累,应用的使用用户不断增加,数据规模也越来越大,往往数据库查询操作会成为影响用户使用体验的瓶颈,此时使用缓存往往是解决 ...
- spring boot中的声明式事务管理及编程式事务管理
这几天在做一个功能,具体的情况是这样的: 项目中原有的几个功能模块中有数据上报的功能,现在需要在这几个功能模块的上报之后生成一条消息记录,然后入库,在写个接口供前台来拉取消息记录. 看到这个需求,首先 ...
- Spring Boot中的微信支付(小程序)
前言 微信支付是企业级项目中经常使用到的功能,作为后端开发人员,完整地掌握该技术是十分有必要的. logo 一.申请流程和步骤 图1-1 注册微信支付账号 获取微信小程序APPID 获取微信商家的商户 ...
- 在Spring Boot中使用数据缓存
春节就要到了,在回家之前要赶快把今年欠下的技术债还清.so,今天继续.Spring Boot前面已经预热了n篇博客了,今天我们来继续看如何在Spring Boot中解决数据缓存问题.本篇博客是以初识在 ...
- Spring Boot中使用EhCache实现缓存支持
SpringBoot提供数据缓存功能的支持,提供了一系列的自动化配置,使我们可以非常方便的使用缓存.,相信非常多人已经用过cache了.因为数据库的IO瓶颈.一般情况下我们都会引入非常多的缓存策略, ...
随机推荐
- Java Hello World 错误 找不到或无法加载主类
Java 有几年没用了 生疏了好多 最近又捡起来 结果第一个Hello World 就在黑窗口内报错! 遇到几个小问题. 1. 安装JDK后 在 CMD 中 执行 java -version 正常 因 ...
- C++ 引用、指针
一.引用 1.引用的作用:给变量起一个别名,是c++对c的扩充.原名和别名有相同的地址,根本上就是同一个东西,只是名字不一样.c++的引用机制主要是为了用作函数参数,增强函数传递数据的能力,比如swa ...
- 使用Caliburn.Micro系列1:新建项目并引入CM
一.WPF的几个MVVM模式实现 MVVMLight:小众的平民框架,实现简单粗暴. pass:最近更新在15年 官网: http://www.mvvmlight.net/ 最近一篇内容全面的好文: ...
- 获取windows版本号
原文:https://blog.csdn.net/justFWD/article/details/44856277 内容整理如下,点击跳至指定内容: manifest文件加上compatibility ...
- Poi 写入图片进入excel
public static void cacheWritePicture(BufferedImage bufferImg, Sheet sheet, Workbook wb, int width, i ...
- phphstrom改变项目中文件排列方式
1.View>Tool Win dows>Project 效果图: 2.File->settings (Ctrl+Alt+S)-> Editor->General-> ...
- js正则表达式,只允许输入纯数字或‘/’
//输入框,限数字和/----需要多个数量询价,请以/分隔 function onlyonce(obj) {//先把非数字的都替换掉,除了数字和.obj.value = obj.value.repla ...
- [Python3网络爬虫开发实战] 3.1.1-发送请求
使用urllib的request模块,我们可以方便地实现请求的发送并得到响应,本节就来看下它的具体用法. 1. urlopen() urllib.request模块提供了最基本的构造HTTP请求的方法 ...
- 详细了解为什么支持Postman Chrome应用程序已被弃用?
本地postman chrome插件确实也无法正常使用,只有Postman官方自己的软件应用程序可以使用.笔者多少追溯终于知道原因,并紧急上线了不同操作系统版本的Postman应用程序. 为什么近期P ...
- 集训第四周(高效算法设计)E题 (区间覆盖问题)
UVA10382 :http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=21419 只能说这道题和D题是一模一样的,不过要进行转化, ...