From 40ab0a4fb39672c6df1b519e19ea1b226747d055 Mon Sep 17 00:00:00 2001 From: wangsq <944414428@qq.com> Date: Tue, 26 Jul 2022 10:58:55 +0800 Subject: [PATCH] =?UTF-8?q?token=E8=8E=B7=E5=8F=96=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../ynxbd/push/controller/ApiController.java | 18 +++ .../ynxbd/push/entity/xbd/wx/AccessToken.java | 10 -- .../push/entity/xbd/wx/RespAccessToken.java | 16 +++ .../com/ynxbd/push/helper/DateHelper.java | 43 ++++++ .../com/ynxbd/push/helper/RequestHelper.java | 30 ++++- .../ynxbd/push/httpRequest/xbd/wx/Test.java | 73 +++++++++++ .../httpRequest/xbd/wx/WxCacheRequest.java | 122 +++++++++++++----- 7 files changed, 266 insertions(+), 46 deletions(-) create mode 100644 src/main/java/com/ynxbd/push/controller/ApiController.java delete mode 100644 src/main/java/com/ynxbd/push/entity/xbd/wx/AccessToken.java create mode 100644 src/main/java/com/ynxbd/push/entity/xbd/wx/RespAccessToken.java create mode 100644 src/main/java/com/ynxbd/push/helper/DateHelper.java create mode 100644 src/main/java/com/ynxbd/push/httpRequest/xbd/wx/Test.java diff --git a/src/main/java/com/ynxbd/push/controller/ApiController.java b/src/main/java/com/ynxbd/push/controller/ApiController.java new file mode 100644 index 0000000..49a09b2 --- /dev/null +++ b/src/main/java/com/ynxbd/push/controller/ApiController.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"; + } +} diff --git a/src/main/java/com/ynxbd/push/entity/xbd/wx/AccessToken.java b/src/main/java/com/ynxbd/push/entity/xbd/wx/AccessToken.java deleted file mode 100644 index 6d012d0..0000000 --- a/src/main/java/com/ynxbd/push/entity/xbd/wx/AccessToken.java +++ /dev/null @@ -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; -} diff --git a/src/main/java/com/ynxbd/push/entity/xbd/wx/RespAccessToken.java b/src/main/java/com/ynxbd/push/entity/xbd/wx/RespAccessToken.java new file mode 100644 index 0000000..7476bca --- /dev/null +++ b/src/main/java/com/ynxbd/push/entity/xbd/wx/RespAccessToken.java @@ -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; +} diff --git a/src/main/java/com/ynxbd/push/helper/DateHelper.java b/src/main/java/com/ynxbd/push/helper/DateHelper.java new file mode 100644 index 0000000..c10c84b --- /dev/null +++ b/src/main/java/com/ynxbd/push/helper/DateHelper.java @@ -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(); + + } +} diff --git a/src/main/java/com/ynxbd/push/helper/RequestHelper.java b/src/main/java/com/ynxbd/push/helper/RequestHelper.java index 55fa1eb..16d414d 100644 --- a/src/main/java/com/ynxbd/push/helper/RequestHelper.java +++ b/src/main/java/com/ynxbd/push/helper/RequestHelper.java @@ -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 get(String url, Map params, Class clazz) { + return JSON.parseObject(get(url, params), clazz); + } + + + /** + * 向目的URL发送get请求 + * + * @param url 请求地址 + * @param params 请求参数 + * @return ResultVO + */ + public static JSONObject getJsonObj(String url, Map params) { + return JSON.parseObject(get(url, params)); + } + + + /** + * 向目的URL发送get请求 + * + * @param url 请求地址 + * @param params 请求参数 + * @return ResultVO + */ + public static String get(String url, Map params) { RestTemplate client = new RestTemplate(); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Type", "application/x-www-form-urlencoded"); - HttpEntity> request = new HttpEntity<>(params,headers); + HttpEntity> request = new HttpEntity<>(params, headers); ResponseEntity responseEntity = client.getForEntity(url, String.class, request); - String data = responseEntity.getBody(); - return JSON.parseObject(data, clazz); + return responseEntity.getBody(); } diff --git a/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/Test.java b/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/Test.java new file mode 100644 index 0000000..48d5612 --- /dev/null +++ b/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/Test.java @@ -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; +// } +// +// +//} diff --git a/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/WxCacheRequest.java b/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/WxCacheRequest.java index 9646cad..8055bec 100644 --- a/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/WxCacheRequest.java +++ b/src/main/java/com/ynxbd/push/httpRequest/xbd/wx/WxCacheRequest.java @@ -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 ACCESS_TOKEN_CACHE; + private static Cache 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 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); + } + } + }