Browse Source

返回优化

wangtao 3 years ago
parent
commit
03496d09fd

+ 35 - 22
lb-app/src/main/java/com/ydd/app/controller/StoreApi.java

@@ -9,6 +9,7 @@ import com.ydd.common.annotation.ControllerLog;
 import com.ydd.common.core.controller.BaseController;
 import com.ydd.common.core.domain.BaseResult;
 import com.ydd.common.core.domain.ResponseResult;
+import com.ydd.common.enums.ResponseResultCodeEnum;
 import com.ydd.common.utils.StringUtils;
 import com.ydd.module.domain.Shop;
 import com.ydd.module.expection.CustomAppException;
@@ -17,6 +18,7 @@ import io.swagger.annotations.ApiOperation;
 import lombok.RequiredArgsConstructor;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.validation.annotation.Validated;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RequestMethod;
 import org.springframework.web.bind.annotation.RestController;
@@ -44,9 +46,13 @@ public class StoreApi extends BaseController {
     @ApiOperation("新增门店")
     @RequestMapping(value = "/create", method = RequestMethod.POST)
     @AccessToken
-    public ResponseResult saveShop(StoreDto storeDto) {
-        Shop shop = apiStoreService.saveShop(getLoginId(), storeDto, false);
-        return ResponseResult.success(shop.getCode());
+    public ResponseResult saveShop(@RequestBody @Validated StoreDto storeDto) {
+        JSONObject resp = apiStoreService.saveShop(getLoginId(), storeDto, false);
+        if (resp.get("code") != null) {
+            return ResponseResult.error((ResponseResultCodeEnum) resp.get("code"));
+        } else {
+            return ResponseResult.success(resp.getString("shopCode"));
+        }
     }
 
 
@@ -56,9 +62,13 @@ public class StoreApi extends BaseController {
     @ApiOperation("更新门店资料")
     @RequestMapping(value = "/update", method = RequestMethod.POST)
     @AccessToken
-    public ResponseResult modify(StoreDto shopReq) {
-        Shop shop = apiStoreService.modify(getLoginId(), shopReq);
-        return ResponseResult.success(shop.getCode());
+    public ResponseResult modify(@RequestBody @Validated StoreDto shopReq) {
+        JSONObject resp = apiStoreService.modify(getLoginId(), shopReq);
+        if (resp.get("code") != null) {
+            return ResponseResult.error((ResponseResultCodeEnum) resp.get("code"));
+        } else {
+            return ResponseResult.success(resp.getString("shopCode"));
+        }
     }
 
     /**
@@ -67,32 +77,35 @@ public class StoreApi extends BaseController {
     @ApiOperation("门店运力禁用")
     @RequestMapping(value = "/delivery/status", method = RequestMethod.POST)
     @AccessToken
-    public BaseResult changeShopDelivery(@Validated StoreStatusDto dto) {
-        try {
-            if (StringUtils.isNotBlank(dto.getDeliveryIdStr())) {
-                apiStoreService.changeShopDelivery(getLoginId(), dto);
-                return BaseResult.success();
+    public ResponseResult changeShopDelivery(@RequestBody @Validated StoreStatusDto dto) {
+
+        if (StringUtils.isNotBlank(dto.getDeliveryIdStr())) {
+            JSONObject json = apiStoreService.changeShopDelivery(getLoginId(), dto);
+            if (json.get("code") != null) {
+                return ResponseResult.error((ResponseResultCodeEnum) json.get("code"));
             } else {
-                return BaseResult.error("运力id不能为空");
+                return ResponseResult.success();
             }
-        } catch (CustomAppException e) {
-            return BaseResult.error(e.getMessage());
+
+        } else {
+            return ResponseResult.error(ResponseResultCodeEnum.SHOP_DELIVERY_NOT_FOUND);
         }
+
     }
 
     @ApiOperation("门店运力查询")
     @RequestMapping(value = "/delivery", method = RequestMethod.POST)
     @AccessToken
-    public BaseResult delivery(@Validated StoreStatusDto dto) {
-        try {
-            if (StringUtils.isNotBlank(dto.getDeliveryIdStr())) {
-                JSONObject json = apiStoreService.queryhopDelivery(getLoginId(), dto);
-                return BaseResult.success(json);
+    public ResponseResult delivery(@RequestBody @Validated StoreStatusDto dto) {
+        if (StringUtils.isNotBlank(dto.getDeliveryIdStr())) {
+            JSONObject json = apiStoreService.queryhopDelivery(getLoginId(), dto);
+            if (json.get("code") != null) {
+                return ResponseResult.error((ResponseResultCodeEnum) json.get("code"));
             } else {
-                return BaseResult.error("运力id不能为空");
+                return ResponseResult.success(json);
             }
-        } catch (CustomAppException e) {
-            return BaseResult.error(e.getMessage());
+        } else {
+            return ResponseResult.error(ResponseResultCodeEnum.SHOP_DELIVERY_NOT_FOUND);
         }
     }
 

+ 2 - 1
lb-app/src/main/java/com/ydd/app/dto/StoreDto.java

@@ -6,6 +6,7 @@ import lombok.NoArgsConstructor;
 import lombok.experimental.Accessors;
 
 import javax.validation.constraints.NotBlank;
+import javax.validation.constraints.NotNull;
 import java.io.Serializable;
 
 /**
@@ -119,7 +120,7 @@ public class StoreDto extends  BaseDto implements Serializable {
     private String foodLicensePic;
 
     /** 食品经营许可 */
-    @NotBlank(message = "门店分类ID不能为空")
+    @NotNull(message = "门店分类ID不能为空")
     @ApiModelProperty(value = "门店分类ID")
     private Long categoryId;
 

+ 3 - 3
lb-app/src/main/java/com/ydd/app/service/ApiStoreService.java

@@ -30,7 +30,7 @@ public interface ApiStoreService {
      * @param shop
      * @param isMerchant true是商家,false是门店
      */
-    Shop saveShop(Long loginId, StoreDto shop, boolean isMerchant);
+    JSONObject saveShop(Long loginId, StoreDto shop, boolean isMerchant);
 
 
 
@@ -39,14 +39,14 @@ public interface ApiStoreService {
      * @param loginId
      * @param shopReq
      */
-    Shop modify(Long loginId, StoreDto shopReq);
+    JSONObject modify(Long loginId, StoreDto shopReq);
 
 
 
 
     Integer getFengniaoShopStatus(Shop shop, DspDelivery d,String lbClient);
 
-    void  changeShopDelivery(Long loginId,StoreStatusDto storeStatusDto);
+    JSONObject  changeShopDelivery(Long loginId,StoreStatusDto storeStatusDto);
 
     JSONObject queryhopDelivery(Long loginId, StoreStatusDto storeStatusDto);
 

+ 48 - 17
lb-app/src/main/java/com/ydd/app/service/impl/ApiStoreServiceImpl.java

@@ -10,6 +10,7 @@ import com.ydd.app.dto.StoreDto;
 import com.ydd.app.dto.StoreStatusDto;
 import com.ydd.app.service.ApiStoreService;
 import com.ydd.common.enums.DeliveryTypeEnums;
+import com.ydd.common.enums.ResponseResultCodeEnum;
 import com.ydd.common.utils.SnCodeUtils;
 import com.ydd.ecloud.core.utils.JsonMapper;
 import com.ydd.module.domain.*;
@@ -66,17 +67,24 @@ public class ApiStoreServiceImpl implements ApiStoreService {
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public Shop saveShop(Long loginId, StoreDto shopReq, boolean isMerchant) {
+    public JSONObject saveShop(Long loginId, StoreDto shopReq, boolean isMerchant) {
+        JSONObject resp = new JSONObject();
+        resp.put("code",0);
         Member member = iMemberService.getById(loginId);
-        if (member.getMerchantId() == null) {
-            throw new CustomAppException("请先申请成为商家!");
-        }
+//        if (member.getMerchantId() == null) {
+//            resp.put("code",-1);
+//            resp.put("msg","门店分类不存在");
+//            return resp;
+//            throw new CustomAppException("请先申请成为商家!");
+//        }
         Merchant merchant = iMerchantService.getById(member.getMerchantId());
         if (merchant.getStatus().equals(MerchantStatusEnum.STOP.status)) {
-            throw new CustomAppException("该商家已禁用!");
+            resp.put("code", ResponseResultCodeEnum.MERCHANT_DISABLE);
+            return resp;
         }
         if (merchant.getStatus().equals(MerchantStatusEnum.TO_BE_CERTIFIED.status)) {
-            throw new CustomAppException("请等待商家通过认证!");
+            resp.put("code", ResponseResultCodeEnum.MERCHANT_IS_AUDIT);
+            return resp;
         }
         Long categoryId = merchant.getCategoryId();
         if (null != shopReq.getCategoryId()) {
@@ -84,7 +92,13 @@ public class ApiStoreServiceImpl implements ApiStoreService {
         }
         MerchantCategory category = iMerchantCategoryService.getById(categoryId);
         if (category == null) {
-            throw new CustomAppException("门店分类不存在!");
+            resp.put("code", ResponseResultCodeEnum.SHOP_CATEGORY_NOT_EXIST);
+            return resp;
+        }
+        Shop existShop = iShopService.getOne(new QueryWrapper<Shop>().eq("name",shopReq.getShopName()));
+        if(existShop!=null){
+            resp.put("code", ResponseResultCodeEnum.SHOP_EXIST);
+            return resp;
         }
         Shop shop = new Shop();
         shop = shopBean(shop,shopReq);
@@ -160,8 +174,8 @@ public class ApiStoreServiceImpl implements ApiStoreService {
             saveShopThird(shop,delivery.getDeliveryId());
         }
 
-
-        return shop;
+        resp.put("shopCode",shop.getCode());
+        return resp;
     }
 
     private  Shop shopBean(Shop shop,StoreDto shopReq){
@@ -251,10 +265,12 @@ public class ApiStoreServiceImpl implements ApiStoreService {
     }
 
     @Override
-    public void changeShopDelivery(Long loginId,StoreStatusDto storeStatusDto) {
+    public JSONObject changeShopDelivery(Long loginId,StoreStatusDto storeStatusDto) {
+        JSONObject json = new JSONObject();
         Shop shop = iShopService.getByCode(storeStatusDto.getShopCode());
         if (shop == null) {
-            throw new CustomAppException("门店不存在!");
+            json.put("code", ResponseResultCodeEnum.SHOP_NOT_EXIST);
+            return  json;
         }
         String deliverIds = storeStatusDto.getDeliveryIdStr();
         if(StatusEnum.SHOW.getStatus().equals(storeStatusDto.getStatus())){
@@ -269,17 +285,19 @@ public class ApiStoreServiceImpl implements ApiStoreService {
                 iShopDeliveryDisableService.save(bean);
             }
         }
-
+        return json;
     }
 
     @Override
     public JSONObject queryhopDelivery(Long loginId, StoreStatusDto storeStatusDto) {
+        JSONObject json = new JSONObject();
         Shop shop = iShopService.getByCode(storeStatusDto.getShopCode());
         if (shop == null) {
-            throw new CustomAppException("门店不存在!");
+            json.put("code", ResponseResultCodeEnum.SHOP_NOT_EXIST);
+            return  json;
         }
         List<StoreDeliveryDto> list = iShopDeliveryDisableService.shopDelivery(shop.getId());
-        JSONObject json = new JSONObject();
+
         json.put("shopCode",shop.getCode());
         json.put("list",list);
         return  json;
@@ -287,11 +305,22 @@ public class ApiStoreServiceImpl implements ApiStoreService {
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public Shop modify(Long loginId, StoreDto storeDto) {
+    public JSONObject modify(Long loginId, StoreDto storeDto) {
+        JSONObject resp = new JSONObject();
+        resp.put("code",0);
         Shop shop = iShopService.getByCode(storeDto.getShopCode());
         if (shop == null) {
-            throw new CustomAppException("门店不存在!");
+
+            return resp;
+        }
+        if(!shop.getName().equals(storeDto.getShopName())){
+            Shop existShop = iShopService.getOne(new QueryWrapper<Shop>().eq("name",storeDto.getShopName()));
+            if(existShop!=null){
+                resp.put("code", ResponseResultCodeEnum.SHOP_EXIST);
+                return resp;
+            }
         }
+
         shop = shopBean(shop,storeDto);
         if (storeDto.getCategoryId() != null){
             shop.setCategoryId(storeDto.getCategoryId());
@@ -382,7 +411,9 @@ public class ApiStoreServiceImpl implements ApiStoreService {
             }
             saveShopThird(shop,delivery.getDeliveryId());
         }
-        return  shop;
+
+        resp.put("shopCode",shop.getCode());
+        return resp;
     }
 
 }

+ 5 - 2
lb-common/src/main/java/com/ydd/common/enums/ResponseResultCodeEnum.java

@@ -21,8 +21,11 @@ public enum ResponseResultCodeEnum {
     TIMESTAMP_ERR(1001, "timestamp错误"),
     APP_ID_ERR(1002, "appId无效"),
     SIGN_ERR(1003, "签名验证失败"),
-
-
+    SHOP_EXIST(2002, "门店名称已存在"),
+    SHOP_CATEGORY_NOT_EXIST(2003, "门店分类不存在"),
+    SHOP_DELIVERY_NOT_FOUND(2004, "运力id不能为空"),
+    MERCHANT_DISABLE(2005, "该商家已禁用"),
+    MERCHANT_IS_AUDIT(2006, "请等待商家通过认证"),
     // 门店、订单类状态码
     SHOP_NOT_EXIST(2001, "门店不存在"),
 

+ 1 - 25
lb-gateway/src/main/java/com/ydd/gateway/filter/AuthorizeGatewayFilterFactory.java

@@ -69,8 +69,7 @@ public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<
 
     // url白名单
     public static final String URL = "/doc.html/**";
-//    @Value("${waimai.meituan.developerId}")
-//    public String aa ;
+
     @Override
     public GatewayFilter apply(AuthorizeGatewayFilterFactory.Config config) {
         return (exchange, chain) -> {
@@ -93,12 +92,7 @@ public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<
 //			}
             HttpHeaders headers = request.getHeaders();
             String method = request.getMethodValue();
-          //  String contentType = request.getHeaders().getFirst("Content-Type");
             MediaType contentType = headers.getContentType();
-//            GatewayContext gatewayContext = exchange.getAttribute(GatewayContext.CACHE_GATEWAY_CONTEXT);
-//            System.out.println(gatewayContext.getCacheBody());
-//            System.out.println(gatewayContext.getFormData().toSingleValueMap());
-//            System.out.println(gatewayContext.getAllRequestData().toSingleValueMap());
             if ("POST".equals(method)&&MediaType.APPLICATION_JSON.equals(contentType)){
                 AtomicReference<String> requestBody = new AtomicReference<>("");
                 RecorderServerHttpRequestDecorator requestDecorator = new RecorderServerHttpRequestDecorator(request);
@@ -168,22 +162,4 @@ public class AuthorizeGatewayFilterFactory extends AbstractGatewayFilterFactory<
 
     }
 
-    public void logInfo(ServerHttpRequest request, HttpHeaders headers) {
-
-        String remoteIP = headers.getFirst("x-real-ip");
-        if (!StringUtils.hasText(remoteIP)) {
-            remoteIP = request.getRemoteAddress().getHostName();
-        }
-        String method = request.getMethodValue();
-        String reqParams = JSON.toJSONString(request.getQueryParams(), SerializerFeature.DisableCircularReferenceDetect,
-                SerializerFeature.WriteMapNullValue);
-        String path = request.getPath().pathWithinApplication().value();
-        logger.info("请求方的IP:" + remoteIP);
-        logger.info("请求的接口:" + path);
-        logger.info("请求的类型:" + method);
-        logger.info("请求的参数:" + reqParams);
-
-    }
-
-
 }

+ 0 - 105
lb-gateway/src/main/java/com/ydd/gateway/filter/CacheRequestFilter.java

@@ -1,105 +0,0 @@
-//package com.ydd.gateway.filter;
-//
-//import java.util.Collections;
-//import java.util.List;
-//import org.springframework.cloud.gateway.filter.GatewayFilter;
-//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
-//import org.springframework.cloud.gateway.filter.OrderedGatewayFilter;
-//import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
-//import org.springframework.core.io.buffer.DataBuffer;
-//import org.springframework.core.io.buffer.DataBufferFactory;
-//import org.springframework.core.io.buffer.DataBufferUtils;
-//import org.springframework.http.HttpMethod;
-//import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
-//import org.springframework.stereotype.Component;
-//import org.springframework.web.server.ServerWebExchange;
-//import reactor.core.publisher.Flux;
-//import reactor.core.publisher.Mono;
-//
-///**
-// * 获取body请求数据(解决流不能重复读取问题)
-// *
-// * @author ruoyi
-// */
-////@Component
-//public class CacheRequestFilter extends AbstractGatewayFilterFactory<CacheRequestFilter.Config>
-//{
-//    public CacheRequestFilter()
-//    {
-//        super(Config.class);
-//    }
-//
-//    @Override
-//    public String name()
-//    {
-//        return "CacheRequestFilter";
-//    }
-//
-//    @Override
-//    public GatewayFilter apply(Config config)
-//    {
-//        CacheRequestGatewayFilter cacheRequestGatewayFilter = new CacheRequestGatewayFilter();
-//        Integer order = config.getOrder();
-//        if (order == null)
-//        {
-//            return cacheRequestGatewayFilter;
-//        }
-//        return new OrderedGatewayFilter(cacheRequestGatewayFilter, order);
-//    }
-//
-//    public static class CacheRequestGatewayFilter implements GatewayFilter
-//    {
-//        @Override
-//        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain)
-//        {
-//            // GET DELETE 不过滤
-//            HttpMethod method = exchange.getRequest().getMethod();
-//            if (method == null || method.matches("GET") || method.matches("DELETE"))
-//            {
-//                return chain.filter(exchange);
-//            }
-//            return DataBufferUtils.join(exchange.getRequest().getBody()).map(dataBuffer -> {
-//                byte[] bytes = new byte[dataBuffer.readableByteCount()];
-//                dataBuffer.read(bytes);
-//                DataBufferUtils.release(dataBuffer);
-//                return bytes;
-//            }).defaultIfEmpty(new byte[0]).flatMap(bytes -> {
-//                DataBufferFactory dataBufferFactory = exchange.getResponse().bufferFactory();
-//                ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(exchange.getRequest())
-//                {
-//                    @Override
-//                    public Flux<DataBuffer> getBody()
-//                    {
-//                        if (bytes.length > 0)
-//                        {
-//                            return Flux.just(dataBufferFactory.wrap(bytes));
-//                        }
-//                        return Flux.empty();
-//                    }
-//                };
-//                return chain.filter(exchange.mutate().request(decorator).build());
-//            });
-//        }
-//    }
-//
-//    @Override
-//    public List<String> shortcutFieldOrder()
-//    {
-//        return Collections.singletonList("order");
-//    }
-//
-//    static class Config
-//    {
-//        private Integer order;
-//
-//        public Integer getOrder()
-//        {
-//            return order;
-//        }
-//
-//        public void setOrder(Integer order)
-//        {
-//            this.order = order;
-//        }
-//    }
-//}

+ 0 - 210
lb-gateway/src/main/java/com/ydd/gateway/filter/GatewayContextFilter.java

@@ -1,210 +0,0 @@
-//package com.ydd.gateway.filter;
-//import com.ydd.gateway.service.GatewayContext;
-//import io.netty.buffer.ByteBufAllocator;
-//import lombok.extern.slf4j.Slf4j;
-//import org.springframework.cloud.gateway.filter.GatewayFilterChain;
-//import org.springframework.cloud.gateway.filter.GlobalFilter;
-//import org.springframework.core.Ordered;
-//import org.springframework.core.io.ByteArrayResource;
-//import org.springframework.core.io.buffer.DataBuffer;
-//import org.springframework.core.io.buffer.DataBufferUtils;
-//import org.springframework.core.io.buffer.NettyDataBufferFactory;
-//import org.springframework.http.HttpHeaders;
-//import org.springframework.http.MediaType;
-//import org.springframework.http.codec.HttpMessageReader;
-//import org.springframework.http.server.reactive.ServerHttpRequest;
-//import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
-//import org.springframework.stereotype.Component;
-//import org.springframework.util.MultiValueMap;
-//import org.springframework.web.reactive.function.server.HandlerStrategies;
-//import org.springframework.web.reactive.function.server.ServerRequest;
-//import org.springframework.web.server.ServerWebExchange;
-//import reactor.core.publisher.Flux;
-//import reactor.core.publisher.Mono;
-//
-//import java.io.UnsupportedEncodingException;
-//import java.net.URLEncoder;
-//import java.nio.charset.Charset;
-//import java.nio.charset.StandardCharsets;
-//import java.util.List;
-//import java.util.Map;
-//
-//@Slf4j
-////@Component
-//public class GatewayContextFilter implements GlobalFilter, Ordered {
-//
-//    /**
-//     * default HttpMessageReader
-//     */
-//    private static final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
-//
-//    @Override
-//    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
-//        /**
-//         * save request path and serviceId into gateway context
-//         */
-//        ServerHttpRequest request = exchange.getRequest();
-//        String path = request.getPath().pathWithinApplication().value();
-//        GatewayContext gatewayContext = new GatewayContext();
-//        gatewayContext.getAllRequestData().addAll(request.getQueryParams());
-//        gatewayContext.setPath(path);
-//        /**
-//         * save gateway context into exchange
-//         */
-//        HttpHeaders headers = request.getHeaders();
-//        MediaType contentType = headers.getContentType();
-//        long contentLength = headers.getContentLength();
-//        if(contentLength>0){
-//            if(MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)){
-//                return readBody(exchange, chain,gatewayContext);
-//            }
-//            if(MediaType.APPLICATION_FORM_URLENCODED.equals(contentType)){
-//                return readFormData(exchange, chain,gatewayContext);
-//            }
-//        }
-//        log.debug("[GatewayContext]ContentType:{},Gateway context is set with {}",contentType, gatewayContext);
-//        return chain.filter(exchange);
-//
-//    }
-//
-//
-//
-//    /**
-//     * ReadFormData
-//     * @param exchange
-//     * @param chain
-//     * @return
-//     */
-//    private Mono<Void> readFormData(ServerWebExchange exchange,GatewayFilterChain chain,GatewayContext gatewayContext){
-//        HttpHeaders headers = exchange.getRequest().getHeaders();
-//        return exchange.getFormData()
-//                .doOnNext(multiValueMap -> {
-//                    gatewayContext.setFormData(multiValueMap);
-//                    exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
-//                    log.debug("[GatewayContext]Read FormData:{}",multiValueMap);
-//                })
-//                .then(Mono.defer(() -> {
-//                    Charset charset = headers.getContentType().getCharset();
-//                    charset = charset == null? StandardCharsets.UTF_8:charset;
-//                    String charsetName = charset.name();
-//                    MultiValueMap<String, String> formData = gatewayContext.getFormData();
-//                    /**
-//                     * formData is empty just return
-//                     */
-//                    if(null == formData || formData.isEmpty()){
-//                        return chain.filter(exchange);
-//                    }
-//                    StringBuilder formDataBodyBuilder = new StringBuilder();
-//                    String entryKey;
-//                    List<String> entryValue;
-//                    try {
-//                        /**
-//                         * repackage form data
-//                         */
-//                        for (Map.Entry<String, List<String>> entry : formData.entrySet()) {
-//                            entryKey = entry.getKey();
-//                            entryValue = entry.getValue();
-//                            if (entryValue.size() > 1) {
-//                                for(String value : entryValue){
-//                                    formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(value, charsetName)).append("&");
-//                                }
-//                            } else {
-//                                formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(entryValue.get(0), charsetName)).append("&");
-//                            }
-//                        }
-//                    }catch (UnsupportedEncodingException e){
-//                        //ignore URLEncode Exception
-//                    }
-//                    /**
-//                     * substring with the last char '&'
-//                     */
-//                    String formDataBodyString = "";
-//                    if(formDataBodyBuilder.length()>0){
-//                        formDataBodyString = formDataBodyBuilder.substring(0, formDataBodyBuilder.length() - 1);
-//                    }
-//                    /**
-//                     * get data bytes
-//                     */
-//                    byte[] bodyBytes =  formDataBodyString.getBytes(charset);
-//                    int contentLength = bodyBytes.length;
-//                    ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(
-//                            exchange.getRequest()) {
-//                        /**
-//                         * change content-length
-//                         * @return
-//                         */
-//                        @Override
-//                        public HttpHeaders getHeaders() {
-//                            HttpHeaders httpHeaders = new HttpHeaders();
-//                            httpHeaders.putAll(super.getHeaders());
-//                            if (contentLength > 0) {
-//                                httpHeaders.setContentLength(contentLength);
-//                            } else {
-//                                httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
-//                            }
-//                            return httpHeaders;
-//                        }
-//
-//                        /**
-//                         * read bytes to Flux<Databuffer>
-//                         * @return
-//                         */
-//                        @Override
-//                        public Flux<DataBuffer> getBody() {
-//                            return DataBufferUtils.read(new ByteArrayResource(bodyBytes),new NettyDataBufferFactory(ByteBufAllocator.DEFAULT),contentLength);
-//                        }
-//                    };
-//                    ServerWebExchange mutateExchange = exchange.mutate().request(decorator).build();
-//                  //  log.debug("[GatewayContext]Rewrite Form Data :{}",formDataBodyString);
-//                    return chain.filter(mutateExchange);
-//                }));
-//    }
-//
-//    /**
-//     * ReadJsonBody
-//     * @param exchange
-//     * @param chain
-//     * @return
-//     */
-//    private Mono<Void> readBody(ServerWebExchange exchange,GatewayFilterChain chain,GatewayContext gatewayContext){
-//        /**
-//         * join the body
-//         */
-//        return DataBufferUtils.join(exchange.getRequest().getBody())
-//                .flatMap(dataBuffer -> {
-//                    /**
-//                     * read the body Flux<Databuffer>
-//                     */
-//                    DataBufferUtils.retain(dataBuffer);
-//                    Flux<DataBuffer> cachedFlux = Flux.defer(() -> Flux.just(dataBuffer.slice(0, dataBuffer.readableByteCount())));
-//                    /**
-//                     * repackage ServerHttpRequest
-//                     */
-//                    ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
-//                        @Override
-//                        public Flux<DataBuffer> getBody() {
-//                            return cachedFlux;
-//                        }
-//                    };
-//                    /**
-//                     * mutate exchage with new ServerHttpRequest
-//                     */
-//                    ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
-//                    /**
-//                     * read body string with default messageReaders
-//                     */
-//                    return ServerRequest.create(mutatedExchange, messageReaders)
-//                            .bodyToMono(String.class)
-//                            .doOnNext(objectValue -> {
-//                                gatewayContext.setCacheBody(objectValue);
-//                                exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
-//                                log.debug("[GatewayContext]Read JsonBody:{}",objectValue);
-//                            }).then(chain.filter(mutatedExchange));
-//                });
-//    }
-//
-//    @Override
-//    public int getOrder() {
-//        return HIGHEST_PRECEDENCE;
-//    }
-//}

+ 0 - 199
lb-gateway/src/main/java/com/ydd/gateway/filter/RequestParamGlobalFilter.java

@@ -1,199 +0,0 @@
-package com.ydd.gateway.filter;
-
-import com.ydd.gateway.service.GatewayContext;
-import io.netty.buffer.ByteBufAllocator;
-import org.springframework.cloud.gateway.filter.GatewayFilterChain;
-import org.springframework.cloud.gateway.filter.GlobalFilter;
-import org.springframework.core.Ordered;
-import org.springframework.core.io.ByteArrayResource;
-import org.springframework.core.io.buffer.DataBuffer;
-import org.springframework.core.io.buffer.DataBufferUtils;
-import org.springframework.core.io.buffer.NettyDataBufferFactory;
-import org.springframework.http.HttpHeaders;
-import org.springframework.http.MediaType;
-import org.springframework.http.codec.HttpMessageReader;
-import org.springframework.http.server.reactive.ServerHttpRequest;
-import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
-import org.springframework.stereotype.Component;
-import org.springframework.util.MultiValueMap;
-import org.springframework.web.reactive.function.server.HandlerStrategies;
-import org.springframework.web.reactive.function.server.ServerRequest;
-import org.springframework.web.server.ServerWebExchange;
-import reactor.core.publisher.Flux;
-import reactor.core.publisher.Mono;
-
-import java.io.UnsupportedEncodingException;
-import java.net.URLEncoder;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.List;
-import java.util.Map;
-
-/**
- * @author wangtao
- * @date 2022/4/1
- */
-@Component
-public class RequestParamGlobalFilter implements GlobalFilter, Ordered {
-
-    @Override
-    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
-
-        /**
-         * save request path and serviceId into gateway context
-         */
-        ServerHttpRequest request = exchange.getRequest();
-        HttpHeaders headers = request.getHeaders();
-
-        // 处理参数
-        MediaType contentType = headers.getContentType();
-        long contentLength = headers.getContentLength();
-
-        if (contentLength > 0) {
-            if (MediaType.APPLICATION_JSON.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)) {
-                return readBody(exchange, chain);
-            }
-            if (MediaType.APPLICATION_FORM_URLENCODED.equals(contentType) || MediaType.APPLICATION_JSON_UTF8.equals(contentType)) {
-                GatewayContext gatewayContext = new GatewayContext();
-                return readFormData(exchange, chain,gatewayContext);
-            }
-        }
-
-        return chain.filter(exchange);
-    }
-
-
-    /**
-     * default HttpMessageReader
-     */
-    private static final List<HttpMessageReader<?>> messageReaders = HandlerStrategies.withDefaults().messageReaders();
-    /**
-     * ReadJsonBody
-     *
-     * @param exchange
-     * @param chain
-     * @return
-     */
-    private Mono<Void> readBody(ServerWebExchange exchange, GatewayFilterChain chain) {
-        /**
-         * join the body
-         */
-        return DataBufferUtils.join(exchange.getRequest().getBody()).flatMap(dataBuffer -> {
-            byte[] bytes = new byte[dataBuffer.readableByteCount()];
-            dataBuffer.read(bytes);
-            DataBufferUtils.release(dataBuffer);
-            Flux<DataBuffer> cachedFlux = Flux.defer(() -> {
-                DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
-                DataBufferUtils.retain(buffer);
-                return Mono.just(buffer);
-            });
-            /**
-             * repackage ServerHttpRequest
-             */
-            ServerHttpRequest mutatedRequest = new ServerHttpRequestDecorator(exchange.getRequest()) {
-                @Override
-                public Flux<DataBuffer> getBody() {
-                    return cachedFlux;
-                }
-            };
-            /**
-             * mutate exchage with new ServerHttpRequest
-             */
-            ServerWebExchange mutatedExchange = exchange.mutate().request(mutatedRequest).build();
-            /**
-             * read body string with default messageReaders
-             */
-            return ServerRequest.create(mutatedExchange, messageReaders).bodyToMono(String.class)
-                    .doOnNext(objectValue -> {
-//                        log.debug("[GatewayContext]Read JsonBody:{}", objectValue);
-                    }).then(chain.filter(mutatedExchange));
-        });
-    }
-
-    private Mono<Void> readFormData(ServerWebExchange exchange, GatewayFilterChain chain, GatewayContext gatewayContext){
-        HttpHeaders headers = exchange.getRequest().getHeaders();
-        exchange.getAttributes().put(GatewayContext.CACHE_GATEWAY_CONTEXT,gatewayContext);
-        return exchange.getFormData()
-                .doOnNext(multiValueMap -> {
-                    gatewayContext.setFormData(multiValueMap);
-                })
-                .then(Mono.defer(() -> {
-                    Charset charset = headers.getContentType().getCharset();
-                    charset = charset == null? StandardCharsets.UTF_8:charset;
-                    String charsetName = charset.name();
-                    MultiValueMap<String, String> formData = gatewayContext.getFormData();
-                    /**
-                     * formData is empty just return
-                     */
-                    if(null == formData || formData.isEmpty()){
-                        return chain.filter(exchange);
-                    }
-                    StringBuilder formDataBodyBuilder = new StringBuilder();
-                    String entryKey;
-                    List<String> entryValue;
-                    try {
-                        /**
-                         * repackage form data
-                         */
-                        for (Map.Entry<String, List<String>> entry : formData.entrySet()) {
-                            entryKey = entry.getKey();
-                            entryValue = entry.getValue();
-                            if (entryValue.size() > 1) {
-                                for(String value : entryValue){
-                                    formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(value, charsetName)).append("&");
-                                }
-                            } else {
-                                formDataBodyBuilder.append(entryKey).append("=").append(URLEncoder.encode(entryValue.get(0), charsetName)).append("&");
-                            }
-                        }
-                    }catch (UnsupportedEncodingException e){
-                        //ignore URLEncode Exception
-                    }
-                    /**
-                     * substring with the last char '&'
-                     */
-                    String formDataBodyString = "";
-                    if(formDataBodyBuilder.length()>0){
-                        formDataBodyString = formDataBodyBuilder.substring(0, formDataBodyBuilder.length() - 1);
-                    }
-                    /**
-                     * get data bytes
-                     */
-                    byte[] bodyBytes =  formDataBodyString.getBytes(charset);
-                    int contentLength = bodyBytes.length;
-                    ServerHttpRequestDecorator decorator = new ServerHttpRequestDecorator(
-                            exchange.getRequest()) {
-                        /**
-                         * change content-length
-                         * @return
-                         */
-                        @Override
-                        public HttpHeaders getHeaders() {
-                            HttpHeaders httpHeaders = new HttpHeaders();
-                            httpHeaders.putAll(super.getHeaders());
-                            if (contentLength > 0) {
-                                httpHeaders.setContentLength(contentLength);
-                            } else {
-                                httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
-                            }
-                            return httpHeaders;
-                        }
-
-                        /**
-                         * read bytes to Flux<Databuffer>
-                         * @return
-                         */
-                        @Override
-                        public Flux<DataBuffer> getBody() {
-                            return DataBufferUtils.read(new ByteArrayResource(bodyBytes),new NettyDataBufferFactory(ByteBufAllocator.DEFAULT),contentLength);
-                        }
-                    };
-                    ServerWebExchange mutateExchange = exchange.mutate().request(decorator).build();
-                    return chain.filter(mutateExchange);
-                }));
-    }
-    @Override
-    public int getOrder() {
-        return HIGHEST_PRECEDENCE;
-    }
-}