token获取调整

master
wangsq 3 years ago
parent a019d38c45
commit 40ab0a4fb3
  1. 18
      src/main/java/com/ynxbd/push/controller/ApiController.java
  2. 10
      src/main/java/com/ynxbd/push/entity/xbd/wx/AccessToken.java
  3. 16
      src/main/java/com/ynxbd/push/entity/xbd/wx/RespAccessToken.java
  4. 43
      src/main/java/com/ynxbd/push/helper/DateHelper.java
  5. 30
      src/main/java/com/ynxbd/push/helper/RequestHelper.java
  6. 73
      src/main/java/com/ynxbd/push/httpRequest/xbd/wx/Test.java
  7. 122
      src/main/java/com/ynxbd/push/httpRequest/xbd/wx/WxCacheRequest.java

@ -0,0 +1,18 @@
package com.ynxbd.push.controller;
import com.ynxbd.push.httpRequest.xbd.wx.WxCacheRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("api")
public class ApiController {
@PostMapping("reToken")
public String reToken() {
WxCacheRequest.clearWxAccessToken();
return "success";
}
}

@ -1,10 +0,0 @@
package com.ynxbd.push.entity.xbd.wx;
import lombok.Data;
@Data
public class AccessToken {
private Integer code;
private String data;
private String message;
}

@ -0,0 +1,16 @@
package com.ynxbd.push.entity.xbd.wx;
import lombok.Data;
import java.io.Serializable;
@Data
public class RespAccessToken implements Serializable {
private static final long serialVersionUID = 36888886677781604L;
// 授权token
private String accessToken;
// 有效时间(s)
private Integer expiresIn;
// 创建时间
private String createTime;
}

@ -0,0 +1,43 @@
package com.ynxbd.push.helper;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateHelper {
public static final String yyyy_MM_dd_HH_mm_ss = "yyyy-MM-dd HH:mm:ss";
/**
* [日期字符串]转日期
*
* @param dateStr 日期字符串
* @param format 日期格式
* @return 日期/时间
*/
public static Date strToDate(String dateStr, String format) {
try {
if (dateStr == null || format == null) {
return null;
}
return new SimpleDateFormat(format).parse(dateStr);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 时间点距离当前时间多少秒
*
* @param dateStr 时间点字符串
* @return 日期/时间
*/
public static long differCurSecond(String dateStr) {
Date date = strToDate(dateStr, yyyy_MM_dd_HH_mm_ss);
if (date == null) {
return 0L;
}
return new Date().getTime() - date.getTime();
}
}

@ -8,6 +8,7 @@
package com.ynxbd.push.helper;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
@ -74,13 +75,36 @@ public class RequestHelper extends SimpleClientHttpRequestFactory {
* @return ResultVO
*/
public static <T> T get(String url, Map<String, String> params, Class<T> clazz) {
return JSON.parseObject(get(url, params), clazz);
}
/**
* 向目的URL发送get请求
*
* @param url 请求地址
* @param params 请求参数
* @return ResultVO
*/
public static JSONObject getJsonObj(String url, Map<String, String> params) {
return JSON.parseObject(get(url, params));
}
/**
* 向目的URL发送get请求
*
* @param url 请求地址
* @param params 请求参数
* @return ResultVO
*/
public static String get(String url, Map<String, String> params) {
RestTemplate client = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
HttpEntity<Map<String,String>> request = new HttpEntity<>(params,headers);
HttpEntity<Map<String, String>> request = new HttpEntity<>(params, headers);
ResponseEntity<String> responseEntity = client.getForEntity(url, String.class, request);
String data = responseEntity.getBody();
return JSON.parseObject(data, clazz);
return responseEntity.getBody();
}

@ -0,0 +1,73 @@
//package com.ynxbd.push.httpRequest.xbd.wx;
//
//import lombok.extern.slf4j.Slf4j;
//
//@Slf4j
//public class Test {
//
// private static int RETRY_INDEX = 0;
// private static final int MAX_RETRY = 3;
//
//
// public static String test02() {
// try {
// if (RETRY_INDEX != MAX_RETRY) {
// System.out.println(1 / 0);
// log.info("请求失败");
// } else {
// log.info("请求成功");
// }
// return "1";
// } catch (Exception e) {
// log.error(e.getMessage());
// RETRY_INDEX++;
// log.error("请求微信获取Token错误:{}", e.getMessage());
// if (RETRY_INDEX > MAX_RETRY) {
// log.error("多次请求后未获取到正确token,抛出异常");
// return null;
// }
// log.error("重试请求第{}次", RETRY_INDEX);
// return test02();
// }
// }
//
// public static void main(String[] args) {
// String s = test02();
// System.out.println(s);
// }
//
//
// public static String test03() {
// try {
// if (RETRY_INDEX != MAX_RETRY) {
// System.out.println(1 / 0);
// log.info("请求失败");
// } else {
// log.info("请求成功");
// }
// return "1";
// } catch (Exception e) {
// log.error(e.getMessage());
// test04();
// }
// return null;
// }
//
//
// public static String test04() {
// try {
// if (RETRY_INDEX != MAX_RETRY) {
// System.out.println(1 / 0);
// log.info("请求失败");
// } else {
// log.info("请求成功");
// }
// return "1";
// } catch (Exception e) {
// log.error(e.getMessage());
// }
// return null;
// }
//
//
//}

@ -1,8 +1,11 @@
package com.ynxbd.push.httpRequest.xbd.wx;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ynxbd.push.config.EhCacheConfig;
import com.ynxbd.push.config.IniConfig;
import com.ynxbd.push.entity.xbd.wx.AccessToken;
import com.ynxbd.push.entity.xbd.wx.RespAccessToken;
import com.ynxbd.push.helper.DateHelper;
import com.ynxbd.push.helper.DesEncryptHelper;
import com.ynxbd.push.helper.RequestHelper;
import lombok.extern.slf4j.Slf4j;
@ -12,8 +15,8 @@ import org.ehcache.Cache;
public class WxCacheRequest {
private static final String SERVICE_URL = "http://127.0.0.1:8080/wx/api/getWxAccessToken.do";
private static final String LOCALHOST_URL = "http://wx.mzsrmyy.net/wx/api/getWxAccessToken.do";
private static Integer RETRY_INDEX = 0;
private static final Integer MAX_RETRY = 3;
private static final int MAX_RETRY = 3;
static {
@ -22,60 +25,113 @@ public class WxCacheRequest {
// 缓存
private static Cache<String, String> ACCESS_TOKEN_CACHE;
private static Cache<String, RespAccessToken> ACCESS_TOKEN_CACHE;
private static final String CACHE_NAME = "access_token";
private static final long CACHE_TIME = 7100;
private synchronized static void createAccessTokenCache() {
if (ACCESS_TOKEN_CACHE == null) {
// 一个半小时
ACCESS_TOKEN_CACHE = EhCacheConfig.createCacheTTL(String.class, String.class, "wx_access_token_cache", (7100L));
ACCESS_TOKEN_CACHE = EhCacheConfig.createCacheTTL(String.class, RespAccessToken.class, "wx_access_token_cache", (CACHE_TIME)); // 一个半小时
}
}
public static String getAccessToken() {
RespAccessToken respAccessToken = getWxAccessToken();
if (respAccessToken == null) {
return null;
}
return respAccessToken.getAccessToken();
}
/**
* 获取微信token
*/
private synchronized static RespAccessToken getWxAccessToken() {
if (ACCESS_TOKEN_CACHE == null) {
createAccessTokenCache();
}
RETRY_INDEX = 0;
String cacheName = "access_token";
String accessToken = ACCESS_TOKEN_CACHE.get(cacheName);
if (accessToken == null) {
accessToken = getWxAccessToken(ACCESS_TOKEN_CACHE, cacheName);
if (accessToken != null) {
ACCESS_TOKEN_CACHE.put(cacheName, accessToken);
log.info("启动医院为:{}", IniConfig.getInstance("name"));
try {
RespAccessToken respAccessToken = ACCESS_TOKEN_CACHE.get(CACHE_NAME);
if (respAccessToken == null) {
respAccessToken = againGetWxAccessToken();
ACCESS_TOKEN_CACHE.put(CACHE_NAME, respAccessToken);
return respAccessToken;
}
if (7200 > DateHelper.differCurSecond(respAccessToken.getCreateTime())) { // 允许100s的旧token存在(5分钟内可以继续使用佬)
respAccessToken = againGetWxAccessToken();
ACCESS_TOKEN_CACHE.put(CACHE_NAME, respAccessToken);
return respAccessToken;
}
} catch (Exception e) {
log.error("请求微信获取Token错误:{}", e.getMessage());
}
return accessToken;
return null;
}
/**
* 根据次数循环获取
*/
private static RespAccessToken againGetWxAccessToken() {
RespAccessToken respAccessToken = null;
for (int i = 0; i < MAX_RETRY; i++) {
respAccessToken = requestWxAccessToken();
if (i != 0) {
log.error("重试请求第{}次", (i + 1));
}
if (respAccessToken != null) {
return respAccessToken;
}
if ((i + 1) == MAX_RETRY) {
log.error("{} 次请求后未获取到正确token", MAX_RETRY);
}
}
return null;
}
/**
* 获取微信token
* 请求微信token
*/
public synchronized static String getWxAccessToken(Cache<String, String> cache, String cacheName) {
private static RespAccessToken requestWxAccessToken() {
try {
String accessToken = cache.get(cacheName);
if (accessToken != null) {
return accessToken;
JSONObject respJson = RequestHelper.getJsonObj(SERVICE_URL, null);
String code = respJson.getString("code");
if (!"200".equals(code)) {
log.info("请求token失败 code={}, message={}", code, respJson.getString("message"));
return null;
}
log.info("启动医院为:{}", IniConfig.getInstance("name"));
AccessToken messageSendResult = RequestHelper.get(SERVICE_URL, null, AccessToken.class);
log.info("access_code:{}", messageSendResult.getCode());
String token = DesEncryptHelper.deCode(messageSendResult.getData());
log.info("access_token:" + token);
return token;
} catch (Exception e) {
RETRY_INDEX++;
log.error("请求微信获取Token错误:{}", e.getMessage());
if(RETRY_INDEX > MAX_RETRY){
log.error("多次请求后未获取到正确token,抛出异常");
String data = respJson.getString("data");
if (data == null || "".equals(data)) {
return null;
}
RespAccessToken resp = JSON.parseObject(data, RespAccessToken.class);
if (resp == null) {
return null;
}
log.error("重试请求第{}次",RETRY_INDEX);
getWxAccessToken(ACCESS_TOKEN_CACHE, cacheName);
String accessToken = resp.getAccessToken();
if (accessToken == null) {
return null;
}
accessToken = DesEncryptHelper.deCode(accessToken);
if (accessToken == null) {
return null;
}
resp.setAccessToken(accessToken);
return resp;
} catch (Exception e) {
log.error("请求微信获取Token错误:{}", e.getMessage());
}
return null;
}
public synchronized static void clearWxAccessToken() {
if (ACCESS_TOKEN_CACHE != null) {
ACCESS_TOKEN_CACHE.remove(CACHE_NAME);
}
}
}

Loading…
Cancel
Save