chenbiao 2 years ago
parent
commit
9299e2ea32

+ 4 - 0
midjourney/src/main/java/com/yhlxj/service/midjourney/impl/MidjourneyServiceImpl.java

@@ -625,6 +625,7 @@ public class MidjourneyServiceImpl implements MidjourneyService {
             if(url.getFile().contains("webp")){
                scaling += "&format=webp";
             }
+            log.info("任务执行回调 imgUrl:{}", conversation.getImageUrl());
             // 使用 Hutool 提取各个部分并构建新 URL
             String newUrl = URLUtil.toURI(new URL(url.getProtocol(), "cdn.mj.liuliangbang.vip", url.getPort(), url.getFile() + scaling)).toString();
             //
@@ -638,6 +639,9 @@ public class MidjourneyServiceImpl implements MidjourneyService {
             if (wssSession != null) {
                 wssSession.sendMessage(WsMessageTypeEnum.SERVER_TASK_INFO, new JSONObject(conversation));
             }
+            conversationMapper.update(null, QueryWrapperUtils.buildUpdateWrapper((wrapper)->{
+                wrapper.eq(MidjourneyUserConversation::getAction,"MODEL").eq(MidjourneyUserConversation::getTaskId, conversation.getTaskId()).set(MidjourneyUserConversation::getAction, conversation.getAction());
+            }));
         });
 
         TASK_EXECUTOR.execute(() -> {

+ 127 - 0
midjourney/src/main/java/com/yhlxj/web/GlobalExceptionHandler.java

@@ -0,0 +1,127 @@
+package com.yhlxj.web;
+
+import cn.hutool.core.lang.Validator;
+import com.cyksj.common.exception.BusinessRuntimeException;
+import com.cyksj.common.util.StringUtil;
+import com.cyksj.dto.Result;
+import com.cyksj.enums.GatewayApiCode;
+import com.cyksj.enums.GatewayResponse;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.validation.BindException;
+import org.springframework.validation.FieldError;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.validation.ConstraintViolation;
+import javax.validation.ConstraintViolationException;
+import java.util.List;
+import java.util.Set;
+import java.util.TreeSet;
+
+/**
+ * @description 异常全局拦截
+ * @author chan
+ * @date 2021-03-22 9:51 下午
+ */
+@Slf4j
+@RestControllerAdvice
+public class GlobalExceptionHandler {
+
+    @Autowired
+    protected HttpServletRequest request;
+
+    private final static List<String> token = List.of("token无效", "token已过期");
+
+    @ExceptionHandler(value = {Exception.class})
+    public Result<String> handleNoteException(Exception e) {
+        StringBuilder builder = new StringBuilder(32);
+        builder.append(request.getRequestURI()).append(" -- > ");
+
+        StackTraceElement[] trace = e.getStackTrace();
+        log.info("{}",e);
+        for (StackTraceElement element : trace) {
+            if (StringUtil.startsWith(element.getClassName(), "com.cyksj")) {
+                builder.append(element.getFileName())
+                        .append("[").append(element.getLineNumber()).append("]")
+                        .append("&");
+            }
+        }
+        builder.deleteCharAt(builder.length() - 1);
+
+        String message = e.getMessage();
+        String value = builder.toString();
+        GatewayApiCode apiCode = null;
+        if (e instanceof BusinessRuntimeException) {
+            BusinessRuntimeException ee = (BusinessRuntimeException) e;
+            String code = ee.getCode();
+            if (Validator.isNumber(code)) {
+                if (GatewayApiCode.CMS_TOKEN_VALID.getCode().equals(Integer.parseInt(code))) {
+                    apiCode = GatewayApiCode.CMS_TOKEN_VALID;
+                }
+            }
+        }
+        log.error("全局错误处理: \n Cause: {} \n Value: {}", message, value);
+        if (apiCode != null) {
+            return GatewayResponse.FAIL.newBuilder().buildGatewayCode(apiCode).toResult();
+        }
+        return GatewayResponse.FAIL.newBuilder().setMsg(message).toResult(value);
+    }
+
+    @ExceptionHandler(value = ConstraintViolationException.class)
+    public Result<String> ConstraintViolationException(ConstraintViolationException ex) {
+        String message = "";
+        // 使用TreeSet是为了让输出的内容有序输出(默认验证的顺序是随机的)
+        Set<String> errorInfoSet = new TreeSet<String>();
+        Set<ConstraintViolation<?>> violations = ex.getConstraintViolations();
+        if (!violations.isEmpty()) {
+            for (ConstraintViolation<?> item : violations) {
+                System.out.println(item.getPropertyPath());
+                // 遍历错误字段信息
+                errorInfoSet.add(item.getMessage());
+            }
+
+            StringBuilder sbf = new StringBuilder();
+            for (String errorInfo : errorInfoSet) {
+                sbf.append(errorInfo);
+                sbf.append(",");
+            }
+            message = sbf.substring(0, sbf.length() - 1);
+        }
+
+        log.error("错误字段 信息: \n Value: {}", message);
+
+        return GatewayResponse.FAIL.newBuilder().buildGatewayCode(GatewayApiCode.PARAMETER_MISSING_ERROR).setMsg(message).toResult();
+    }
+
+    @ExceptionHandler(BindException.class)
+    public Result<String> BindException(BindException bindingResult) {
+
+        // 验证参数信息是否有效
+        if (bindingResult.hasErrors()) {
+            // 获取错误字段信息集合
+            List<FieldError> fieldErrorList = bindingResult.getFieldErrors();
+
+            // 使用TreeSet是为了让输出的内容有序输出(默认验证的顺序是随机的)
+            Set<String> errorInfoSet = new TreeSet<String>();
+            for (FieldError fieldError : fieldErrorList) {
+                // 遍历错误字段信息
+                errorInfoSet.add(fieldError.getDefaultMessage());
+            }
+
+            StringBuilder sbf = new StringBuilder();
+            for (String errorInfo : errorInfoSet) {
+                sbf.append(errorInfo);
+                sbf.append(",");
+            }
+            String message = sbf.substring(0, sbf.length() - 1);
+
+            log.error("验证参数信息是否有效 错误信息: \n Value: {}", message);
+
+            return GatewayResponse.FAIL.newBuilder().buildGatewayCode(GatewayApiCode.PARAMETER_MISSING_ERROR).setMsg(message).toResult();
+
+        }
+        return GatewayResponse.SUCCESS.newBuilder().buildGatewayCode(GatewayApiCode.SUCCESS).setMsg("参数校验通过").toResult();
+    }
+}

+ 9 - 2
midjourney/src/main/java/com/yhlxj/web/wss/MidjourneyServerEndpoint.java

@@ -20,6 +20,7 @@ import javax.websocket.server.ServerEndpoint;
 import java.io.IOException;
 import java.util.Map;
 import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.TimeUnit;
 
 /**
  * @author chan
@@ -43,6 +44,7 @@ public class MidjourneyServerEndpoint {
     public void onOpen(Session session, @PathParam("userToken") String userToken, @PathParam("taskId") String taskId) throws IOException {
         log.info("[WS建立连接],token:{}, taskId:{}", userToken, taskId);
 
+        session.setMaxIdleTimeout(TimeUnit.MINUTES.toMillis(5));
         //检查uniodId是否合法
         if (StringUtils.isBlank(userToken) || StringUtils.isBlank(taskId)) {
 
@@ -134,11 +136,14 @@ public class MidjourneyServerEndpoint {
      * @param error
      */
     @OnError
-    public void OnError(Session session, Throwable error) throws IOException {
+    public void OnError(Session session, Throwable error, @PathParam("userToken") String userToken, @PathParam("taskId") String taskId) throws IOException {
         log.error("[WS ONERROR],{}", error.getMessage());
         if (session.isOpen()) {
             session.close();
         }
+        log.info("[WS ONERROR],移除连接池内连接");
+        MidjourneyUser user = getUser(userToken);
+        WSS_SESSION_MAP.remove(user.getId());
     }
 
     /**
@@ -153,12 +158,14 @@ public class MidjourneyServerEndpoint {
         if (session.isOpen()) {
             session.close();
         }
+        log.info("[WS连接关闭],移除连接池内连接");
+        MidjourneyUser user = getUser(userToken);
+        WSS_SESSION_MAP.remove(user.getId());
     }
 
     public MidjourneyUser getUser(String userToken) {
         MidjourneyService midjourneyService = SpringCtxUtils.getBean(MidjourneyServiceImpl.class);
         return midjourneyService.getUser(userToken);
-
     }
 
 }

File diff suppressed because it is too large
+ 0 - 0
midjourney/src/main/resources/application-prd.yml


Some files were not shown because too many files changed in this diff