Browse Source

更新token错误

xiewj 2 years ago
parent
commit
7da080edaa

+ 32 - 4
src/main/java/com/fdkk/bim/Interceptor/BimFaceInterceptor.java

@@ -1,10 +1,15 @@
 package com.fdkk.bim.Interceptor;
 package com.fdkk.bim.Interceptor;
 
 
 import cn.hutool.extra.spring.SpringUtil;
 import cn.hutool.extra.spring.SpringUtil;
+import com.alibaba.fastjson2.JSON;
+import com.alibaba.fastjson2.JSONObject;
+import com.dtflys.forest.exceptions.ForestRuntimeException;
 import com.dtflys.forest.http.ForestRequest;
 import com.dtflys.forest.http.ForestRequest;
 import com.dtflys.forest.http.ForestResponse;
 import com.dtflys.forest.http.ForestResponse;
 import com.dtflys.forest.interceptor.Interceptor;
 import com.dtflys.forest.interceptor.Interceptor;
 import com.dtflys.forest.reflection.ForestMethod;
 import com.dtflys.forest.reflection.ForestMethod;
+import com.fdkankan.redis.util.RedisUtil;
+import com.fdkk.bim.client.BimFaceClient;
 import com.fdkk.bim.config.BimFaceConfig;
 import com.fdkk.bim.config.BimFaceConfig;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Autowired;
@@ -15,8 +20,6 @@ import org.springframework.beans.factory.annotation.Autowired;
  */
  */
 @Slf4j
 @Slf4j
 public class BimFaceInterceptor<T> implements Interceptor<T> {
 public class BimFaceInterceptor<T> implements Interceptor<T> {
-   @Autowired
-   BimFaceConfig bimFaceConfig;
 
 
 
 
    /**
    /**
@@ -27,9 +30,13 @@ public class BimFaceInterceptor<T> implements Interceptor<T> {
    @Override
    @Override
    public void onInvokeMethod(ForestRequest req, ForestMethod method, Object[] args) {
    public void onInvokeMethod(ForestRequest req, ForestMethod method, Object[] args) {
       log.info("on invoke method");
       log.info("on invoke method");
-      if (!method.getMethodName().equals("getToken")){
+      RedisUtil cache = SpringUtil.getBean(RedisUtil.class);
+      if (!method.getMethodName().equals("getToken")&&cache.hasKey("bim:token")){
+         req.addHeader("Authorization", "Bearer "+cache.get("bim:token"));  // 添加Header
+      }else if (!method.getMethodName().equals("getToken")){
          BimFaceConfig bean = SpringUtil.getBean(BimFaceConfig.class);
          BimFaceConfig bean = SpringUtil.getBean(BimFaceConfig.class);
-         req.addHeader("Authorization", "Bearer "+bean.getAccessToken());  // 添加Header
+         bean.reload();
+         req.addHeader("Authorization", "Bearer "+cache.get("bim:token"));  // 添加Header
       }
       }
    }
    }
 
 
@@ -40,5 +47,26 @@ public class BimFaceInterceptor<T> implements Interceptor<T> {
    public void onSuccess(T data, ForestRequest req, ForestResponse res) {
    public void onSuccess(T data, ForestRequest req, ForestResponse res) {
       log.info("invoke Simple onSuccess {},data:{}",res,data);
       log.info("invoke Simple onSuccess {},data:{}",res,data);
    }
    }
+
+   /**
+    * 该方法在请求发送失败时被调用
+    */
+   @Override
+   public void onError(ForestRuntimeException ex, ForestRequest req, ForestResponse res) {
+      log.info("invoke Simple onError {},data:{}",res,req);
+      String content = res.getContent();
+      JSONObject resJSON = JSON.parseObject(content);
+      if (res.getStatusCode()==401&&resJSON.getString("error").equals("invalid_token")){
+         log.info("onError 401 ,retry");
+      }
+
+
+//
+//      // 执行发送请求失败后处理的代码
+//      int status = res.getStatusCode(); // 获取请求响应状态码
+//      String content = res.getContent(); // 获取请求的响应内容
+//      String result = res.getResult(); // 获取方法返回类型对应的返回数据结果
+
+   }
 }
 }
 
 

+ 2 - 0
src/main/java/com/fdkk/bim/client/BimFaceClient.java

@@ -8,6 +8,7 @@ import com.fdkk.bim.bimEntity.dto.ProjectDTO;
 import com.fdkk.bim.bimEntity.dto.TranslateDTO;
 import com.fdkk.bim.bimEntity.dto.TranslateDTO;
 import com.fdkk.bim.bimEntity.vo.*;
 import com.fdkk.bim.bimEntity.vo.*;
 import com.fdkk.bim.bimEntity.BimResult;
 import com.fdkk.bim.bimEntity.BimResult;
+import com.fdkk.bim.retryCondition.BimRetryCondition;
 
 
 import java.util.List;
 import java.util.List;
 
 
@@ -18,6 +19,7 @@ import java.util.List;
 @BaseRequest(
 @BaseRequest(
         baseURL = "https://api.bimface.com",
         baseURL = "https://api.bimface.com",
         interceptor = {BimFaceInterceptor.class})
         interceptor = {BimFaceInterceptor.class})
+@Retry(maxRetryCount = "1", maxRetryInterval = "10" ,condition = BimRetryCondition.class)
 public interface BimFaceClient {
 public interface BimFaceClient {
     @Post("/oauth2/token")
     @Post("/oauth2/token")
     BimResult<AccessTokenBean> getToken(@Header("Authorization") String Authorization);
     BimResult<AccessTokenBean> getToken(@Header("Authorization") String Authorization);

+ 12 - 6
src/main/java/com/fdkk/bim/config/BimFaceConfig.java

@@ -40,22 +40,28 @@ public class BimFaceConfig {
 
 
     public String appSecret;
     public String appSecret;
 
 
-    public String accessToken;
 
 
     @PostConstruct
     @PostConstruct
-    private void init(){
+    public void init(){
        String Authorization = Base64.encode((appKey+":"+appSecret).getBytes());
        String Authorization = Base64.encode((appKey+":"+appSecret).getBytes());
         if (cache.hasKey("bim:token")){
         if (cache.hasKey("bim:token")){
-            this.accessToken=cache.get("bim:token");
+                cache.get("bim:token");
         }else {
         }else {
             BimResult<AccessTokenBean> token = bimFaceClient.getToken("Basic " + Authorization);
             BimResult<AccessTokenBean> token = bimFaceClient.getToken("Basic " + Authorization);
             if (ObjectUtil.isNotNull(token)&&token.getCode().equals("success")){
             if (ObjectUtil.isNotNull(token)&&token.getCode().equals("success")){
-                this.accessToken=token.getData().getToken();
                 log.info("token,-{}",token.getData());
                 log.info("token,-{}",token.getData());
-                cache.set("bim:token",token.getData().getToken(),TimeUnit.SECONDS.convert(6,TimeUnit.DAYS));
+                cache.set("bim:token",token.getData().getToken(),TimeUnit.SECONDS.convert(1,TimeUnit.DAYS));
             }
             }
         }
         }
-
     }
     }
+    public void reload(){
+        String Authorization = Base64.encode((appKey+":"+appSecret).getBytes());
+        BimResult<AccessTokenBean> token = bimFaceClient.getToken("Basic " + Authorization);
+        if (ObjectUtil.isNotNull(token)&&token.getCode().equals("success")){
+            log.info("token,-{}",token.getData());
+            cache.set("bim:token",token.getData().getToken(),TimeUnit.SECONDS.convert(1,TimeUnit.DAYS));
+            log.info("token,-{}",cache.get("bim:token"));
 
 
+        }
+    }
 }
 }

+ 8 - 5
src/main/java/com/fdkk/bim/controller/TestController.java

@@ -1,5 +1,8 @@
 package com.fdkk.bim.controller;
 package com.fdkk.bim.controller;
 
 
+import com.fdkk.bim.bimEntity.BimResult;
+import com.fdkk.bim.bimEntity.vo.ProjectBean;
+import com.fdkk.bim.client.BimFaceClient;
 import com.fdkk.bim.entity.po.BimFaceEntity;
 import com.fdkk.bim.entity.po.BimFaceEntity;
 import com.fdkk.bim.service.BimFaceService;
 import com.fdkk.bim.service.BimFaceService;
 import lombok.extern.slf4j.Slf4j;
 import lombok.extern.slf4j.Slf4j;
@@ -10,6 +13,7 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 import org.springframework.web.bind.annotation.*;
 
 
 import javax.annotation.Resource;
 import javax.annotation.Resource;
+import java.util.List;
 
 
 /**
 /**
  * @author Xiewj
  * @author Xiewj
@@ -26,13 +30,12 @@ public class TestController extends BaseController {
     @Resource
     @Resource
     BimCallBackClient bimCallBackClient;
     BimCallBackClient bimCallBackClient;
 
 
-
+    @Autowired
+    BimFaceClient bimFaceClient;
     @PostMapping("/save")
     @PostMapping("/save")
     public Result translate() {
     public Result translate() {
-        BimFaceEntity bimFaceEntity=new BimFaceEntity();
-        bimFaceEntity.setTask("bimFaceEntity");
-        bimFaceService.save(bimFaceEntity);
-        return success();
+        BimResult<List<ProjectBean>> uat1 = bimFaceClient.getProjectInfo("uat1");
+        return success(uat1);
     }
     }
 
 
     @PostMapping("/send")
     @PostMapping("/send")

+ 43 - 0
src/main/java/com/fdkk/bim/retryCondition/BimRetryCondition.java

@@ -0,0 +1,43 @@
+package com.fdkk.bim.retryCondition;
+
+import cn.hutool.extra.spring.SpringUtil;
+import com.dtflys.forest.callback.RetryWhen;
+import com.dtflys.forest.http.ForestRequest;
+import com.dtflys.forest.http.ForestResponse;
+import com.dtflys.forest.interceptor.Interceptor;
+import com.fdkankan.redis.util.RedisUtil;
+import com.fdkk.bim.config.BimFaceConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+
+/**
+ * @author Xiewj
+ * @date 2022/10/17
+ */
+public class BimRetryCondition implements RetryWhen {
+
+   /**
+    * 在请重试前调用 onRetry 回调函数
+    *
+    * @param req Forest请求对象
+    * @param res Forest响应对象
+    */
+   /**
+    * 请求重试条件
+    * @param req Forest请求对象
+    * @param res Forest响应对象
+    * @return true 重试,false 不重试
+    */
+   @Override
+   public boolean retryWhen(ForestRequest req, ForestResponse res) {
+      // 响应状态码为 203 就重试
+      if (res.statusIs(401)&&res.getContent().contains("invalid_token")){
+         BimFaceConfig bimFaceConfig= SpringUtil.getBean(BimFaceConfig.class);
+         bimFaceConfig.reload();
+         RedisUtil cache = SpringUtil.getBean(RedisUtil.class);
+         req.addHeader("Authorization", "Bearer "+cache.get("bim:token"));  // 添加Header
+         return true;
+
+      }
+      return false;
+   }
+}

+ 1 - 0
src/main/resources/application-dev.yml

@@ -21,6 +21,7 @@ spring:
     port: 6379
     port: 6379
     timeout: 6000ms
     timeout: 6000ms
     password: 1234
     password: 1234
+    database: 2
     # cluster:
     # cluster:
     #   max-redirects: 3  # 获取失败 最大重定向次数
     #   max-redirects: 3  # 获取失败 最大重定向次数
     #   nodes:
     #   nodes:

+ 7 - 2
startJar.sh

@@ -2,6 +2,9 @@ APP_NAME=
 APP_DEBUG=
 APP_DEBUG=
 APP_DUMPlOG=/mnt/fdkk_bim/logs/heapdump/heapdump.log
 APP_DUMPlOG=/mnt/fdkk_bim/logs/heapdump/heapdump.log
 date=`date`
 date=`date`
+path=$(pwd)
+
+
 usage() {
 usage() {
     echo "case: sh run.sh [start|stop|restart|status|checkServer]"
     echo "case: sh run.sh [start|stop|restart|status|checkServer]"
     echo "请类似这样执行 ./*.sh start prod  or  ./*sh restart prod"
     echo "请类似这样执行 ./*.sh start prod  or  ./*sh restart prod"
@@ -9,6 +12,8 @@ usage() {
 }
 }
 
 
 checkEnv(){
 checkEnv(){
+      echo "prod config"
+
       if [ -z "${APP_NAME}" ] || [ -z "${APP_DEBUG}" ]; then #判断pid是否为空
       if [ -z "${APP_NAME}" ] || [ -z "${APP_DEBUG}" ]; then #判断pid是否为空
            if [[ $1 = 'prod' ]];   then
            if [[ $1 = 'prod' ]];   then
                         echo "prod config"
                         echo "prod config"
@@ -46,7 +51,7 @@ start(){
     if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
     if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
         echo "${APP_NAME} running. pid=${pid}"
         echo "${APP_NAME} running. pid=${pid}"
     else
     else
-        nohup java -jar -Xmx4072M -Xms1024M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${APP_DUMPlOG} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${APP_DEBUG} $APP_NAME --spring.profiles.active=$1  > logs.log 2>error.log &  # 说明pid为空 执行java -jar 命令启动服务
+        nohup java -jar -Xmx4072M -Xms1024M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${APP_DUMPlOG} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${APP_DEBUG} ${path}/${APP_NAME} --spring.profiles.active=$1  > logs.log 2>error.log &  # 说明pid为空 执行java -jar 命令启动服务
         # 执行java -jar 命令启动服务
         # 执行java -jar 命令启动服务
         echo "${APP_NAME} started启动"
         echo "${APP_NAME} started启动"
     fi
     fi
@@ -108,7 +113,7 @@ restart(){
         if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
         if [ $? -eq "0" ]; then    # [$? -eq "0"] 说明pid不等于空 说明服务正在运行中,将进程号打印出来
             echo "${APP_NAME} running. pid=${pid}"
             echo "${APP_NAME} running. pid=${pid}"
         else
         else
-            nohup java -jar -Xmx4072M -Xms1024M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${APP_DUMPlOG} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${APP_DEBUG} $APP_NAME --spring.profiles.active=$1  > logs.log 2>error.log &  # 说明pid为空 执行java -jar 命令启动服务
+            nohup java -jar -Xmx4072M -Xms1024M -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=${APP_DUMPlOG} -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=${APP_DEBUG} ${path}/${APP_NAME} --spring.profiles.active=$1  > logs.log 2>error.log &  # 说明pid为空 执行java -jar 命令启动服务
             echo "${APP_NAME} started启动"
             echo "${APP_NAME} started启动"
         fi
         fi
 }
 }