You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
92 lines
2.7 KiB
92 lines
2.7 KiB
package com.ynxbd.wx.wxfactory;
|
|
|
|
import com.ynxbd.common.bean.User;
|
|
import com.ynxbd.common.config.EhCacheConfig;
|
|
import com.ynxbd.wx.wxfactory.bean.AccessToken;
|
|
import lombok.extern.slf4j.Slf4j;
|
|
import org.ehcache.Cache;
|
|
|
|
@Slf4j
|
|
public class WxCacheHelper {
|
|
static {
|
|
createUserCache();
|
|
createAccessTokenCache();
|
|
}
|
|
|
|
// 缓存
|
|
private static Cache<String, User> USER_CACHE;
|
|
|
|
private static Cache<String, AccessToken> ACCESS_TOKEN_CACHE;
|
|
|
|
private synchronized static void createUserCache() {
|
|
if (USER_CACHE == null) {
|
|
USER_CACHE = EhCacheConfig.createCacheTTL(String.class, User.class, "wx_auth_cache", (5400L)); // 一个半小时
|
|
}
|
|
}
|
|
|
|
|
|
public static Cache<String, User> getUserCache() {
|
|
if (USER_CACHE == null) {
|
|
createUserCache();
|
|
}
|
|
return USER_CACHE;
|
|
}
|
|
|
|
public static void removeUser(String openid) {
|
|
Cache<String, User> cache = getUserCache();
|
|
if (cache != null) {
|
|
cache.remove(openid);
|
|
}
|
|
}
|
|
|
|
public static User getCacheUser(String openid) {
|
|
if (USER_CACHE == null) {
|
|
createUserCache();
|
|
}
|
|
return USER_CACHE.get(openid);
|
|
}
|
|
|
|
public static final String ACCESS_TOKEN_CACHE_NAME = "access_token";
|
|
|
|
|
|
private synchronized static void createAccessTokenCache() {
|
|
if (ACCESS_TOKEN_CACHE == null) {
|
|
ACCESS_TOKEN_CACHE = EhCacheConfig.createCacheTTL(String.class, AccessToken.class, "wx_access_token_cache", (7100L)); // 一个半小时
|
|
}
|
|
}
|
|
|
|
public static AccessToken getWxAccessToken() {
|
|
if (ACCESS_TOKEN_CACHE == null) {
|
|
createAccessTokenCache();
|
|
}
|
|
AccessToken token = new AccessToken();
|
|
|
|
AccessToken cacheToken = ACCESS_TOKEN_CACHE.get(ACCESS_TOKEN_CACHE_NAME);
|
|
log.warn("cacheToken={}", cacheToken);
|
|
if (cacheToken != null) {
|
|
token.setCreateTime(cacheToken.getCreateTime());
|
|
token.setAccessToken(cacheToken.getAccessToken());
|
|
return token;
|
|
}
|
|
AccessToken respToken = WxMedicalHelper.getAccessToken(ACCESS_TOKEN_CACHE);
|
|
if (respToken == null) {
|
|
return null;
|
|
}
|
|
|
|
log.warn("respToken={}", respToken);
|
|
token.setCreateTime(respToken.getCreateTime());
|
|
token.setAccessToken(respToken.getAccessToken());
|
|
ACCESS_TOKEN_CACHE.put(ACCESS_TOKEN_CACHE_NAME, respToken);
|
|
return token;
|
|
}
|
|
|
|
|
|
public static String getAccessToken() {
|
|
AccessToken accessToken = getWxAccessToken();
|
|
if (accessToken != null) {
|
|
return accessToken.getAccessToken();
|
|
}
|
|
return null;
|
|
}
|
|
|
|
}
|
|
|