Kaynağa Gözat

en+ token获取优化

skyline 2 yıl önce
ebeveyn
işleme
c1e8c14b02

+ 0 - 36
service/src/main/java/com/kym/service/enplus/impl/EnPlusServiceHelper.java

@@ -1,36 +0,0 @@
-package com.kym.service.enplus.impl;
-
-import com.kym.service.enplus.EnPlusService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.cache.annotation.CacheConfig;
-import org.springframework.cache.annotation.Cacheable;
-import org.springframework.stereotype.Service;
-
-/**
- * @author skyline
- * @description 这里处理很粗糙,后面再优化吧
- * @date 2023-08-02 15:38
- */
-@Service
-@CacheConfig
-public class EnPlusServiceHelper {
-    /*
-     * 原因:
-     * Spring 缓存注解是基于Spring AOP切面,必须走代理才能生效,同类调用或者子类调用父类带有缓存注解的方法时属于内部调用,没有走代理,所以注解不生效。
-     * 解决方法: 将方法抽离到一个独立类中
-     */
-
-    private EnPlusService enPlusService;
-
-    @Autowired
-    public void setEnPlusService(EnPlusService enPlusService) {
-        this.enPlusService = enPlusService;
-    }
-
-    @Cacheable(cacheNames = "EN_PLUS", key = "#root.methodName")
-    //有个坑,@Cacheable 注解在对象内部调用不会生效,参考:https://blog.csdn.net/zh452647457/article/details/86487423
-    public String queryToken() {
-        return enPlusService.queryToken();
-    }
-
-}

+ 12 - 8
service/src/main/java/com/kym/service/enplus/impl/EnPlusServiceImpl.java

@@ -11,6 +11,7 @@ import com.kym.common.enums.EnPlusApi;
 import com.kym.common.exception.BusinessException;
 import com.kym.common.exception.EnPushException;
 import com.kym.common.utils.AESUtil;
+import com.kym.common.utils.CommUtil;
 import com.kym.entity.common.RedisKeys;
 import com.kym.entity.enplus.EnRespQueryToken;
 import com.kym.entity.enplus.response.EnResponse;
@@ -19,7 +20,6 @@ import okhttp3.*;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.Lazy;
 import org.springframework.data.redis.core.RedisTemplate;
 import org.springframework.stereotype.Service;
 
@@ -40,7 +40,6 @@ public class EnPlusServiceImpl implements EnPlusService {
     static OkHttpClient HTTP_CLIENT = new OkHttpClient.Builder().build();
     private final RedisTemplate<String, String> redisTemplate;
 
-    private final EnPlusServiceHelper enPlusServiceHelper;
     @Value("${en-plus.operatorId}")
     private String OperatorId;
     @Value("${en-plus.operatorSecret}")
@@ -48,9 +47,8 @@ public class EnPlusServiceImpl implements EnPlusService {
     @Value("${en-plus.sigSecret}")
     private String SigSecret;
 
-    public EnPlusServiceImpl(RedisTemplate<String, String> redisTemplate, @Lazy EnPlusServiceHelper enPlusServiceHelper) {
+    public EnPlusServiceImpl(RedisTemplate<String, String> redisTemplate) {
         this.redisTemplate = redisTemplate;
-        this.enPlusServiceHelper = enPlusServiceHelper;
     }
 
     public static <T> T parse(String json, Class<T> clz) {
@@ -75,7 +73,7 @@ public class EnPlusServiceImpl implements EnPlusService {
     @Override
     public EnResponse enPlusPost(String url, String params) {
         // token获取
-        var token = enPlusServiceHelper.queryToken();
+        var token = queryToken();
         Headers headers = Headers.of("Authorization", "Bearer ".concat(token));
         RequestBody requestBody = RequestBody.create(params, JSON);
         Request request = new Request.Builder()
@@ -88,7 +86,8 @@ public class EnPlusServiceImpl implements EnPlusService {
         if (0 == response.getRet()) {
             return response;
         } else {
-            LOGGER.error("EN+接口数据异常:url:{}\n params:{}\ntoken:{}\n返回信息:{}", url, params, token, response);
+            LOGGER.error(":url:{}\n params:{}\ntoken:{}\n返回信息:{}", url, params, token, response);
+            // todo 如果返回Ret=4002,token错误的情况下,删除redis中的token,如果是预约订单则将此订单设置为延迟启动
             throw new BusinessException(ResponseEnum.EN_PLUS_API_EXCEPTION);
         }
     }
@@ -102,6 +101,11 @@ public class EnPlusServiceImpl implements EnPlusService {
     @Override
     public String queryToken() {
         LOGGER.debug("查询token");
+        var token = redisTemplate.opsForValue().get(RedisKeys.EN_PLUS_TOKEN);
+        if (CommUtil.isNotEmptyAndNull(token)) {
+            LOGGER.debug("从缓存中查询到token:{},ttl:{}", token, redisTemplate.getExpire(RedisKeys.EN_PLUS_TOKEN));
+            return token;
+        }
         var data = """
                 {
                     "OperatorID":"%s",
@@ -117,8 +121,8 @@ public class EnPlusServiceImpl implements EnPlusService {
             // 解密Data获取token
             var enRespQueryToken = JSONObject.parseObject(AESUtil.decrypt(enResponse.getData()), EnRespQueryToken.class);
             LOGGER.debug("EN+接口AccessToken:{}", enRespQueryToken.toString());
-            // 缓存token,有效期7天,这里有效期减1天,防止临界请求token失效
-            redisTemplate.opsForValue().set(RedisKeys.EN_PLUS_TOKEN, enRespQueryToken.getAccessToken(), enRespQueryToken.getTokenAvailableTime() - 3600 * 24, TimeUnit.SECONDS);
+            // 缓存token,有效期7天(我们这里每次请求en+获取token的有效期并不是从7天开始,有效期是在en+的剩余有效时间)
+            redisTemplate.opsForValue().set(RedisKeys.EN_PLUS_TOKEN, enRespQueryToken.getAccessToken(), enRespQueryToken.getTokenAvailableTime(), TimeUnit.SECONDS);
             return enRespQueryToken.getAccessToken();
         } else {
             // 记录错误码,返回错误信息