From 0fea955db9776dca6c6a7361fc511aa9a657f082 Mon Sep 17 00:00:00 2001 From: tanghc Date: Tue, 28 Jul 2020 18:21:01 +0800 Subject: [PATCH] 4.0 --- .gitignore | 1 + changelog.md | 13 + doc/docs/_sidebar.md | 69 ++-- doc/docs/files/10010_快速体验.md | 17 - doc/docs/files/10020_新增接口.md | 107 ++----- doc/docs/files/10030_业务参数校验.md | 3 +- doc/docs/files/10041_编写文档.md | 2 +- doc/docs/files/10070_easyopen支持.md | 78 ----- doc/docs/files/10089_自定义校验token.md | 15 +- doc/docs/files/10090_路由授权.md | 4 +- .../files/10096_使用SpringCloudGateway.md | 16 - doc/docs/files/10100_提供restful接口.md | 24 +- doc/docs/files/10104_文件上传.md | 6 +- doc/docs/files/10112_使用eureka.md | 4 +- doc/docs/files/10113_扩展其它注册中心.md | 86 ----- doc/docs/files/90010_原理分析之@ApiMapping.md | 21 -- doc/docs/files/90099_2.x升3.x注意事项.md | 23 -- doc/docs/files/90100_常见问题.md | 4 +- pom.xml | 2 +- sop-admin/sop-admin-server/pom.xml | 5 +- sop-admin/sop-admin-server/readme.md | 11 +- .../sop/adminserver/api/system/SystemApi.java | 2 +- .../sop/adminserver/bean/ServiceInfo.java | 19 +- .../resources/META-INF/sop-admin.properties | 10 +- .../main/resources/application-dev.properties | 4 +- .../gitee/sop/adminserver/AccountTest.java | 23 ++ .../sopauth/controller/OAuth2Controller.java | 5 +- .../main/resources/application-dev.properties | 4 +- sop-common/pom.xml | 4 +- sop-common/readme.md | 4 +- .../pom.xml | 10 +- .../bridge/SopRegisterAutoConfiguration.java | 31 ++ .../bridge}/route/EurekaRegistryListener.java | 5 +- .../pom.xml | 16 +- .../bridge/SopRegisterAutoConfiguration.java | 46 +++ .../bridge}/route/NacosRegistryListener.java | 4 +- .../sop/bridge}/route/NacosServiceHolder.java | 5 +- .../src/main/resources/sop-bridge.properties | 2 +- .../bridge/SopGatewayAutoConfiguration.java | 24 -- sop-common/sop-gateway-common/pom.xml | 12 +- .../sop/gatewaycommon/bean/ApiConfig.java | 19 -- .../sop/gatewaycommon/bean/SopConstants.java | 1 + .../AbstractConfiguration.java | 60 +--- .../config}/SopGatewayAutoConfiguration.java | 3 +- .../SopGatewayEnvironmentPostProcessor.java | 2 +- .../easyopen/EasyopenResultExecutor.java | 44 --- .../easyopen/EasyopenSigner.java | 33 -- .../easyopen/EasyopenZuulConfiguration.java | 38 --- .../gateway/ServerWebExchangeUtil.java | 9 +- .../BaseGatewayConfiguration.java | 2 +- .../GatewayModifyResponseGatewayFilter.java | 5 + .../gateway/filter/IndexFilter.java | 14 +- .../gateway/filter/LimitFilter.java | 7 + .../gateway/result/GatewayResultExecutor.java | 2 +- .../loadbalancer/ServiceGrayConfig.java | 2 +- .../loadbalancer/SopPropertiesFactory.java | 27 -- .../manager/DefaultEnvGrayManager.java | 6 +- .../gatewaycommon/manager/EnvGrayManager.java | 2 +- .../manager/EnvironmentKeys.java | 17 +- .../result/ResultExecutorForZuul.java | 9 - .../route/ServiceRouteListener.java | 7 +- .../sop/gatewaycommon/util/RequestUtil.java | 27 -- .../zuul/RequestContextUtil.java | 37 --- .../gatewaycommon/zuul/ValidateService.java | 97 ------ .../sop/gatewaycommon/zuul/ZuulContext.java | 137 -------- .../AlipayZuulConfiguration.java | 16 - .../configuration/BaseZuulConfiguration.java | 176 ----------- .../TaobaoZuulConfiguration.java | 23 -- .../WebappZuulConfiguration.java | 18 -- .../controller/ConfigChannelController.java | 68 ---- .../zuul/controller/ErrorLogController.java | 23 -- .../zuul/controller/ZuulErrorController.java | 53 ---- .../zuul/controller/ZuulIndexController.java | 84 ----- .../controller/ZuulMonitorController.java | 21 -- .../zuul/filter/BaseZuulFilter.java | 130 -------- .../zuul/filter/ErrorFilter.java | 60 ---- .../zuul/filter/FormBodyWrapperFilterExt.java | 14 - .../zuul/filter/PostResultFilter.java | 75 ----- .../zuul/filter/PreEnvGrayFilter.java | 53 ---- .../PreHttpServletRequestWrapperFilter.java | 31 -- .../zuul/filter/PreLimitFilter.java | 118 ------- .../filter/PreParameterFormatterFilter.java | 42 --- .../zuul/filter/PreValidateFilter.java | 30 -- .../filter/Servlet30WrapperFilterExt.java | 14 - .../EnvironmentServerChooser.java | 55 ---- .../ZuulLoadBalanceServerChooser.java | 24 -- .../zuul/param/ZuulParamBuilder.java | 67 ---- .../zuul/param/ZuulParameterUtil.java | 141 --------- .../zuul/result/ZuulResultExecutor.java | 115 ------- .../zuul/route/SopRouteLocator.java | 63 ---- .../zuul/route/ZuulForwardChooser.java | 18 -- .../zuul/route/ZuulRouteCache.java | 34 -- .../zuul/route/ZuulRouteRepository.java | 98 ------ .../zuul/route/ZuulTargetRoute.java | 18 -- .../src/main/resources/sop-bridge.properties | 39 +++ .../servercommon/annotation/ApiMapping.java | 92 ------ .../annotation/{ApiAbility.java => Open.java} | 16 +- .../sop/servercommon/bean/OpenContext.java | 108 ------- .../servercommon/bean/OpenContextImpl.java | 124 -------- .../sop/servercommon/bean/ServiceApiInfo.java | 4 - .../sop/servercommon/bean/ServiceConfig.java | 4 - .../sop/servercommon/bean/ServiceContext.java | 12 - .../BaseServiceConfiguration.java | 120 +------ .../EasyopenDocSupportController.java | 58 ---- .../configuration/GlobalExceptionHandler.java | 5 +- .../configuration/ServiceConfiguration.java | 94 ++++++ .../SpringMvcServiceConfiguration.java | 90 ------ .../TaobaoServiceConfiguration.java | 9 - .../WebappServiceConfiguration.java | 16 - .../easyopen/EasyopenApiMetaBuilder.java | 91 ------ .../EasyopenServiceConfiguration.java | 24 -- .../EasyopenServiceRouteController.java | 27 -- .../ServiceContextInterceptor.java | 24 -- .../servercommon/manager/ApiMetaBuilder.java | 146 --------- .../servercommon/manager/ApiMetaManager.java | 14 - .../manager/DefaultRequestMappingEvent.java | 29 -- .../manager/EnvironmentContext.java | 23 -- .../servercommon/manager/EnvironmentKeys.java | 42 --- .../manager/RequestMappingEvent.java | 14 - .../mapping/ApiMappingHandlerMapping.java | 100 ------ .../servercommon/mapping/ApiMappingInfo.java | 23 -- .../mapping/ApiMappingRequestCondition.java | 74 ----- .../ApiMappingStringValueResolver.java | 19 -- .../ApiMappingStringValueResolverMVC.java | 14 - .../ApiMappingStringValueResolverVersion.java | 25 -- .../sop/servercommon/mapping/RouteUtil.java | 23 -- .../param/ApiArgumentResolver.java | 81 ++--- .../servercommon/route/ApiMetaBuilder.java | 93 ++++++ .../ServiceRouteController.java | 10 +- .../ServiceRouteInfoBuilder.java | 7 +- .../DocumentationPluginsManagerExt.java | 22 +- .../swagger/SwaggerValidator.java | 5 +- .../gitee/sop/servercommon/util/OpenUtil.java | 49 +-- sop-example/sop-springmvc/pom.xml | 1 + .../gitee/app/config/OpenServiceConfig.java | 10 +- .../gitee/app/controller/HomeController.java | 5 +- sop-example/sop-story/pom.xml | 7 +- .../storyweb/config/OpenServiceConfig.java | 11 +- .../storyweb/controller/AlipayController.java | 297 ------------------ .../controller/AlipayController2.java | 32 -- .../controller/DemoOrderController.java | 74 ----- .../Example1001_BaseController.java | 133 ++++++++ ... => Example1002_FileUploadController.java} | 18 +- ...va => Example1003_DownloadController.java} | 9 +- ...java => Example1004_JSR303Controller.java} | 8 +- ... => Example1005_PermissionController.java} | 10 +- ...Example1005_ThrowExceptionController.java} | 10 +- ....java => Example1007_TokenController.java} | 18 +- ...ava => Example1008_RestfulController.java} | 2 +- .../controller/PostJsonController.java | 41 --- .../main/resources/application-dev.properties | 4 +- sop-gateway/pom.xml | 26 +- .../sop/gateway/manager/DbEnvGrayManager.java | 2 +- .../resources/META-INF/gateway.properties | 35 +++ .../main/resources/META-INF/spring.factories | 3 +- .../main/resources/application-dev.properties | 5 +- .../com/gitee/sop/gateway}/ExcludeTest.java | 2 +- .../gitee/sop/gateway}/RoundRobinTest.java | 2 +- .../gitee/sop/test/AlipayClientPostTest.java | 2 +- .../java/com/gitee/sop/test/AllInOneTest.java | 147 ++------- .../sop/test/PermissionDemoPostTest.java | 2 +- sop-website/pom.xml | 12 +- .../websiteserver/config/WebsiteConfig.java | 18 -- .../main/resources/META-INF/spring.factories | 2 + .../main/resources/application-dev.properties | 8 +- 165 files changed, 918 insertions(+), 4838 deletions(-) delete mode 100644 doc/docs/files/10070_easyopen支持.md delete mode 100644 doc/docs/files/10096_使用SpringCloudGateway.md delete mode 100644 doc/docs/files/10113_扩展其它注册中心.md delete mode 100644 doc/docs/files/90010_原理分析之@ApiMapping.md delete mode 100644 doc/docs/files/90099_2.x升3.x注意事项.md create mode 100644 sop-admin/sop-admin-server/src/test/java/com/gitee/sop/adminserver/AccountTest.java rename sop-common/{sop-bridge-zuul => sop-bridge-eureka}/pom.xml (78%) create mode 100644 sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java rename sop-common/{sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon => sop-bridge-eureka/src/main/java/com/gitee/sop/bridge}/route/EurekaRegistryListener.java (96%) rename sop-common/{sop-bridge-gateway => sop-bridge-nacos}/pom.xml (65%) create mode 100644 sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java rename sop-common/{sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon => sop-bridge-nacos/src/main/java/com/gitee/sop/bridge}/route/NacosRegistryListener.java (97%) rename sop-common/{sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon => sop-bridge-nacos/src/main/java/com/gitee/sop/bridge}/route/NacosServiceHolder.java (75%) rename sop-common/{sop-bridge-gateway => sop-bridge-nacos}/src/main/resources/sop-bridge.properties (95%) delete mode 100644 sop-common/sop-bridge-zuul/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java rename sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/{manager => config}/AbstractConfiguration.java (82%) rename sop-common/{sop-bridge-gateway/src/main/java/com/gitee/sop/bridge => sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config}/SopGatewayAutoConfiguration.java (85%) delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenResultExecutor.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenSigner.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenZuulConfiguration.java rename sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/{zuul => }/loadbalancer/ServiceGrayConfig.java (91%) delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/SopPropertiesFactory.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/result/ResultExecutorForZuul.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/RequestContextUtil.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ValidateService.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ZuulContext.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/AlipayZuulConfiguration.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/BaseZuulConfiguration.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/TaobaoZuulConfiguration.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/WebappZuulConfiguration.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ConfigChannelController.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ErrorLogController.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulErrorController.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulIndexController.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulMonitorController.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/BaseZuulFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/ErrorFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/FormBodyWrapperFilterExt.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PostResultFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreEnvGrayFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreHttpServletRequestWrapperFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreLimitFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreParameterFormatterFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreValidateFilter.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/Servlet30WrapperFilterExt.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/EnvironmentServerChooser.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ZuulLoadBalanceServerChooser.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParamBuilder.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParameterUtil.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/result/ZuulResultExecutor.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/SopRouteLocator.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulForwardChooser.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteCache.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteRepository.java delete mode 100644 sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulTargetRoute.java create mode 100644 sop-common/sop-gateway-common/src/main/resources/sop-bridge.properties delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiMapping.java rename sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/{ApiAbility.java => Open.java} (73%) delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContext.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContextImpl.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/EasyopenDocSupportController.java create mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/ServiceConfiguration.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/SpringMvcServiceConfiguration.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/TaobaoServiceConfiguration.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/WebappServiceConfiguration.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenApiMetaBuilder.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceConfiguration.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceRouteController.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaBuilder.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaManager.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/DefaultRequestMappingEvent.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentContext.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentKeys.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/RequestMappingEvent.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingHandlerMapping.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingInfo.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingRequestCondition.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolver.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverMVC.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverVersion.java delete mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/RouteUtil.java create mode 100644 sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ApiMetaBuilder.java rename sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/{manager => route}/ServiceRouteController.java (82%) rename sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/{manager => route}/ServiceRouteInfoBuilder.java (94%) delete mode 100644 sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController.java delete mode 100644 sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController2.java delete mode 100644 sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DemoOrderController.java create mode 100644 sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1001_BaseController.java rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{FileUploadDemoController.java => Example1002_FileUploadController.java} (90%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{DownloadController.java => Example1003_DownloadController.java} (77%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{JSR303DemoController.java => Example1004_JSR303Controller.java} (67%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{PermissionDemoController.java => Example1005_PermissionController.java} (60%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{ThrowExceptionDemoController.java => Example1005_ThrowExceptionController.java} (82%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{TokenController.java => Example1007_TokenController.java} (52%) rename sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/{TraditionalWebappController.java => Example1008_RestfulController.java} (98%) delete mode 100644 sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PostJsonController.java create mode 100644 sop-gateway/src/main/resources/META-INF/gateway.properties rename {sop-common/sop-gateway-common/src/test/java/com/gitee/sop/gatewaycommon => sop-gateway/src/test/java/com/gitee/sop/gateway}/ExcludeTest.java (94%) rename {sop-common/sop-gateway-common/src/test/java/com/gitee/sop/gatewaycommon => sop-gateway/src/test/java/com/gitee/sop/gateway}/RoundRobinTest.java (98%) create mode 100644 sop-website/src/main/resources/META-INF/spring.factories diff --git a/.gitignore b/.gitignore index d6dc1877..1739d49e 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,7 @@ *.iws *.iml *.ipr +*.png ### NetBeans ### /nbproject/private/ diff --git a/changelog.md b/changelog.md index 03f668dd..6b148f00 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,18 @@ # changelog +## 4.0.0(不兼容3.x) + +- 新增@Open注解,代替ApiMapping和ApiAbility +- service接入减少代码入侵 +- 修复admin密码存储规则 + +### 不兼容部分 + +- 移除ApiMapping和ApiAbility,改为Open注解 +- 移除OpenContext +- 移除zuul +- 移除对easyopen支持 + ## 3.2.1 - 强化RouteInterceptorContext,可获取微服务信息 diff --git a/doc/docs/_sidebar.md b/doc/docs/_sidebar.md index d510aa50..88780f43 100644 --- a/doc/docs/_sidebar.md +++ b/doc/docs/_sidebar.md @@ -1,39 +1,34 @@ -* [首页](/?t=1595832340981) +* [首页](/?t=1595931646391) * 开发文档 - * [快速体验](files/10010_快速体验.md?t=1595832340983) - * [项目接入到SOP](files/10011_项目接入到SOP.md?t=1595832341000) - * [新增接口](files/10020_新增接口.md?t=1595832341000) - * [开发流程](files/10021_开发流程.md?t=1595832341001) - * [业务参数校验](files/10030_业务参数校验.md?t=1595832341001) - * [错误处理](files/10040_错误处理.md?t=1595832341001) - * [编写文档](files/10041_编写文档.md?t=1595832341001) - * [接口交互详解](files/10050_接口交互详解.md?t=1595832341001) - * [easyopen支持](files/10070_easyopen支持.md?t=1595832341001) - * [使用签名校验工具](files/10080_使用签名校验工具.md?t=1595832341001) - * [ISV管理](files/10085_ISV管理.md?t=1595832341001) - * [自定义返回结果](files/10087_自定义返回结果.md?t=1595832341001) - * [自定义过滤器](files/10088_自定义过滤器.md?t=1595832341001) - * [自定义校验token](files/10089_自定义校验token.md?t=1595832341002) - * [网关拦截器](files/10090_网关拦截器.md?t=1595832341002) - * [路由授权](files/10090_路由授权.md?t=1595832341002) - * [接口限流](files/10092_接口限流.md?t=1595832341002) - * [路由监控](files/10093_路由监控.md?t=1595832341002) - * [SDK开发](files/10095_SDK开发.md?t=1595832341002) - * [使用SpringCloudGateway](files/10096_使用SpringCloudGateway.md?t=1595832341002) - * [应用授权](files/10097_应用授权.md?t=1595832341003) - * [提供restful接口](files/10100_提供restful接口.md?t=1595832341003) - * [文件上传](files/10104_文件上传.md?t=1595832341003) - * [配置Sleuth链路追踪](files/10109_配置Sleuth链路追踪.md?t=1595832341003) - * [预发布灰度发布](files/10110_预发布灰度发布.md?t=1595832341003) - * [动态修改请求参数](files/10111_动态修改请求参数.md?t=1595832341003) - * [使用eureka](files/10112_使用eureka.md?t=1595832341003) - * [扩展其它注册中心](files/10113_扩展其它注册中心.md?t=1595832341003) + * [快速体验](files/10010_快速体验.md?t=1595931646394) + * [项目接入到SOP](files/10011_项目接入到SOP.md?t=1595931646412) + * [新增接口](files/10020_新增接口.md?t=1595931646412) + * [开发流程](files/10021_开发流程.md?t=1595931646412) + * [业务参数校验](files/10030_业务参数校验.md?t=1595931646412) + * [错误处理](files/10040_错误处理.md?t=1595931646412) + * [编写文档](files/10041_编写文档.md?t=1595931646412) + * [接口交互详解](files/10050_接口交互详解.md?t=1595931646412) + * [使用签名校验工具](files/10080_使用签名校验工具.md?t=1595931646413) + * [ISV管理](files/10085_ISV管理.md?t=1595931646413) + * [自定义返回结果](files/10087_自定义返回结果.md?t=1595931646413) + * [自定义过滤器](files/10088_自定义过滤器.md?t=1595931646413) + * [自定义校验token](files/10089_自定义校验token.md?t=1595931646413) + * [网关拦截器](files/10090_网关拦截器.md?t=1595931646413) + * [路由授权](files/10090_路由授权.md?t=1595931646413) + * [接口限流](files/10092_接口限流.md?t=1595931646413) + * [路由监控](files/10093_路由监控.md?t=1595931646413) + * [SDK开发](files/10095_SDK开发.md?t=1595931646413) + * [应用授权](files/10097_应用授权.md?t=1595931646414) + * [提供restful接口](files/10100_提供restful接口.md?t=1595931646414) + * [文件上传](files/10104_文件上传.md?t=1595931646414) + * [配置Sleuth链路追踪](files/10109_配置Sleuth链路追踪.md?t=1595931646414) + * [预发布灰度发布](files/10110_预发布灰度发布.md?t=1595931646414) + * [动态修改请求参数](files/10111_动态修改请求参数.md?t=1595931646414) + * [使用eureka](files/10112_使用eureka.md?t=1595931646414) * 原理分析 - * [网关性能测试](files/90001_网关性能测试.md?t=1595832341004) - * [原理分析之@ApiMapping](files/90010_原理分析之@ApiMapping.md?t=1595832341004) - * [原理分析之如何存储路由](files/90011_原理分析之如何存储路由.md?t=1595832341004) - * [原理分析之如何路由](files/90012_原理分析之如何路由.md?t=1595832341004) - * [原理分析之文档归纳](files/90013_原理分析之文档归纳.md?t=1595832341004) - * [原理分析之预发布灰度发布](files/90014_原理分析之预发布灰度发布.md?t=1595832341004) - * [2.x升3.x注意事项](files/90099_2.x升3.x注意事项.md?t=1595832341004) - * [常见问题](files/90100_常见问题.md?t=1595832341004) + * [网关性能测试](files/90001_网关性能测试.md?t=1595931646414) + * [原理分析之如何存储路由](files/90011_原理分析之如何存储路由.md?t=1595931646415) + * [原理分析之如何路由](files/90012_原理分析之如何路由.md?t=1595931646415) + * [原理分析之文档归纳](files/90013_原理分析之文档归纳.md?t=1595931646415) + * [原理分析之预发布灰度发布](files/90014_原理分析之预发布灰度发布.md?t=1595931646415) + * [常见问题](files/90100_常见问题.md?t=1595931646415) diff --git a/doc/docs/files/10010_快速体验.md b/doc/docs/files/10010_快速体验.md index b27e9ae4..a0f9418d 100644 --- a/doc/docs/files/10010_快速体验.md +++ b/doc/docs/files/10010_快速体验.md @@ -30,20 +30,3 @@ - 修改sop-website下的application-dev.properties相关配置 - 运行WebsiteServerApplication.java - 访问http://localhost:8083 - -## 基本配置 - -在`sop-gateway`下的application-dev.properties配置,各项配置说明如下 - -```properties -# 忽略验证,设置true,则所有接口不会进行签名校验,默认false -sop.api-config.ignore-validate=false -# 是否对结果进行合并,默认true -sop.api-config.merge-result=true -# 显示返回sign,默认true -sop.api-config.show-return-sign=true -# 是否开启限流功能,默认true -sop.api-config.open-limit=true -# 请求超时时间,默认5分钟,即允许在5分钟内重复请求,默认300 -sop.api-config.timeout-seconds=300 -``` \ No newline at end of file diff --git a/doc/docs/files/10020_新增接口.md b/doc/docs/files/10020_新增接口.md index eb2bcaf8..634dd321 100644 --- a/doc/docs/files/10020_新增接口.md +++ b/doc/docs/files/10020_新增接口.md @@ -1,21 +1,29 @@ # 新增接口 -以story服务为例,新增一个获取故事内容接口 +假设要对下面这个接口提供开放能力。 + -- 在controller下新建一个类,StoryDemoController.java -- 加上`@RestController`注解 ```java @RestController public class StoryDemoController { + @RequestMapping("/story/get") + public StoryResult getStory() { + StoryResult result = new StoryResult(); + result.setId(1L); + result.setName("海底小纵队"); + return result; + } } ``` -- 新增一个接口 +只需要在方法上新增一个`@Open`注解,指定接口名即可 ```java -@ApiMapping(value = "story.demo.get") +// 添加一个@Open注解 +@Open("story.demo.get") +@RequestMapping("/story/get") public StoryResult getStory() { StoryResult result = new StoryResult(); result.setId(1L); @@ -24,13 +32,9 @@ public StoryResult getStory() { } ``` -这里的`@ApiMapping`注解作用同`@RequestMapping`注解,可以理解为是它的扩展 - -value就是接口名,对应客户端的`method`参数 +如果要加上版本号,指定`version`参数:`@Open(value = "story.demo.get", version = "2.0")` -如果要加上版本号,指定`version`参数:`@ApiMapping(value = "story.demo.get", version = "2.0")` - -- 重启story服务,这样接口就可以使用了。 +- 重启服务,这样接口就可以使用了。 ## 绑定业务参数 @@ -43,7 +47,8 @@ value就是接口名,对应客户端的`method`参数 其中biz_content部分是我们想要的,在方法上申明一个对象,对应biz_content中的内容即可完成参数绑定,并且对参数进行JSR-303校验。 ```java -@ApiMapping(value = "goods.add") +@Open("goods.add") +@RequestMapping("/goods/add") public Object addGoods(GoodsParam param) { return param; } @@ -58,40 +63,14 @@ public class GoodsParam { 一般情况下,只需要获取业务参数即可,如果想要获取更多的参数,可在后面跟一个`HttpServletRequest`对象。 ```java -@ApiMapping(value = "goods.add") +@Open("goods.add") +@RequestMapping("/goods/add") public Object addGoods(GoodsParam param, HttpServletRequest request) { System.out.println(request.getParameter("method")); return param; } ``` -- 方式2 - -```java -@ApiMapping(value = "story.get", version = "2.2") -public Story getStory22(OpenContext openContext) { - // 业务参数 - Story bizObject = openContext.getBizObject(); - // 获取appid,更多方法查看OpenContext类 - String appId = openContext.getAppId(); - System.out.println(appId); - return bizObject; -} -``` - -另一种方式,OpenContext泛型参数填bizObject类,调用openContext.getBizObject()可直接获得对象 - -此方式等价于: - -```java -@ApiMapping(value = "story.get", version = "2.2") -public Story getStory22(Story bizObject) { - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - String appId = openContext.getAppId(); - System.out.println(appId); - return bizObject; -} -``` ## 接口命名 @@ -122,13 +101,13 @@ public class StoryDemoTest extends TestBase { // 公共请求参数 Map params = new HashMap(); params.put("app_id", appId); - // 这里对应@ApiMapping.value属性 + // 这里对应@Open.value属性 params.put("method", "story.demo.get"); params.put("format", "json"); params.put("charset", "utf-8"); params.put("sign_type", "RSA2"); params.put("timestamp", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); - // 这里对应@ApiMapping.version属性 + // 这里对应@Open.version属性 params.put("version", "1.0"); // 业务参数 @@ -166,47 +145,3 @@ public class StoryDemoTest extends TestBase { {"story_demo_get_response":{"msg":"Success","code":"10000","name":"白雪公主","id":1},"sign":"YMbxTPdovi6htcn1K3USTS6/Tbg6MOAMigG6x/kG0kQFCYH8ljvxXzcY86UT056nUG3OXxnj0xkw07eV6E03HMlu7bn3/jrT3PCcV3YguhA92aWz720x2xJWdfXY13OUPS9VOCC9zIVxu6EBD+PoZ7ojYChYvOfCR5I8bR/oOc0ZLjK63PWTBdf0eFS4sybXzRf81uNLMROsMhmBDDy0Fhml3ml77qzWBIpsmq5ECZ+89rMPbkNhAUcnFAe7ik7xZIL6WcUhAOhKVa8ZQK1GMjoGnAbGRed1FbuOHZGubgffg4/vMqrY10Bcy6h9jt/zK5w9L3HVgK3aPgQlfP16Gg=="} ``` -## 开放现有接口 - -如果想把现有项目中的接口开放出去,提供给客户调用,具体操作如下: - -- 将现有项目接入到SOP,前往`项目接入到SOP`文档页查看 -- 在现有接口方法上加上一个注解`@ApiAbility`,如下面这个接口 - -```java -// 具备开放平台能力 -@ApiAbility -@RequestMapping("getStory2") -public Story getStory2_0() { - Story story = new Story(); - story.setId(1); - story.setName("海底小纵队(默认版本号)"); - return story; -} -``` - -- 启动程序 - -这种情况下,老接口依然能正常访问,同时开放平台也能访问进来。 - -**注意** 此时的开放接口对应的接口名为:类@RequestMapping.value + "." + 方法@RequestMapping.value - -举个列子: - -```java -@RequestMapping("goods") -public class MyController { - @ApiAbility - @RequestMapping("listGoods") - public Object fun() { - - } -} -``` - -fun接口对应的路径为:`/goods/listGoods` - -那么对应开放平台的接口名会转换成:`goods.listGoods`,客户端的method参数要填`goods.listGoods` - -当然也可以直接把@RequestMapping替换成`@ApiMapping`并指定接口名,这样的话不能兼容以前的访问形式。 - diff --git a/doc/docs/files/10030_业务参数校验.md b/doc/docs/files/10030_业务参数校验.md index 6ea1bce3..267f70fc 100644 --- a/doc/docs/files/10030_业务参数校验.md +++ b/doc/docs/files/10030_业务参数校验.md @@ -5,7 +5,8 @@ 在参数中使用注解即可,框架会自动进行验证。如下面一个添加商品接口,它的参数是GoodsParam ```java -@ApiMapping(value = "goods.add") +@Open("goods.add") +@RequestMapping("/goods/add") public void addGoods(GoodsParam param) { ... } diff --git a/doc/docs/files/10041_编写文档.md b/doc/docs/files/10041_编写文档.md index 7099232b..25ad741e 100644 --- a/doc/docs/files/10041_编写文档.md +++ b/doc/docs/files/10041_编写文档.md @@ -84,7 +84,7 @@ public class StoryResult { * @return */ @ApiOperation(value = "获取故事信息", notes = "说明接口的详细信息,介绍,用途,注意事项等。") -@ApiMapping(value = "alipay.story.find") +@Open(value = "alipay.story.find") public StoryResult getStory2(StoryParam story) { log.info("获取故事信息参数, story: {}", story); // 获取其它参数 diff --git a/doc/docs/files/10070_easyopen支持.md b/doc/docs/files/10070_easyopen支持.md deleted file mode 100644 index 438f7022..00000000 --- a/doc/docs/files/10070_easyopen支持.md +++ /dev/null @@ -1,78 +0,0 @@ -# easyopen支持 - -SOP对easyopen项目提供了很好的支持,如果您的服务端使用了easyopen框架,相关配置步骤如下: - -## 服务端配置 - -首先是服务端相关配置 - -- pom添加依赖 - -```xml - - - com.gitee.sop - sop-service-common - 最新版本 - - - - - org.springframework.cloud - spring-cloud-starter-alibaba-nacos-discovery - 0.2.2.RELEASE - - - com.alibaba.nacos - nacos-client - - - - - com.alibaba.nacos - nacos-client - 1.1.0 - - - - net.oschina.durcframework - easyopen - 1.16.1 - - -``` - -easyopen版本必须升级到1.16.1 - -- 启动类上面添加注解@EnableDiscoveryClient,将自己注册到注册中心 -- 新增一个配置类,继承EasyopenServiceConfiguration,内容为空 - -```java -@Configuration -public class SopConfig extends EasyopenServiceConfiguration { -} -``` - -服务端配置完毕,重启服务。 - -## 网关端配置 - -接下来是网关的配置 - -- 打开ZuulConfig.java,注释掉原本的@Configuration,新增如下Configuration - -```java -@Configuration -public class ZuulConfig extends EasyopenZuulConfiguration { - -} -``` - -配置完毕,重启网关服务,可运行测试用例`EasyopenClientPostTest.java`验证 - -**注:** 配置完成后easyopen签名校验将会关闭,改用网关端来校验;网关对easyopen返回的结果不进行处理,直接返回服务端的结果。 - -完整配置可查看sop-example/sop-easyopen项目 diff --git a/doc/docs/files/10089_自定义校验token.md b/doc/docs/files/10089_自定义校验token.md index 07152ef6..50aba542 100644 --- a/doc/docs/files/10089_自定义校验token.md +++ b/doc/docs/files/10089_自定义校验token.md @@ -1,6 +1,6 @@ -# 自定义校验token(2.5.0) +# 自定义校验token -从2.5.0开始在`@ApiMapping`注解中新增了一个属性`needToken`,用来告诉网关是否校验token +在`@Open`注解中有一个属性`needToken`,用来告诉网关是否校验token ```java /** @@ -12,7 +12,9 @@ boolean needToken() default false; 使用方式: ```java -@ApiMapping(value = "story.token.get", needToken = true/* 设置true,网关会校验token是否存在 */) +@ApiOperation(value="传递token", notes = "传递token") +@Open(value = "story.get.token", needToken = true/* 设置true,网关会校验token是否存在 */) +@RequestMapping("token") public StoryResult token(StoryParam story) { OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); String appAuthToken = openContext.getAppAuthToken(); @@ -42,14 +44,11 @@ public class MyConfig { ApiConfig.getInstance().setTokenValidator(apiParam -> { // 获取客户端传递过来的token String token = apiParam.fetchAccessToken(); - if (StringUtils.isBlank(token)) { - return false; - } + return !StringUtils.isBlank(token); // TODO: 校验token有效性,可以从redis中读取 // 返回true表示这个token真实、有效 - return true; - }); +}); } } ``` diff --git a/doc/docs/files/10090_路由授权.md b/doc/docs/files/10090_路由授权.md index 017dccc4..30e88502 100644 --- a/doc/docs/files/10090_路由授权.md +++ b/doc/docs/files/10090_路由授权.md @@ -9,8 +9,8 @@ 假设把路由a,b,c分配给了`VIP角色`,那么具有VIP角色的ISV可以访问a,b,c三个路由。 -默认情况下,接口访问时公开的,ISV都能访问。如果要设置某个接口访问权限,在`@ApiMapping`注解中指定permission=true。 -如:`@ApiMapping(value = "permission.story.get", permission = true)`。这样该接口是需要经过授权给ISV才能访问的。 +默认情况下,接口访问时公开的,ISV都能访问。如果要设置某个接口访问权限,在`@Open`注解中指定permission=true。 +如:`@Open(value = "permission.story.get", permission = true)`。这样该接口是需要经过授权给ISV才能访问的。 重启服务后,登录admin,服务管理-路由列表界面中,操作操作列会出现一个授权按钮,点击出现授权窗口,勾选对应的角色即可完成授权。 diff --git a/doc/docs/files/10096_使用SpringCloudGateway.md b/doc/docs/files/10096_使用SpringCloudGateway.md deleted file mode 100644 index 68d59c37..00000000 --- a/doc/docs/files/10096_使用SpringCloudGateway.md +++ /dev/null @@ -1,16 +0,0 @@ -# 使用SpringCloudGateway - -修改`sop-gateway/pom.xml`配置,artifactId部分改成`sop-bridge-gateway`即可 - -```xml - - com.gitee.sop - - - - sop-bridge-gateway - 对应版本 - -``` - -修改完毕,重启sop-gateway diff --git a/doc/docs/files/10100_提供restful接口.md b/doc/docs/files/10100_提供restful接口.md index 6bd49edb..2aef7b1f 100644 --- a/doc/docs/files/10100_提供restful接口.md +++ b/doc/docs/files/10100_提供restful接口.md @@ -1,27 +1,10 @@ -# 传统web开发 +# 提供rest接口 -默认情况下SOP只提供开放接口,也可以同时提供restful接口,即程序提供一部分的开放接口,同时提供一部分restful接口。 - -默认情况下提供restful功能是关闭的,开启方式如下: - -- 打开sop-gateway配置文件,新增一行配置: - -```properties -# 提供restful接口 -sop.restful.enable=true -``` - -- 前端app请求网关(`2.4.1之后有变动`) +有些接口没有被开放,但是也想要通过网关来访问,SOP提供一个固定的请求格式来访问。 请求格式: -**2.4.1版本之前:** `http://ip:port/rest/your_path`,其中`http://ip:port/rest/`为固定部分,后面跟微服务请求路径。 - -**2.4.1之后:** `http://ip:port/rest/服务id/your_path`,其中`http://ip:port/rest/`为固定部分,后面跟微服务请求路径。 - -**注意,`2.4.1`开始多了一个服务id作为区分,这样做是为了避免各微服务之间url冲突,假如两个微服务都有一个叫`/getItems`这样的接口 -那么调用`http://ip:port/rest/getItems`接口网关无法做出正确的路由,虽然可以在代码上进行规范,为了防止万一,还是强行加上了,避免采坑 -。可以指定`sop.restful.old-model=true`强制使用老的调用方式** +`http://ip:port/rest/服务id/your_path`,其中`http://ip:port/rest/`为固定部分,后面跟微服务请求路径。 > 可在微服务端指定一个配置:`sop.restful.prefix=xxx`。请求路径将变成:`http://ip:port/rest/xxx/your_path` @@ -48,7 +31,6 @@ public class TraditionalWebappController { 2. 本地访问:`http://10.0.1.22:2222/food/getFoodById/?id=2` -更多例子,可查看源码类:`TraditionalWebappController.java` 由此可见,对于前端调用者来说,它把网关看做一个大服务,只访问网关提供的请求,不需要关心网关后面的路由转发。网关后面各个微服务独自管理, 微服务之间的调用可以使用dubbo或feign,有了版本号的管理,可以做到服务的平滑升级,对用户来说都是无感知的。结合SOP-Admin提供的上下线功能, diff --git a/doc/docs/files/10104_文件上传.md b/doc/docs/files/10104_文件上传.md index c4482b16..ac60ab36 100644 --- a/doc/docs/files/10104_文件上传.md +++ b/doc/docs/files/10104_文件上传.md @@ -61,7 +61,8 @@ public UploadFile(String name, File file) throws IOException { * @param param * @return */ -@ApiMapping(value = "demo.file.upload") +@Open("file.upload") +@RequestMapping("file1") public FileUploadVO file1(FileUploadParam param) { System.out.println(param.getRemark()); // 获取上传的文件 @@ -95,7 +96,8 @@ public class FileUploadParam { * @param param * @return */ -@ApiMapping(value = "demo.file.upload2") +@Open("file.upload2") +@RequestMapping("file2") public FileUploadVO file2(FileUploadParam2 param, HttpServletRequest request) { System.out.println(param.getRemark()); FileUploadVO vo = new FileUploadVO(); diff --git a/doc/docs/files/10112_使用eureka.md b/doc/docs/files/10112_使用eureka.md index d239eb6e..b879bace 100644 --- a/doc/docs/files/10112_使用eureka.md +++ b/doc/docs/files/10112_使用eureka.md @@ -21,8 +21,8 @@ ```properties # nacos cloud配置 -#spring.cloud.nacos.discovery.server-addr=${nacos.url} -#nacos.config.server-addr=${nacos.url} +#spring.cloud.nacos.discovery.server-addr=${register.url} +#nacos.config.server-addr=${register.url} ``` 添加eureka配置 diff --git a/doc/docs/files/10113_扩展其它注册中心.md b/doc/docs/files/10113_扩展其它注册中心.md deleted file mode 100644 index c211d29a..00000000 --- a/doc/docs/files/10113_扩展其它注册中心.md +++ /dev/null @@ -1,86 +0,0 @@ -# 扩展其它注册中心 - -SOP默认使用的注册中心是[nacos](https://nacos.io/),可以扩展实现其它注册中心,其中`eureka`分支是已经扩展好的,使用eureka注册中心。 - -现在以扩展[consul](https://www.consul.io/)为例,说下具体扩展步骤: - -- 扩展注册中心监听 - -在`sop-gateway-common`工程下,找到com.gitee.sop.gatewaycommon.route包,可以看到有两个类 - -`EurekaRegistryListener`和`NacosRegistryListener` - -这两个类的作用是监听注册中心服务注册,从而触发事件,然后获取新注册的服务。 - -新建一个类:`ConsulRegistryListener`,继承`BaseRegistryListener` - -实现onEvent方法,具体内容可参考`EurekaRegistryListener`类 - -```java -public class ConsulRegistryListener extends BaseRegistryListener { - /** - * 注册中心触发事件,可以从中获取服务
- * - * 这个方法做的事情有2个:
- * - * 1. 找出新注册的服务,调用pullRoutes方法
- * 2. 找出删除的服务,调用removeRoutes方法
- * - * @param applicationEvent 事件体 - */ - @Override - public void onEvent(ApplicationEvent applicationEvent) { - - } -} -``` - -配置类中新增: - -```java -@Bean -@ConditionalOnProperty("spring.cloud.consul.host") -RegistryListener registryListenerConsul() { - return new ConsulRegistryListener(); -} -``` - -其中`@ConditionalOnProperty("spring.cloud.consul.host")`的意思是只有配置了`spring.cloud.consul.host`属性,这个Bean才会被Spring注入 - -`sop-gateway`工程添加`Spring Cloud Consul`相关依赖,配置文件新增consul配置 - -- 扩展admin实现 - -找到`sop-admin-server`工程下com.gitee.sop.adminserver.service包,可以看到有两个类,`RegistryServiceEurekaImpl`和`RegistryServiceNacosImpl` -它们实现了`com.gitee.sop.adminserver.service.RegistryService`接口,因此我们要新建一个consul对应的类 - -新建`RegistryServiceConsulImpl`,然后实现RegistryService接口中的方法,具体可参考RegistryServiceEurekaImpl - -```java -public class RegistryServiceConsulImpl implements RegistryService { - -} -``` - -打开`com.gitee.sop.adminserver.config.WebConfig`类 - -新增一条配置 - -```java -/** - * 当配置了registry.name=eureka生效。 - * - * @return - */ -@Bean -@ConditionalOnProperty(value = "registry.name", havingValue = "consul") -RegistryService registryServiceEureka() { - return new RegistryServiceConsulImpl(); -} -``` - -application配置文件新增一条配置: - -```properties -registry.name=consul -``` diff --git a/doc/docs/files/90010_原理分析之@ApiMapping.md b/doc/docs/files/90010_原理分析之@ApiMapping.md deleted file mode 100644 index 3b823294..00000000 --- a/doc/docs/files/90010_原理分析之@ApiMapping.md +++ /dev/null @@ -1,21 +0,0 @@ -# 原理分析之@ApiMapping注解 - -@ApiMapping注解的使用方式参考了Spring自带的@PostMapping注解。 - -查看org.springframework.web.bind.annotation.PostMapping的类注释,有这么一句话: - - -> Specifically, @PostMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.POST). - -翻译过来就是说,@PostMapping是一个组合模式的注解,可以看成是@RequestMapping(method = RequestMethod.POST)快捷方式。 - -如果我们自己定义个Mapping,仿照@PostMapping的方式,然后作用在方法上面会不会成功呢?实践证明是可以的。 - -@ApiMapping注解正是仿照了@PostMapping注解,然后再添加了几个自己的属性,比如版本号字段。 - -那么如何才能通过path + 版本号来确定一个接口呢? - -springmvc提供了RequestCondition接口来实现这个功能,具体的操作可参考这篇文章:[让SpringMVC支持可版本管理的Restful接口](http://www.cnblogs.com/jcli/p/springmvc_restful_version.html) - -SOP对应的是`com.gitee.sop.servercommon.mapping.ApiMappingRequestCondition`,这个类在com.gitee.sop.servercommon.mapping下。可以从`ApiMappingHandlerMapping`类开始解读。 - diff --git a/doc/docs/files/90099_2.x升3.x注意事项.md b/doc/docs/files/90099_2.x升3.x注意事项.md deleted file mode 100644 index 1cf1d194..00000000 --- a/doc/docs/files/90099_2.x升3.x注意事项.md +++ /dev/null @@ -1,23 +0,0 @@ -# 2.x升3.x注意事项 - -升级到3.x后`本地访问接口`方式会有不同。 - -```java -@ApiMapping(value = "alipay.story.get") -public StoryResult getStory(StoryParam param) { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("海底小纵队(alipay.story.get1.0), port:" + environment.getProperty("server.port") + ", param:" + param); - return story; -} -``` - -- 2.x版本访问方式: - -`http://localhost:2222/alipay.story.get/?name=Jim&version=1.0` - -- 3.x版本访问方式: - -`http://localhost:2222/alipay.story.get/1.0/?name=Jim` - -3.x版本中把版本号融合在了url中,如果这个功能没有用到,可以放心升级。 \ No newline at end of file diff --git a/doc/docs/files/90100_常见问题.md b/doc/docs/files/90100_常见问题.md index 65b54b8f..c852eb15 100644 --- a/doc/docs/files/90100_常见问题.md +++ b/doc/docs/files/90100_常见问题.md @@ -34,7 +34,7 @@ Story bizObject = openContext.getBizObject(Story.class); ## 如何关闭签名验证 - 针对某一个接口关闭签名验证 -`@ApiMapping(value = "alipay.story.get", ignoreValidate = true)` +`@Open(value = "alipay.story.get", ignoreValidate = true)` - 针对所有接口关闭签名验证 @@ -100,7 +100,7 @@ yml添加: # https://blog.csdn.net/qq_36872046/article/details/81058045 # 路由转发超时时间,毫秒,默认值1000,详见:RibbonClientConfiguration.DEFAULT_READ_TIMEOUT。 # 如果微服务端 处理时间过长,会导致ribbon read超时,解决办法将这个值调大一点 -ribbon.ReadTimeout: 60000 +ribbon.ReadTimeout= 60000 ``` ## 指定了context-path(拉取路由404) diff --git a/pom.xml b/pom.xml index ffd2adce..c760cfd0 100644 --- a/pom.xml +++ b/pom.xml @@ -51,7 +51,7 @@ 4.11 - 1.2.70 + 1.2.73 2.5 1.3.3 3.2.2 diff --git a/sop-admin/sop-admin-server/pom.xml b/sop-admin/sop-admin-server/pom.xml index cd697a17..9d779dc8 100644 --- a/sop-admin/sop-admin-server/pom.xml +++ b/sop-admin/sop-admin-server/pom.xml @@ -22,8 +22,9 @@ - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery + com.gitee.sop + sop-bridge-nacos + 3.2.0-SNAPSHOT diff --git a/sop-admin/sop-admin-server/readme.md b/sop-admin/sop-admin-server/readme.md index c233a546..947b5486 100644 --- a/sop-admin/sop-admin-server/readme.md +++ b/sop-admin/sop-admin-server/readme.md @@ -10,4 +10,13 @@ 后台用户表:admin_user_info -密码保存规则:两次MD5,即`md5(md5("123456"))` \ No newline at end of file +- 密码保存规则:`md5(username + md5(password) + username)` + +```text +username: admin +password: 123456 +即 +md5("admin" + md5(123456) + "admin") +``` + +详见:com.gitee.sop.adminserver.AccountTest diff --git a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/system/SystemApi.java b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/system/SystemApi.java index 356411fb..3a9b4b81 100644 --- a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/system/SystemApi.java +++ b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/api/system/SystemApi.java @@ -36,7 +36,7 @@ public class SystemApi { String adminLogin(LoginForm param) { String username = param.getUsername(); String password = param.getPassword(); - password = DigestUtils.md5Hex(password); + password = DigestUtils.md5Hex(username + password + username); Query query = new Query() .eq("username", username) diff --git a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/bean/ServiceInfo.java b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/bean/ServiceInfo.java index 8a10e096..cf17a94d 100644 --- a/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/bean/ServiceInfo.java +++ b/sop-admin/sop-admin-server/src/main/java/com/gitee/sop/adminserver/bean/ServiceInfo.java @@ -1,16 +1,29 @@ package com.gitee.sop.adminserver.bean; -import lombok.Data; - import java.util.List; /** * @author tanghc */ -@Data public class ServiceInfo { /** 服务名称 */ private String serviceId; /** 实例列表 */ private List instances; + + public String getServiceId() { + return serviceId; + } + + public void setServiceId(String serviceId) { + this.serviceId = serviceId; + } + + public List getInstances() { + return instances; + } + + public void setInstances(List instances) { + this.instances = instances; + } } diff --git a/sop-admin/sop-admin-server/src/main/resources/META-INF/sop-admin.properties b/sop-admin/sop-admin-server/src/main/resources/META-INF/sop-admin.properties index f182a180..3920b570 100644 --- a/sop-admin/sop-admin-server/src/main/resources/META-INF/sop-admin.properties +++ b/sop-admin/sop-admin-server/src/main/resources/META-INF/sop-admin.properties @@ -10,10 +10,14 @@ admin.access-token.timeout-minutes=30 sop.sign-type=rsa # nacos配置 -nacos.config.server-addr=${nacos.url} -nacos.discovery.server-addr=${nacos.url} +nacos.config.server-addr=${register.url} +nacos.discovery.server-addr=${register.url} + # nacos cloud配置 -spring.cloud.nacos.discovery.server-addr=${nacos.url} +spring.cloud.nacos.discovery.server-addr=${register.url} + +# eureka地址 +eureka.client.serviceUrl.defaultZone=${register.url} # 数据库配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/sop-admin/sop-admin-server/src/main/resources/application-dev.properties b/sop-admin/sop-admin-server/src/main/resources/application-dev.properties index 917d0f92..62de585c 100644 --- a/sop-admin/sop-admin-server/src/main/resources/application-dev.properties +++ b/sop-admin/sop-admin-server/src/main/resources/application-dev.properties @@ -5,7 +5,7 @@ mysql.host=localhost:3306 mysql.username=root mysql.password=root -# nacos注册中心地址 -nacos.url=127.0.0.1:8848 +# 注册中心地址 +register.url=127.0.0.1:8848 logging.level.com.gitee=debug diff --git a/sop-admin/sop-admin-server/src/test/java/com/gitee/sop/adminserver/AccountTest.java b/sop-admin/sop-admin-server/src/test/java/com/gitee/sop/adminserver/AccountTest.java new file mode 100644 index 00000000..a9427f7a --- /dev/null +++ b/sop-admin/sop-admin-server/src/test/java/com/gitee/sop/adminserver/AccountTest.java @@ -0,0 +1,23 @@ +package com.gitee.sop.adminserver; + +import junit.framework.TestCase; +import org.apache.commons.codec.digest.DigestUtils; +import org.junit.jupiter.api.Test; + +/** + * @author tanghc + */ +public class AccountTest extends TestCase { + + /* + 生成密码 + */ + @Test + public void genPwd() { + String username = "admin"; + String password = "123456"; + String save_to_db = DigestUtils.md5Hex(username + DigestUtils.md5Hex(password) + username); + System.out.println(save_to_db); + } + +} diff --git a/sop-auth/src/main/java/com/gitee/sop/sopauth/controller/OAuth2Controller.java b/sop-auth/src/main/java/com/gitee/sop/sopauth/controller/OAuth2Controller.java index 97fcfc6e..2989ab63 100644 --- a/sop-auth/src/main/java/com/gitee/sop/sopauth/controller/OAuth2Controller.java +++ b/sop-auth/src/main/java/com/gitee/sop/sopauth/controller/OAuth2Controller.java @@ -1,6 +1,6 @@ package com.gitee.sop.sopauth.controller; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.sopauth.auth.FetchTokenParam; import com.gitee.sop.sopauth.auth.FetchTokenResult; import com.gitee.sop.sopauth.auth.OAuth2Config; @@ -73,7 +73,8 @@ public class OAuth2Controller { * @param param * @return */ - @ApiMapping("open.auth.token.app") + @Open("open.auth.token.app") + @RequestMapping("fetchToken") @ResponseBody public FetchTokenResult fetchToken(FetchTokenParam param) { FetchTokenResult fetchTokenResult = oAuth2Service.accessToken(param, OAuth2Config.getInstance()); diff --git a/sop-auth/src/main/resources/application-dev.properties b/sop-auth/src/main/resources/application-dev.properties index 6a15f1c6..40f34a1b 100644 --- a/sop-auth/src/main/resources/application-dev.properties +++ b/sop-auth/src/main/resources/application-dev.properties @@ -8,12 +8,12 @@ mysql.username=root mysql.password=root # nacos地址 -nacos.url=127.0.0.1:8848 +register.url=127.0.0.1:8848 # ------- 需要改的配置end ------- # nacos cloud配置 -spring.cloud.nacos.discovery.server-addr=${nacos.url} +spring.cloud.nacos.discovery.server-addr=${register.url} # 数据库配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/sop-common/pom.xml b/sop-common/pom.xml index 00e5bfdd..9fc2f485 100644 --- a/sop-common/pom.xml +++ b/sop-common/pom.xml @@ -20,10 +20,10 @@ + sop-bridge-nacos + sop-bridge-eureka sop-gateway-common sop-service-common - sop-bridge-zuul - sop-bridge-gateway diff --git a/sop-common/readme.md b/sop-common/readme.md index d5109565..497bdfd7 100644 --- a/sop-common/readme.md +++ b/sop-common/readme.md @@ -1,7 +1,7 @@ # sop-common -- sop-bridge-gateway:网关桥接器,供sop-gateway依赖,依赖后使用spring cloud gateway网关 -- sop-bridge-zuul:网关桥接器,供sop-gateway依赖,依赖后使用spring cloud zuul网关 +- sop-bridge-nacos:注册中心桥接器,接入nacos +- sop-bridge-eureka:注册中心桥接器,接入eureka - sop-gateway-common:提供给网关使用 - sop-service-common:提供给微服务端使用,需要打成jar diff --git a/sop-common/sop-bridge-zuul/pom.xml b/sop-common/sop-bridge-eureka/pom.xml similarity index 78% rename from sop-common/sop-bridge-zuul/pom.xml rename to sop-common/sop-bridge-eureka/pom.xml index 58ba3568..ead99a7b 100644 --- a/sop-common/sop-bridge-zuul/pom.xml +++ b/sop-common/sop-bridge-eureka/pom.xml @@ -12,7 +12,7 @@ 4.0.0 3.2.0-SNAPSHOT - sop-bridge-zuul + sop-bridge-eureka @@ -23,11 +23,13 @@ org.springframework.cloud - spring-cloud-starter-netflix-zuul + spring-cloud-starter-netflix-eureka-client + - org.springframework.retry - spring-retry + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + \ No newline at end of file diff --git a/sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java b/sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java new file mode 100644 index 00000000..4b6a8a7c --- /dev/null +++ b/sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java @@ -0,0 +1,31 @@ +package com.gitee.sop.bridge; + +import com.gitee.sop.bridge.route.EurekaRegistryListener; +import com.gitee.sop.gatewaycommon.route.RegistryListener; +import org.springframework.cloud.netflix.ribbon.ServerIntrospector; +import org.springframework.cloud.netflix.ribbon.eureka.EurekaServerIntrospector; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author tanghc + */ +@Configuration +public class SopRegisterAutoConfiguration { + + /** + * 负责获取eureka实例的metadata + * @return + */ + @Bean + ServerIntrospector eurekaServerIntrospector() { + return new EurekaServerIntrospector(); + } + + @Bean + RegistryListener registryListenerEureka() { + return new EurekaRegistryListener(); + } + +} + diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/EurekaRegistryListener.java b/sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/route/EurekaRegistryListener.java similarity index 96% rename from sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/EurekaRegistryListener.java rename to sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/route/EurekaRegistryListener.java index 61cc436e..f0ca2758 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/EurekaRegistryListener.java +++ b/sop-common/sop-bridge-eureka/src/main/java/com/gitee/sop/bridge/route/EurekaRegistryListener.java @@ -1,6 +1,9 @@ -package com.gitee.sop.gatewaycommon.route; +package com.gitee.sop.bridge.route; import com.gitee.sop.gatewaycommon.bean.InstanceDefinition; +import com.gitee.sop.gatewaycommon.route.BaseRegistryListener; +import com.gitee.sop.gatewaycommon.route.RegistryEvent; +import com.gitee.sop.gatewaycommon.route.ServiceHolder; import com.netflix.appinfo.InstanceInfo; import com.netflix.discovery.shared.Application; import com.netflix.discovery.shared.Applications; diff --git a/sop-common/sop-bridge-gateway/pom.xml b/sop-common/sop-bridge-nacos/pom.xml similarity index 65% rename from sop-common/sop-bridge-gateway/pom.xml rename to sop-common/sop-bridge-nacos/pom.xml index 89b05e72..6b5f547b 100644 --- a/sop-common/sop-bridge-gateway/pom.xml +++ b/sop-common/sop-bridge-nacos/pom.xml @@ -11,7 +11,7 @@ 4.0.0 3.2.0-SNAPSHOT - sop-bridge-gateway + sop-bridge-nacos @@ -21,16 +21,14 @@ - org.springframework.cloud - spring-cloud-starter-gateway - - - org.springframework.boot - spring-boot-starter-webflux + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + - org.springframework.boot - spring-boot-starter-actuator + org.projectlombok + lombok + provided \ No newline at end of file diff --git a/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java new file mode 100644 index 00000000..6929b702 --- /dev/null +++ b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/SopRegisterAutoConfiguration.java @@ -0,0 +1,46 @@ +package com.gitee.sop.bridge; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosWatch; +import com.gitee.sop.bridge.route.NacosRegistryListener; +import com.gitee.sop.gatewaycommon.route.RegistryListener; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.scheduling.TaskScheduler; + +import java.util.Map; + +/** + * @author tanghc + */ +@Configuration +public class SopRegisterAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties, ObjectProvider taskScheduler, Environment environment) { + Map metadata = nacosDiscoveryProperties.getMetadata(); + String contextPath = environment.getProperty("server.servlet.context-path"); + // 将context-path信息加入到metadata中 + if (contextPath != null) { + metadata.put("context-path", contextPath); + } + // 在元数据中新增启动时间,不能修改这个值,不然网关拉取接口会有问题 + metadata.put("time.startup", String.valueOf(System.currentTimeMillis())); + return new NacosWatch(nacosDiscoveryProperties, taskScheduler); + } + + /** + * 微服务路由加载 + */ + @Bean + RegistryListener registryListenerNacos() { + return new NacosRegistryListener(); + } +} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosRegistryListener.java b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosRegistryListener.java similarity index 97% rename from sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosRegistryListener.java rename to sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosRegistryListener.java index 75519137..cc871f80 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosRegistryListener.java +++ b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosRegistryListener.java @@ -1,4 +1,4 @@ -package com.gitee.sop.gatewaycommon.route; +package com.gitee.sop.bridge.route; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.exception.NacosException; @@ -6,6 +6,8 @@ import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; import com.gitee.sop.gatewaycommon.bean.InstanceDefinition; +import com.gitee.sop.gatewaycommon.route.BaseRegistryListener; +import com.gitee.sop.gatewaycommon.route.RegistryEvent; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationEvent; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosServiceHolder.java b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosServiceHolder.java similarity index 75% rename from sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosServiceHolder.java rename to sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosServiceHolder.java index 0b022f62..e7dfecbd 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/NacosServiceHolder.java +++ b/sop-common/sop-bridge-nacos/src/main/java/com/gitee/sop/bridge/route/NacosServiceHolder.java @@ -1,13 +1,14 @@ -package com.gitee.sop.gatewaycommon.route; +package com.gitee.sop.bridge.route; import com.alibaba.nacos.api.naming.pojo.Instance; +import com.gitee.sop.gatewaycommon.route.ServiceHolder; /** * @author tanghc */ public class NacosServiceHolder extends ServiceHolder { - private Instance instance; + private final Instance instance; public NacosServiceHolder(String serviceId, long lastUpdatedTimestamp, Instance instance) { super(serviceId, lastUpdatedTimestamp); diff --git a/sop-common/sop-bridge-gateway/src/main/resources/sop-bridge.properties b/sop-common/sop-bridge-nacos/src/main/resources/sop-bridge.properties similarity index 95% rename from sop-common/sop-bridge-gateway/src/main/resources/sop-bridge.properties rename to sop-common/sop-bridge-nacos/src/main/resources/sop-bridge.properties index 115692b7..0535c7b5 100644 --- a/sop-common/sop-bridge-gateway/src/main/resources/sop-bridge.properties +++ b/sop-common/sop-bridge-nacos/src/main/resources/sop-bridge.properties @@ -7,7 +7,7 @@ sop.secret=MZZOUSTua6LzApIWXCwEgbBmxSzpzC sop.gateway-index-path=/ # nacos cloud配置 -spring.cloud.nacos.discovery.server-addr=${nacos.url} +spring.cloud.nacos.discovery.server-addr=${register.url} # 数据库配置 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver diff --git a/sop-common/sop-bridge-zuul/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java b/sop-common/sop-bridge-zuul/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java deleted file mode 100644 index 2e17861c..00000000 --- a/sop-common/sop-bridge-zuul/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.sop.bridge; - -import com.gitee.sop.gatewaycommon.config.BaseGatewayAutoConfiguration; -import com.gitee.sop.gatewaycommon.zuul.configuration.AlipayZuulConfiguration; -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration; -import org.springframework.cloud.netflix.zuul.EnableZuulProxy; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - -/** - * https://blog.csdn.net/seashouwang/article/details/80299571 - * @author tanghc - */ -@Configuration -@EnableZuulProxy -@Import(AlipayZuulConfiguration.class) -// 在ErrorMvcAutoConfiguration之前加载 -// 如果不加会出现basicErrorController和zuulErrorController冲突 -// zuulErrorController是SOP中的,提前加载后basicErrorController就不会加载 -@AutoConfigureBefore({ErrorMvcAutoConfiguration.class}) -public class SopGatewayAutoConfiguration extends BaseGatewayAutoConfiguration { -} - diff --git a/sop-common/sop-gateway-common/pom.xml b/sop-common/sop-gateway-common/pom.xml index e087901c..82bd2131 100644 --- a/sop-common/sop-gateway-common/pom.xml +++ b/sop-common/sop-gateway-common/pom.xml @@ -19,6 +19,7 @@ + com.google.guava guava @@ -60,12 +61,6 @@ true - - org.springframework.cloud - spring-cloud-starter-netflix-zuul - true - - org.springframework.cloud spring-cloud-starter-gateway @@ -76,11 +71,6 @@ spring-boot-starter-webflux true - - org.springframework.cloud - spring-cloud-netflix-eureka-server - true - org.springframework.data diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/ApiConfig.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/ApiConfig.java index 855a134e..8118cc8d 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/ApiConfig.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/ApiConfig.java @@ -25,7 +25,6 @@ import com.gitee.sop.gatewaycommon.result.DataNameBuilder; import com.gitee.sop.gatewaycommon.result.DefaultDataNameBuilder; import com.gitee.sop.gatewaycommon.result.ResultAppender; import com.gitee.sop.gatewaycommon.result.ResultExecutorForGateway; -import com.gitee.sop.gatewaycommon.result.ResultExecutorForZuul; import com.gitee.sop.gatewaycommon.secret.CacheIsvManager; import com.gitee.sop.gatewaycommon.secret.IsvManager; import com.gitee.sop.gatewaycommon.session.ApiSessionManager; @@ -37,9 +36,6 @@ import com.gitee.sop.gatewaycommon.validate.Encrypter; import com.gitee.sop.gatewaycommon.validate.Signer; import com.gitee.sop.gatewaycommon.validate.TokenValidator; import com.gitee.sop.gatewaycommon.validate.Validator; -import com.gitee.sop.gatewaycommon.zuul.controller.ZuulErrorController; -import com.gitee.sop.gatewaycommon.zuul.param.ZuulParamBuilder; -import com.gitee.sop.gatewaycommon.zuul.result.ZuulResultExecutor; import lombok.Data; import org.apache.commons.lang3.StringUtils; @@ -67,11 +63,6 @@ public class ApiConfig { */ private ResultExecutorForGateway gatewayResultExecutor = new GatewayResultExecutor(); - /** - * zuul合并结果处理 - */ - private ResultExecutorForZuul zuulResultExecutor = new ZuulResultExecutor(); - /** * isv管理 */ @@ -87,11 +78,6 @@ public class ApiConfig { */ private Signer signer = new ApiSigner(); - /** - * 参数解析,zuul - */ - private ZuulParamBuilder zuulParamBuilder = new ZuulParamBuilder(); - /** * 验证 */ @@ -147,11 +133,6 @@ public class ApiConfig { */ private ServiceErrorManager serviceErrorManager = new DefaultServiceErrorManager(); - /** - * zuul网关全局异常处理 - */ - private ZuulErrorController zuulErrorController = new ZuulErrorController(); - private ParameterFormatter parameterFormatter; /** diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/SopConstants.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/SopConstants.java index beb5e859..47abfbd3 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/SopConstants.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/bean/SopConstants.java @@ -52,5 +52,6 @@ public class SopConstants { public static final String CACHE_ROUTE_INTERCEPTOR_CONTEXT = "cacheRouteInterceptorContext"; public static final String TARGET_SERVICE = "sop-target-service"; + public static final String RESTFUL_REQUEST = "sop-restful-request"; } diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/AbstractConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/AbstractConfiguration.java similarity index 82% rename from sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/AbstractConfiguration.java rename to sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/AbstractConfiguration.java index 41432203..c4ad39a3 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/AbstractConfiguration.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/AbstractConfiguration.java @@ -1,4 +1,4 @@ -package com.gitee.sop.gatewaycommon.manager; +package com.gitee.sop.gatewaycommon.config; import com.gitee.sop.gatewaycommon.bean.ApiConfig; import com.gitee.sop.gatewaycommon.bean.ApiContext; @@ -8,11 +8,16 @@ import com.gitee.sop.gatewaycommon.gateway.loadbalancer.NacosServerIntrospector; import com.gitee.sop.gatewaycommon.interceptor.MonitorRouteInterceptor; import com.gitee.sop.gatewaycommon.interceptor.RouteInterceptor; import com.gitee.sop.gatewaycommon.limit.LimitManager; -import com.gitee.sop.gatewaycommon.loadbalancer.SopPropertiesFactory; +import com.gitee.sop.gatewaycommon.manager.EnvGrayManager; +import com.gitee.sop.gatewaycommon.manager.EnvironmentContext; +import com.gitee.sop.gatewaycommon.manager.EnvironmentKeys; +import com.gitee.sop.gatewaycommon.manager.IPBlacklistManager; +import com.gitee.sop.gatewaycommon.manager.IsvRoutePermissionManager; +import com.gitee.sop.gatewaycommon.manager.LimitConfigManager; +import com.gitee.sop.gatewaycommon.manager.RouteConfigManager; +import com.gitee.sop.gatewaycommon.manager.RouteRepositoryContext; import com.gitee.sop.gatewaycommon.message.ErrorFactory; import com.gitee.sop.gatewaycommon.param.ParameterFormatter; -import com.gitee.sop.gatewaycommon.route.EurekaRegistryListener; -import com.gitee.sop.gatewaycommon.route.NacosRegistryListener; import com.gitee.sop.gatewaycommon.route.RegistryListener; import com.gitee.sop.gatewaycommon.route.ServiceListener; import com.gitee.sop.gatewaycommon.route.ServiceRouteListener; @@ -29,9 +34,7 @@ import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.client.discovery.event.HeartbeatEvent; -import org.springframework.cloud.netflix.ribbon.PropertiesFactory; import org.springframework.cloud.netflix.ribbon.ServerIntrospector; -import org.springframework.cloud.netflix.ribbon.eureka.EurekaServerIntrospector; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; @@ -39,9 +42,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.event.EventListener; import org.springframework.core.env.Environment; import org.springframework.web.cors.CorsConfiguration; -import org.springframework.web.cors.UrlBasedCorsConfigurationSource; import org.springframework.web.cors.reactive.CorsWebFilter; -import org.springframework.web.filter.CorsFilter; import javax.annotation.PostConstruct; import java.util.ArrayList; @@ -96,27 +97,6 @@ public class AbstractConfiguration implements ApplicationContextAware, Applicati registryListener.onEvent(heartbeatEvent); } - @Bean - @ConditionalOnProperty("zuul.servlet-path") - PropertiesFactory propertiesFactory() { - return new SopPropertiesFactory(); - } - - /** - * 微服务路由加载 - */ - @Bean - @ConditionalOnProperty("spring.cloud.nacos.discovery.server-addr") - RegistryListener registryListenerNacos() { - return new NacosRegistryListener(); - } - - @Bean - @ConditionalOnProperty("eureka.client.serviceUrl.defaultZone") - RegistryListener registryListenerEureka() { - return new EurekaRegistryListener(); - } - @Bean @ConditionalOnMissingBean ServiceListener serviceListener() { @@ -184,18 +164,6 @@ public class AbstractConfiguration implements ApplicationContextAware, Applicati } - /** - * 跨域过滤器,zuul - */ - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty("zuul.servlet-path") - public CorsFilter corsFilter() { - UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); - source.registerCorsConfiguration("/**", createCorsConfiguration()); - return new CorsFilter(source); - } - /** * 跨域过滤器,gateway采用react形式,需要使用reactive包下的UrlBasedCorsConfigurationSource */ @@ -226,15 +194,7 @@ public class AbstractConfiguration implements ApplicationContextAware, Applicati return new NacosServerIntrospector(); } - /** - * 负责获取eureka实例的metadata - * @return - */ - @Bean - @ConditionalOnProperty("eureka.client.serviceUrl.defaultZone") - ServerIntrospector eurekaServerIntrospector() { - return new EurekaServerIntrospector(); - } + @Override public void run(ApplicationArguments args) throws Exception { diff --git a/sop-common/sop-bridge-gateway/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayAutoConfiguration.java similarity index 85% rename from sop-common/sop-bridge-gateway/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java rename to sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayAutoConfiguration.java index 34c61cd8..49ff0574 100644 --- a/sop-common/sop-bridge-gateway/src/main/java/com/gitee/sop/bridge/SopGatewayAutoConfiguration.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayAutoConfiguration.java @@ -1,6 +1,5 @@ -package com.gitee.sop.bridge; +package com.gitee.sop.gatewaycommon.config; -import com.gitee.sop.gatewaycommon.config.BaseGatewayAutoConfiguration; import com.gitee.sop.gatewaycommon.gateway.configuration.AlipayGatewayConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayEnvironmentPostProcessor.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayEnvironmentPostProcessor.java index 9ea1cbc1..6f12412c 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayEnvironmentPostProcessor.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/config/SopGatewayEnvironmentPostProcessor.java @@ -20,7 +20,7 @@ public class SopGatewayEnvironmentPostProcessor implements EnvironmentPostProces @Override public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { - Resource resource = new ClassPathResource("sop-bridge.properties"); + Resource resource = new ClassPathResource("META-INF/gateway.properties"); // 加载成PropertySource对象,并添加到Environment环境中 environment.getPropertySources().addLast(loadProfiles(resource)); } diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenResultExecutor.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenResultExecutor.java deleted file mode 100644 index 44c54282..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenResultExecutor.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.gitee.sop.gatewaycommon.easyopen; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.gatewaycommon.message.Error; -import com.gitee.sop.gatewaycommon.result.ApiResult; -import com.gitee.sop.gatewaycommon.result.ResultExecutorForZuul; -import com.gitee.sop.gatewaycommon.zuul.result.ZuulResultExecutor; -import com.netflix.zuul.context.RequestContext; - -import java.util.Locale; -import java.util.Optional; - -/** - * @author tanghc - */ -public class EasyopenResultExecutor implements ResultExecutorForZuul { - - boolean onlyReturnData; - - public EasyopenResultExecutor(boolean onlyReturnData) { - this.onlyReturnData = onlyReturnData; - } - - @Override - public String mergeResult(RequestContext request, String serviceResult) { - if (onlyReturnData) { - JSONObject jsonObject = JSON.parseObject(serviceResult); - return Optional.ofNullable(jsonObject.getString("data")).orElse("{}"); - } else { - return serviceResult; - } - } - - @Override - public String buildErrorResult(RequestContext requestContext, Throwable ex) { - ApiResult apiResult = new ApiResult(); - Locale locale = requestContext.getRequest().getLocale(); - Error error = ZuulResultExecutor.getError(locale, ex); - apiResult.setCode(error.getSub_code()); - apiResult.setMsg(error.getSub_msg()); - return JSON.toJSONString(apiResult); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenSigner.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenSigner.java deleted file mode 100644 index daf23ba9..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenSigner.java +++ /dev/null @@ -1,33 +0,0 @@ -package com.gitee.sop.gatewaycommon.easyopen; - -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.validate.AbstractSigner; -import org.apache.commons.codec.digest.DigestUtils; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -/** - * @author tanghc - */ -public class EasyopenSigner extends AbstractSigner { - @Override - protected String buildServerSign(ApiParam params, String secret) { - Set keySet = params.keySet(); - List paramNames = new ArrayList<>(keySet); - - Collections.sort(paramNames); - - StringBuilder paramNameValue = new StringBuilder(); - - for (String paramName : paramNames) { - paramNameValue.append(paramName).append(params.get(paramName)); - } - - String source = secret + paramNameValue.toString() + secret; - - return DigestUtils.md5Hex(source).toUpperCase(); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenZuulConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenZuulConfiguration.java deleted file mode 100644 index 5e531fe4..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/easyopen/EasyopenZuulConfiguration.java +++ /dev/null @@ -1,38 +0,0 @@ -package com.gitee.sop.gatewaycommon.easyopen; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.param.ParamNames; -import com.gitee.sop.gatewaycommon.zuul.configuration.BaseZuulConfiguration; - -/** - * @author tanghc - */ -public class EasyopenZuulConfiguration extends BaseZuulConfiguration { - - public EasyopenZuulConfiguration() { - ApiConfig apiConfig = ApiContext.getApiConfig(); - if (compatibilityModel()) { - ParamNames.APP_KEY_NAME = "app_key"; - ParamNames.API_NAME = "name"; - ParamNames.SIGN_TYPE_NAME = "sign_type"; - ParamNames.APP_AUTH_TOKEN_NAME = "access_token"; - apiConfig.setSigner(new EasyopenSigner()); - apiConfig.setZuulResultExecutor(new EasyopenResultExecutor(false)); - apiConfig.setMergeResult(false); - } else { - apiConfig.setZuulResultExecutor(new EasyopenResultExecutor(true)); - } - } - - /** - * 是否是兼容模式 - * @return 返回true,返回true可兼容之前的easyopen接口。 - */ - public boolean compatibilityModel() { - return true; - } - - - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/ServerWebExchangeUtil.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/ServerWebExchangeUtil.java index 502178ed..4357fe76 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/ServerWebExchangeUtil.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/ServerWebExchangeUtil.java @@ -81,13 +81,10 @@ public class ServerWebExchangeUtil { return ServerRequest.create(exchange, messageReaders); } - public static ApiParam getApiParamForRestful(ServerWebExchange exchange, String path) { + public static String getRestfulPath(String path) { int index = path.indexOf(REST_PATH); // 取"/rest"的后面部分 - String newPath = path.substring(index + REST_PATH.length()); - ApiParam apiParam = ApiParam.createRestfulApiParam(newPath); - setApiParam(exchange, apiParam); - return apiParam; + return path.substring(index + REST_PATH.length()); } /** @@ -97,7 +94,7 @@ public class ServerWebExchangeUtil { * @param forwardPath 重定向path * @return 返回新的ServerWebExchange,配合chain.filter(newExchange);使用 */ - private static ServerWebExchange getForwardExchange(ServerWebExchange exchange, String forwardPath) { + public static ServerWebExchange getForwardExchange(ServerWebExchange exchange, String forwardPath) { ServerHttpRequest newRequest = exchange.getRequest() .mutate() .path(forwardPath).build(); diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/configuration/BaseGatewayConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/configuration/BaseGatewayConfiguration.java index ae8717e7..f5036d8a 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/configuration/BaseGatewayConfiguration.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/configuration/BaseGatewayConfiguration.java @@ -15,7 +15,7 @@ import com.gitee.sop.gatewaycommon.gateway.loadbalancer.SopLoadBalancerClient; import com.gitee.sop.gatewaycommon.gateway.route.GatewayForwardChooser; import com.gitee.sop.gatewaycommon.gateway.route.GatewayRouteCache; import com.gitee.sop.gatewaycommon.gateway.route.GatewayRouteRepository; -import com.gitee.sop.gatewaycommon.manager.AbstractConfiguration; +import com.gitee.sop.gatewaycommon.config.AbstractConfiguration; import com.gitee.sop.gatewaycommon.manager.RouteRepositoryContext; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.ObjectProvider; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/GatewayModifyResponseGatewayFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/GatewayModifyResponseGatewayFilter.java index 986af8e7..ca72a59c 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/GatewayModifyResponseGatewayFilter.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/GatewayModifyResponseGatewayFilter.java @@ -1,6 +1,7 @@ package com.gitee.sop.gatewaycommon.gateway.filter; import com.gitee.sop.gatewaycommon.bean.ApiContext; +import com.gitee.sop.gatewaycommon.bean.SopConstants; import com.gitee.sop.gatewaycommon.result.ResultExecutor; import org.apache.commons.lang3.StringUtils; import org.reactivestreams.Publisher; @@ -48,6 +49,10 @@ public class GatewayModifyResponseGatewayFilter implements GlobalFilter, Ordered if (StringUtils.containsIgnoreCase(originalResponseContentType, MediaType.APPLICATION_OCTET_STREAM_VALUE)) { return chain.filter(exchange); } + // rest请求,直接放行 + if (exchange.getAttribute(SopConstants.RESTFUL_REQUEST) != null) { + return chain.filter(exchange); + } Class inClass = String.class; Class outClass = String.class; HttpHeaders httpHeaders = new HttpHeaders(); diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/IndexFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/IndexFilter.java index 0d9801b9..7c5b5a5d 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/IndexFilter.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/IndexFilter.java @@ -48,7 +48,7 @@ public class IndexFilter implements WebFilter { private static final String REST_PATH_PREFIX = "/rest"; /** 路径白名单 */ - private static List PATH_WHITE_LIST = Arrays.asList( + private static final List PATH_WHITE_LIST = Arrays.asList( "/sop", "/actuator" ); @@ -71,15 +71,9 @@ public class IndexFilter implements WebFilter { } // 如果是restful请求,直接转发 if (path.startsWith(REST_PATH_PREFIX)) { - String sopRestfulEnableValue = EnvironmentKeys.SOP_RESTFUL_ENABLE.getValue(); - if (!Objects.equals("true", sopRestfulEnableValue)) { - log.error("尝试调用restful请求,但sop.restful.enable未开启"); - return ServerWebExchangeUtil.forwardUnknown(exchange, chain); - } - ApiParam apiParam = ServerWebExchangeUtil.getApiParamForRestful(exchange, path); - this.doValidate(exchange, apiParam); - ForwardInfo forwardInfo = gatewayForwardChooser.getForwardInfo(exchange); - ServerWebExchange newExchange = ServerWebExchangeUtil.getForwardExchange(exchange, forwardInfo); + exchange.getAttributes().put(SopConstants.RESTFUL_REQUEST, true); + String restfulPath = ServerWebExchangeUtil.getRestfulPath(path); + ServerWebExchange newExchange = ServerWebExchangeUtil.getForwardExchange(exchange, restfulPath); return chain.filter(newExchange); } if (Objects.equals(path, indexPath)) { diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/LimitFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/LimitFilter.java index 740b6553..30af46d6 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/LimitFilter.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/filter/LimitFilter.java @@ -2,6 +2,7 @@ package com.gitee.sop.gatewaycommon.gateway.filter; import com.gitee.sop.gatewaycommon.bean.ApiConfig; import com.gitee.sop.gatewaycommon.bean.ConfigLimitDto; +import com.gitee.sop.gatewaycommon.bean.SopConstants; import com.gitee.sop.gatewaycommon.exception.ApiException; import com.gitee.sop.gatewaycommon.gateway.ServerWebExchangeUtil; import com.gitee.sop.gatewaycommon.limit.LimitManager; @@ -32,12 +33,18 @@ public class LimitFilter implements GlobalFilter, Ordered { @Override public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) { + if (exchange.getAttribute(SopConstants.RESTFUL_REQUEST) != null) { + return chain.filter(exchange); + } ApiConfig apiConfig = ApiConfig.getInstance(); // 限流功能未开启,直接返回 if (!apiConfig.isOpenLimit()) { return chain.filter(exchange); } ApiParam apiParam = ServerWebExchangeUtil.getApiParam(exchange); + if (apiParam == null) { + return chain.filter(exchange); + } ConfigLimitDto configLimitDto = this.findConfigLimitDto(apiConfig, apiParam, exchange); if (configLimitDto == null) { return chain.filter(exchange); diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/result/GatewayResultExecutor.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/result/GatewayResultExecutor.java index 03eab2c4..b745a3f5 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/result/GatewayResultExecutor.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/gateway/result/GatewayResultExecutor.java @@ -3,10 +3,10 @@ package com.gitee.sop.gatewaycommon.gateway.result; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import com.gitee.sop.gatewaycommon.bean.DefaultRouteInterceptorContext; -import com.gitee.sop.gatewaycommon.interceptor.RouteInterceptorContext; import com.gitee.sop.gatewaycommon.bean.SopConstants; import com.gitee.sop.gatewaycommon.exception.ApiException; import com.gitee.sop.gatewaycommon.gateway.ServerWebExchangeUtil; +import com.gitee.sop.gatewaycommon.interceptor.RouteInterceptorContext; import com.gitee.sop.gatewaycommon.message.Error; import com.gitee.sop.gatewaycommon.message.ErrorEnum; import com.gitee.sop.gatewaycommon.param.ApiParam; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ServiceGrayConfig.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/ServiceGrayConfig.java similarity index 91% rename from sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ServiceGrayConfig.java rename to sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/ServiceGrayConfig.java index 7aed5c38..911ccf96 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ServiceGrayConfig.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/ServiceGrayConfig.java @@ -1,4 +1,4 @@ -package com.gitee.sop.gatewaycommon.zuul.loadbalancer; +package com.gitee.sop.gatewaycommon.loadbalancer; import lombok.Data; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/SopPropertiesFactory.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/SopPropertiesFactory.java deleted file mode 100644 index 461a64b3..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/loadbalancer/SopPropertiesFactory.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.gitee.sop.gatewaycommon.loadbalancer; - -import com.gitee.sop.gatewaycommon.manager.EnvironmentKeys; -import com.netflix.loadbalancer.IRule; -import org.springframework.cloud.netflix.ribbon.PropertiesFactory; - -/** - * 自定义PropertiesFactory,用来动态添加LoadBalance规则 - * @author tanghc - */ -public class SopPropertiesFactory extends PropertiesFactory { - - /** - * 配置文件配置:.ribbon.NFLoadBalancerRuleClassName=com.gitee.sop.gateway.loadbalancer.EnvironmentServerChooser - * @param clazz - * @param name serviceId - * @return 返回class全限定名 - */ - @Override - public String getClassName(Class clazz, String name) { - if (clazz == IRule.class) { - return EnvironmentKeys.ZUUL_CUSTOM_RULE_CLASSNAME.getValue(); - } else { - return super.getClassName(clazz, name); - } - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/DefaultEnvGrayManager.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/DefaultEnvGrayManager.java index abf3ae4f..c42f961a 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/DefaultEnvGrayManager.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/DefaultEnvGrayManager.java @@ -1,6 +1,6 @@ package com.gitee.sop.gatewaycommon.manager; -import com.gitee.sop.gatewaycommon.zuul.loadbalancer.ServiceGrayConfig; +import com.gitee.sop.gatewaycommon.loadbalancer.ServiceGrayConfig; import com.google.common.collect.Maps; import java.util.Map; @@ -13,12 +13,12 @@ public class DefaultEnvGrayManager implements EnvGrayManager { /** * key:serviceId,服务对应的灰度配置 */ - private Map serviceGrayConfigMap = Maps.newConcurrentMap(); + private final Map serviceGrayConfigMap = Maps.newConcurrentMap(); /** * key:instanceId value:serviceId */ - private Map instanceIdServiceIdMap = Maps.newConcurrentMap(); + private final Map instanceIdServiceIdMap = Maps.newConcurrentMap(); @Override public void saveServiceGrayConfig(ServiceGrayConfig serviceGrayConfig) { diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvGrayManager.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvGrayManager.java index 54d36f59..e58c70b8 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvGrayManager.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvGrayManager.java @@ -1,7 +1,7 @@ package com.gitee.sop.gatewaycommon.manager; import com.gitee.sop.gatewaycommon.bean.BeanInitializer; -import com.gitee.sop.gatewaycommon.zuul.loadbalancer.ServiceGrayConfig; +import com.gitee.sop.gatewaycommon.loadbalancer.ServiceGrayConfig; /** * @author tanghc diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvironmentKeys.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvironmentKeys.java index 3fa1b20f..ea6f2bac 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvironmentKeys.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/manager/EnvironmentKeys.java @@ -1,28 +1,17 @@ package com.gitee.sop.gatewaycommon.manager; -import com.gitee.sop.gatewaycommon.zuul.loadbalancer.EnvironmentServerChooser; - public enum EnvironmentKeys { SPRING_PROFILES_ACTIVE("spring.profiles.active", "default"), /** * spring.application.name */ SPRING_APPLICATION_NAME("spring.application.name"), - /** - * 指定负载均衡规则类 - */ - ZUUL_CUSTOM_RULE_CLASSNAME("zuul.custom-rule-classname", EnvironmentServerChooser.class.getName()), /** * sign.urlencode=true,签名验证拼接字符串的value部分进行urlencode */ SIGN_URLENCODE("sign.urlencode"), - /** - * sop.restful.enable=true,开启传统web开发模式 - */ - SOP_RESTFUL_ENABLE("sop.restful.enable"), - /** * sop.restful.path=/xx ,指定请求前缀,默认/rest */ @@ -39,9 +28,11 @@ public enum EnvironmentKeys { /** * 预发布域名 */ - PRE_DOMAIN("pre.domain"); + PRE_DOMAIN("pre.domain"), + + ; - private String key; + private final String key; private String defaultValue; public String getKey() { diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/result/ResultExecutorForZuul.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/result/ResultExecutorForZuul.java deleted file mode 100644 index 12cbc89b..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/result/ResultExecutorForZuul.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.gitee.sop.gatewaycommon.result; - -import com.netflix.zuul.context.RequestContext; - -/** - * @author tanghc - */ -public interface ResultExecutorForZuul extends ResultExecutor { -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/ServiceRouteListener.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/ServiceRouteListener.java index c4db5311..b466312e 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/ServiceRouteListener.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/route/ServiceRouteListener.java @@ -3,9 +3,7 @@ package com.gitee.sop.gatewaycommon.route; import com.alibaba.fastjson.JSON; import com.gitee.sop.gatewaycommon.bean.InstanceDefinition; import com.gitee.sop.gatewaycommon.bean.ServiceRouteInfo; -import com.gitee.sop.gatewaycommon.bean.SopConstants; import com.gitee.sop.gatewaycommon.manager.BaseRouteCache; -import com.gitee.sop.gatewaycommon.manager.EnvironmentKeys; import lombok.extern.slf4j.Slf4j; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; @@ -46,7 +44,7 @@ public class ServiceRouteListener extends BaseServiceListener { String serviceName = instance.getServiceId(); String url = getRouteRequestUrl(instance); log.info("拉取路由配置,serviceId: {}, url: {}", serviceName, url); - ResponseEntity responseEntity = getRestTemplate().postForEntity(url, getHttpEntity(), String.class); + ResponseEntity responseEntity = getRestTemplate().getForEntity(url, String.class); if (responseEntity.getStatusCode() == HttpStatus.OK) { String body = responseEntity.getBody(); ServiceRouteInfo serviceRouteInfo = JSON.parseObject(body, ServiceRouteInfo.class); @@ -58,9 +56,6 @@ public class ServiceRouteListener extends BaseServiceListener { protected HttpEntity getHttpEntity() { HttpHeaders headers = new HttpHeaders(); - String restful = EnvironmentKeys.SOP_RESTFUL_ENABLE.getValue(); - boolean enableRestful = "true".equals(restful); - headers.add(HEADER_RESTFUL, String.valueOf(enableRestful)); return new HttpEntity<>(headers); } diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/util/RequestUtil.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/util/RequestUtil.java index a71d03bb..7abe5c31 100644 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/util/RequestUtil.java +++ b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/util/RequestUtil.java @@ -4,8 +4,6 @@ import com.alibaba.fastjson.JSON; import com.gitee.sop.gatewaycommon.bean.SopConstants; import com.gitee.sop.gatewaycommon.param.ApiUploadContext; import com.gitee.sop.gatewaycommon.param.UploadContext; -import com.gitee.sop.gatewaycommon.zuul.param.ZuulParameterUtil; -import com.netflix.zuul.http.HttpServletRequestWrapper; import lombok.Data; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.fileupload.FileItem; @@ -16,8 +14,6 @@ import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpHeaders; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; import org.springframework.http.server.reactive.ServerHttpRequest; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; @@ -121,9 +117,6 @@ public class RequestUtil { * @return 返回参数键值对 */ public static Map convertRequestParamsToMap(HttpServletRequest request) { - if (request instanceof HttpServletRequestWrapper) { - request = ((HttpServletRequestWrapper) request).getRequest(); - } Map paramMap = request.getParameterMap(); if (paramMap == null || paramMap.isEmpty()) { return Collections.emptyMap(); @@ -342,26 +335,6 @@ public class RequestUtil { } } - public static HttpServletRequest wrapRequest(HttpServletRequest request) { - if (request.getMethod().equalsIgnoreCase(HttpMethod.GET.name()) || - request instanceof StandardMultipartHttpServletRequest) { - return request; - } - HttpServletRequest wrapper = request; - String contentType = request.getContentType(); - MediaType mediaType = MediaType.valueOf(contentType); - if (MediaType.APPLICATION_JSON.includes(mediaType)) { - try { - String json = RequestUtil.getText(request); - byte[] data = json.getBytes(StandardCharsets.UTF_8); - wrapper = new ZuulParameterUtil.BodyDataHttpServletRequestWrapper(request, data); - } catch (IOException e) { - log.error("wrapRequest异常", e); - } - } - return wrapper; - } - @Data public static class UploadInfo { private Map uploadParams; diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/RequestContextUtil.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/RequestContextUtil.java deleted file mode 100644 index bea76c79..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/RequestContextUtil.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul; - -import com.netflix.util.Pair; -import com.netflix.zuul.context.RequestContext; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.HttpHeaders; - -import java.util.List; - -/** - * @author tanghc - */ -public class RequestContextUtil { - - /** - * 获取微服务端传递过来的header - * - * @param name header名 - * @return 返回value,没有返回null - */ - public static String getZuulResponseHeader(RequestContext requestContext, String name) { - List> zuulResponseHeaders = requestContext.getZuulResponseHeaders(); - return zuulResponseHeaders.stream() - .filter(pair -> StringUtils.containsIgnoreCase(pair.first(), name)) - .findFirst() - .map(Pair::second) - .orElse(null); - } - - /** - * 获取微服务端的content-type - * @return 返回content-type - */ - public static String getZuulContentType(RequestContext requestContext) { - return getZuulResponseHeader(requestContext, HttpHeaders.CONTENT_TYPE); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ValidateService.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ValidateService.java deleted file mode 100644 index 90111bd4..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ValidateService.java +++ /dev/null @@ -1,97 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.DefaultRouteInterceptorContext; -import com.gitee.sop.gatewaycommon.bean.SopConstants; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.param.ParamBuilder; -import com.gitee.sop.gatewaycommon.util.ResponseUtil; -import com.gitee.sop.gatewaycommon.util.RouteInterceptorUtil; -import com.gitee.sop.gatewaycommon.validate.Validator; -import com.netflix.zuul.context.RequestContext; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * 负责签名校验 - * @author tanghc - */ -@Slf4j -public class ValidateService { - - @Autowired - private ParamBuilder paramBuilder; - - @Autowired - private Validator validator; - - /** - * 校验操作 - * - * @param currentContext currentContext - * @param callback 校验后操作 - */ - public void validate(RequestContext currentContext, ValidateCallback callback) { - // 解析参数 - ApiParam param = ZuulContext.getApiParam(); - if (param == null) { - param = paramBuilder.build(currentContext); - ZuulContext.setApiParam(param); - } - doValidate(currentContext, param, callback); - } - - /** - * 签名校验 - * - * @param currentContext currentContext - */ - private void doValidate(RequestContext currentContext, ApiParam param, ValidateCallback callback) { - Exception error = null; - // 验证操作,这里有负责验证签名参数 - try { - validator.validate(param); - this.afterValidate(currentContext, param); - } catch (Exception e) { - error = e; - } - param.fitNameVersion(); - if (callback != null) { - if (error == null) { - callback.onSuccess(currentContext); - } else { - callback.onError(currentContext, param, error); - } - } - } - - private void afterValidate(RequestContext currentContext, ApiParam param) { - RouteInterceptorUtil.runPreRoute(currentContext, param, context -> { - DefaultRouteInterceptorContext defaultRouteInterceptorContext = (DefaultRouteInterceptorContext) context; - defaultRouteInterceptorContext.setRequestDataSize(currentContext.getRequest().getContentLengthLong()); - currentContext.set(SopConstants.CACHE_ROUTE_INTERCEPTOR_CONTEXT, context); - }); - } - - public interface ValidateCallback { - /** - * 校验成功触发 - * - * @param currentContext 上下文 - */ - void onSuccess(RequestContext currentContext); - - /** - * 校验失败触发 - * - * @param currentContext 上下文 - * @param param 参数 - * @param throwable 异常 - */ - default void onError(RequestContext currentContext, ApiParam param, Throwable throwable) { - log.error("验证失败,ip:{}, params:{}, errorMsg:{}", param.fetchIp(), param.toJSONString(), throwable.getMessage()); - String errorResult = ApiConfig.getInstance().getZuulResultExecutor().buildErrorResult(currentContext, throwable); - ResponseUtil.writeJson(currentContext.getResponse(), errorResult); - } - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ZuulContext.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ZuulContext.java deleted file mode 100644 index 6ad62646..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/ZuulContext.java +++ /dev/null @@ -1,137 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.netflix.zuul.context.RequestContext; - -import javax.servlet.ServletContext; -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import javax.servlet.http.HttpSession; -import java.util.Locale; - - -/** - * @author tanghc - */ -public class ZuulContext extends ApiContext { - - private static final String ATTR_PARAM = "zuul.common.api.param"; - - private static void setAttr(String name, Object val) { - HttpServletRequest request = getRequest(); - if (request != null) { - request.setAttribute(name, val); - } - } - - private static Object getAttr(String name) { - HttpServletRequest request = getRequest(); - if (request == null) { - return null; - } - return request.getAttribute(name); - } - - - /** - * 获取HttpServletRequest - * - * @return HttpServletRequest - */ - public static HttpServletRequest getRequest() { - return RequestContext.getCurrentContext().getRequest(); - } - - /** - * 返回默认的HttpServletRequest.getSession(); - * - * @return 没有返回null - */ - public static HttpSession getSession() { - HttpServletRequest req = getRequest(); - if (req == null) { - return null; - } else { - return req.getSession(); - } - } - - - /** - * 同getSessionId() - * - * @return 返回accessToken, 没有返回null - */ - public static String getAccessToken() { - return getSessionId(); - } - - - /** - * 获取登陆的token - * - * @return 没有返回null - */ - public static String getSessionId() { - ApiParam apiParam = getApiParam(); - if (apiParam == null) { - return null; - } - return apiParam.fetchAccessToken(); - } - - /** - * 获取本地化,从HttpServletRequest中获取,没有则返回Locale.SIMPLIFIED_CHINESE - * - * @return Locale - */ - public static Locale getLocale() { - HttpServletRequest req = getRequest(); - if (req == null) { - return Locale.SIMPLIFIED_CHINESE; - } - return req.getLocale(); - } - - public static void setApiParam(ApiParam apiParam) { - setAttr(ATTR_PARAM, apiParam); - } - - /** - * 获取系统参数 - * - * @return 返回ApiParam - */ - public static ApiParam getApiParam() { - return (ApiParam) getAttr(ATTR_PARAM); - } - - public static ApiConfig getApiConfig() { - return ApiConfig.getInstance(); - } - - public static void setApiConfig(ApiConfig apiConfig) { - ApiConfig.setInstance(apiConfig); - } - - - public static ServletContext getServletContext() { - ServletContext ctx = null; - HttpSession session = getSession(); - if (session != null) { - ctx = session.getServletContext(); - } - return ctx; - } - - /** - * 获取response - * - * @return 返回response - */ - public static HttpServletResponse getResponse() { - return RequestContext.getCurrentContext().getResponse(); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/AlipayZuulConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/AlipayZuulConfiguration.java deleted file mode 100644 index 3b07e6e8..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/AlipayZuulConfiguration.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.configuration; - -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.validate.alipay.AlipaySigner; - -/** - * 具备支付宝开放平台能力配置 https://docs.open.alipay.com/api - * - * @author tanghc - */ -public class AlipayZuulConfiguration extends BaseZuulConfiguration { - - static { - ApiContext.getApiConfig().setSigner(new AlipaySigner()); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/BaseZuulConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/BaseZuulConfiguration.java deleted file mode 100644 index 3f499c77..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/BaseZuulConfiguration.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.configuration; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.manager.AbstractConfiguration; -import com.gitee.sop.gatewaycommon.manager.RouteRepositoryContext; -import com.gitee.sop.gatewaycommon.param.ParamBuilder; -import com.gitee.sop.gatewaycommon.zuul.ValidateService; -import com.gitee.sop.gatewaycommon.zuul.controller.ConfigChannelController; -import com.gitee.sop.gatewaycommon.zuul.controller.ErrorLogController; -import com.gitee.sop.gatewaycommon.zuul.controller.ZuulErrorController; -import com.gitee.sop.gatewaycommon.zuul.controller.ZuulIndexController; -import com.gitee.sop.gatewaycommon.zuul.controller.ZuulMonitorController; -import com.gitee.sop.gatewaycommon.zuul.filter.ErrorFilter; -import com.gitee.sop.gatewaycommon.zuul.filter.FormBodyWrapperFilterExt; -import com.gitee.sop.gatewaycommon.zuul.filter.PostResultFilter; -import com.gitee.sop.gatewaycommon.zuul.filter.PreHttpServletRequestWrapperFilter; -import com.gitee.sop.gatewaycommon.zuul.filter.PreLimitFilter; -import com.gitee.sop.gatewaycommon.zuul.filter.PreParameterFormatterFilter; -import com.gitee.sop.gatewaycommon.zuul.filter.Servlet30WrapperFilterExt; -import com.gitee.sop.gatewaycommon.zuul.route.SopRouteLocator; -import com.gitee.sop.gatewaycommon.zuul.route.ZuulForwardChooser; -import com.gitee.sop.gatewaycommon.zuul.route.ZuulRouteCache; -import com.gitee.sop.gatewaycommon.zuul.route.ZuulRouteRepository; -import com.netflix.zuul.context.RequestContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.web.ServerProperties; -import org.springframework.cloud.netflix.zuul.filters.ProxyRequestHelper; -import org.springframework.cloud.netflix.zuul.filters.ZuulProperties; -import org.springframework.cloud.netflix.zuul.filters.pre.PreDecorationFilter; -import org.springframework.context.annotation.Bean; - -/** - * @author tanghc - */ -public class BaseZuulConfiguration extends AbstractConfiguration { - - @Autowired - protected ZuulProperties zuulProperties; - - @Autowired - protected ServerProperties server; - - @Bean - public ConfigChannelController configChannelController() { - return new ConfigChannelController(); - } - - @Bean - public ErrorLogController errorLogController() { - return new ErrorLogController(); - } - - @Bean - public ZuulIndexController zuulIndexController() { - return new ZuulIndexController(); - } - - @Bean - public ZuulMonitorController zuulMonitorController() { - return new ZuulMonitorController(); - } - - @Bean - @ConditionalOnMissingBean - ParamBuilder paramBuilder() { - return ApiConfig.getInstance().getZuulParamBuilder(); - } - - /** - * 路由仓库 - */ - @Bean - ZuulRouteRepository zuulRouteRepository() { - ZuulRouteRepository zuulRouteRepository = new ZuulRouteRepository(); - RouteRepositoryContext.setRouteRepository(zuulRouteRepository); - return zuulRouteRepository; - } - - - @Bean - PreHttpServletRequestWrapperFilter preHttpServletRequestWrapperFilter() { - return new PreHttpServletRequestWrapperFilter(); - } - - @Bean - FormBodyWrapperFilterExt formBodyWrapperFilterExt() { - return new FormBodyWrapperFilterExt(); - } - - @Bean - Servlet30WrapperFilterExt servlet30WrapperFilterExt() { - return new Servlet30WrapperFilterExt(); - } - - @Bean - SopRouteLocator sopRouteLocator() { - return new SopRouteLocator(); - } - - /** - * 选取路由 - * @param sopRouteLocator - * @param proxyRequestHelper - * @return - */ - @Bean - PreDecorationFilter preDecorationFilter(SopRouteLocator sopRouteLocator, ProxyRequestHelper proxyRequestHelper) { - // 自定义路由 - return new PreDecorationFilter(sopRouteLocator, - this.server.getServlet().getContextPath(), - this.zuulProperties, - proxyRequestHelper); - } - - - - /** - * 路由管理 - * @param zuulRouteRepository 路由仓库 - */ - @Bean - ZuulRouteCache zuulRouteCache(ZuulRouteRepository zuulRouteRepository) { - return new ZuulRouteCache(zuulRouteRepository); - } - - @Bean - ValidateService validateService() { - return new ValidateService(); - } - - @Bean - PreParameterFormatterFilter preParameterFormatterFilter() { - return new PreParameterFormatterFilter(); - } - - /** - * 开启限流 - */ - @Bean - PreLimitFilter preLimitFilter() { - return new PreLimitFilter(); - } - - /** - * 错误处理扩展 - */ - @Bean - ErrorFilter errorFilter() { - return new ErrorFilter(); - } - - /** - * 结果返回 - */ - @Bean - PostResultFilter postResultFilter() { - return new PostResultFilter(); - } - - - /** - * 统一错误处理 - */ - @Bean - ZuulErrorController zuulErrorController() { - return ApiContext.getApiConfig().getZuulErrorController(); - } - - @Bean - ZuulForwardChooser zuulForwardChooser() { - return new ZuulForwardChooser(); - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/TaobaoZuulConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/TaobaoZuulConfiguration.java deleted file mode 100644 index 356cd37b..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/TaobaoZuulConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.configuration; - -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.param.ParamNames; -import com.gitee.sop.gatewaycommon.validate.taobao.TaobaoSigner; - -/** - * 具备淘宝开放平台能力配置 - * 淘宝开放平台:http://open.taobao.com/doc.htm - * @author tanghc - */ -public class TaobaoZuulConfiguration extends BaseZuulConfiguration { - - static { - ParamNames.APP_KEY_NAME = "app_key"; - ParamNames.SIGN_TYPE_NAME = "sign_method"; - ParamNames.VERSION_NAME = "v"; - ParamNames.APP_AUTH_TOKEN_NAME = "session"; - - ApiContext.getApiConfig().setSigner(new TaobaoSigner()); - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/WebappZuulConfiguration.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/WebappZuulConfiguration.java deleted file mode 100644 index 1517226e..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/configuration/WebappZuulConfiguration.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.configuration; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.result.CustomDataNameBuilder; - -/** - * 支持传统webapp开发,没有签名验证 - * - * @author tanghc - */ -@Deprecated -public class WebappZuulConfiguration extends BaseZuulConfiguration { - - static { - ApiConfig.getInstance().setDataNameBuilder(new CustomDataNameBuilder()); - ApiConfig.getInstance().setShowReturnSign(false); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ConfigChannelController.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ConfigChannelController.java deleted file mode 100644 index 8dad0d85..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ConfigChannelController.java +++ /dev/null @@ -1,68 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.controller; - -import com.alibaba.fastjson.JSON; -import com.gitee.sop.gatewaycommon.bean.GatewayPushDTO; -import com.gitee.sop.gatewaycommon.bean.NacosConfigs; -import com.gitee.sop.gatewaycommon.bean.SpringContext; -import com.gitee.sop.gatewaycommon.manager.ChannelMsgProcessor; -import com.gitee.sop.gatewaycommon.manager.EnvGrayManager; -import com.gitee.sop.gatewaycommon.manager.IPBlacklistManager; -import com.gitee.sop.gatewaycommon.manager.IsvRoutePermissionManager; -import com.gitee.sop.gatewaycommon.manager.LimitConfigManager; -import com.gitee.sop.gatewaycommon.manager.RouteConfigManager; -import com.gitee.sop.gatewaycommon.secret.IsvManager; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * @author tanghc - */ -@Slf4j -@RestController -public class ConfigChannelController { - - private static Map> processorMap = new HashMap<>(16); - - static { - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_GRAY, EnvGrayManager.class); - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_IP_BLACKLIST, IPBlacklistManager.class); - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_ISV, IsvManager.class); - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_ROUTE_PERMISSION, IsvRoutePermissionManager.class); - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_LIMIT_CONFIG, LimitConfigManager.class); - processorMap.put(NacosConfigs.GROUP_CHANNEL + NacosConfigs.DATA_ID_ROUTE_CONFIG, RouteConfigManager.class); - } - - @Value("${sop.secret}") - private String secret; - - @PostMapping("/sop/configChannelMsg") - public String configChannel(HttpServletRequest request) throws IOException { - String requestJson = RequestUtil.getText(request); - String sign = request.getHeader("sign"); - try { - RequestUtil.checkResponseBody(requestJson, sign, secret); - } catch (Exception e) { - log.error("configChannelMsg错误", e); - return e.getMessage(); - } - GatewayPushDTO gatewayPushDTO = JSON.parseObject(requestJson, GatewayPushDTO.class); - ChannelMsgProcessor channelMsgProcessor = getChannelMsgProcessor(gatewayPushDTO); - channelMsgProcessor.process(gatewayPushDTO.getChannelMsg()); - return "ok"; - } - - private ChannelMsgProcessor getChannelMsgProcessor(GatewayPushDTO gatewayPushDTO) { - String key = gatewayPushDTO.getGroupId() + gatewayPushDTO.getDataId(); - Class aClass = processorMap.get(key); - return SpringContext.getBean(aClass); - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ErrorLogController.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ErrorLogController.java deleted file mode 100644 index c4907461..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ErrorLogController.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.controller; - -import com.gitee.sop.gatewaycommon.bean.BaseErrorLogController; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import java.util.Map; - -/** - * @author tanghc - */ -@RestController -public class ErrorLogController extends BaseErrorLogController { - - @Override - protected ApiParam getApiParam(HttpServletRequest request) { - Map params = RequestUtil.convertRequestParamsToMap(request); - return ApiParam.build(params); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulErrorController.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulErrorController.java deleted file mode 100644 index d49cdf09..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulErrorController.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.controller; - -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.result.ResultExecutor; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.web.servlet.error.ErrorController; -import org.springframework.web.bind.annotation.ExceptionHandler; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * zuul的异常处理 - * - * @author tanghc - */ -@Slf4j -@RestController -public class ZuulErrorController implements ErrorController { - - /** - * 错误最终会到这里来 - */ - @RequestMapping("/error") - public Object error(HttpServletRequest request, HttpServletResponse response) { - RequestContext ctx = RequestContext.getCurrentContext(); - if (ctx.getResponse() == null) { - ctx.setResponse(response); - } - Throwable throwable = ctx.getThrowable(); - log.error("zuul网关报错,URL:{}, status:{}, params:{}", - request.getRequestURL().toString() - , response.getStatus() - , ZuulContext.getApiParam() - , throwable); - RequestContext.getCurrentContext().setRequest(request); - return this.buildResult(throwable); - } - - protected Object buildResult(Throwable throwable) { - ResultExecutor resultExecutor = ApiContext.getApiConfig().getZuulResultExecutor(); - return resultExecutor.buildErrorResult(RequestContext.getCurrentContext(), throwable); - } - - @Override - public String getErrorPath() { - return "/error"; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulIndexController.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulIndexController.java deleted file mode 100644 index 4556f119..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulIndexController.java +++ /dev/null @@ -1,84 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.controller; - -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import com.gitee.sop.gatewaycommon.zuul.ValidateService; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.stereotype.Controller; -import org.springframework.web.bind.annotation.RequestMapping; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; - -/** - * zuul网关入口 - * - * @author tanghc - */ -@Slf4j -@Controller -public class ZuulIndexController { - - private static final String EMPTY_VERSION = ""; - - @Autowired - private ValidateService validateService; - - @Value("${zuul.servlet-path:/zuul}") - private String path; - - @Value("${sop.restful.path:/rest}") - private String restPath; - - /** - * 验证回调,可自定义实现接口 - */ - private ValidateService.ValidateCallback callback = (currentContext -> { - try { - currentContext.getRequest().getRequestDispatcher(path).forward(currentContext.getRequest(), currentContext.getResponse()); - } catch (Exception e) { - log.error("请求转发异常", e); - } - }); - - /** - * 网关入口 - * - * @param request request - * @param response response - */ - @RequestMapping("/") - public void index(HttpServletRequest request, HttpServletResponse response) { - RequestContext currentContext = RequestContext.getCurrentContext(); - currentContext.setRequest(RequestUtil.wrapRequest(request)); - currentContext.setResponse(response); - validateService.validate(currentContext, callback); - } - - /** - * restful入口 - * - * @param request request - * @param response response - */ - @RequestMapping("/rest/**") - public void rest(HttpServletRequest request, HttpServletResponse response) { - RequestContext currentContext = RequestContext.getCurrentContext(); - currentContext.setRequest(RequestUtil.wrapRequest(request)); - currentContext.setResponse(response); - - String url = request.getRequestURL().toString(); - int index = url.indexOf(restPath); - // 取/rest的后面部分 - String path = url.substring(index + restPath.length()); - ApiParam apiParam = ApiParam.createRestfulApiParam(path); - ZuulContext.setApiParam(apiParam); - - validateService.validate(currentContext, callback); - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulMonitorController.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulMonitorController.java deleted file mode 100644 index 009902c0..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/controller/ZuulMonitorController.java +++ /dev/null @@ -1,21 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.controller; - -import com.gitee.sop.gatewaycommon.support.BaseMonitorController; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import org.springframework.web.bind.annotation.RestController; - -import javax.servlet.http.HttpServletRequest; -import java.util.Map; - -/** - * @author tanghc - */ -@RestController -public class ZuulMonitorController extends BaseMonitorController { - @Override - protected ApiParam getApiParam(HttpServletRequest request) { - Map params = RequestUtil.convertRequestParamsToMap(request); - return ApiParam.build(params); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/BaseZuulFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/BaseZuulFilter.java deleted file mode 100644 index ac36a154..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/BaseZuulFilter.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.alibaba.fastjson.JSON; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author tanghc - */ -public abstract class BaseZuulFilter extends ZuulFilter { - - protected Logger log = LoggerFactory.getLogger(getClass()); - - public static final int HTTP_SERVLET_REQUEST_WRAPPER_FILTER_ORDER = -2000; - - public static final int SERVLET_30_WRAPPER_FILTER_ORDER = HTTP_SERVLET_REQUEST_WRAPPER_FILTER_ORDER + 1; - - public static final int FORM_BODY_WRAPPER_FILTER_ORDER = SERVLET_30_WRAPPER_FILTER_ORDER + 1; - - /** 签名验证过滤 */ - public static final int PRE_VALIDATE_FILTER_ORDER = -1000; - - /** 限流过滤 */ - public static final int PRE_LIMIT_FILTER_ORDER = -990; - - /** 参数格式化过滤器 */ - public static final int PRE_PARAMETER_FORMATTER_FILTER_ORDER = -980; - - /** 灰度发布过滤器 */ - public static final int PRE_ENV_GRAY_FILTER_ORDER = -970; - - private Integer filterOrder; - - /** - * 获取过滤器类型 - * @return 返回FilterType - * @see ZuulFilter#filterType() filterType() - */ - protected abstract FilterType getFilterType(); - - /** - * 获取过滤器顺序 - * @return 返回顺序,越小优先执行 - * @see ZuulFilter#filterOrder() filterOrder() - */ - protected abstract int getFilterOrder(); - - /** - * 执行run - * @param requestContext - * @return Some arbitrary artifact may be returned. Current implementation ignores it. - * @throws ZuulException - */ - protected abstract Object doRun(RequestContext requestContext) throws ZuulException; - - /** - * 设置过滤器顺序 - * - * @param filterOrder 顺序,值越小优先执行 - * @return 返回自身对象 - */ - public BaseZuulFilter order(int filterOrder) { - this.filterOrder = filterOrder; - return this; - } - - @Override - public int filterOrder() { - return filterOrder != null ? filterOrder : this.getFilterOrder(); - } - - @Override - public String filterType() { - return this.getFilterType().getType(); - } - - @Override - public boolean shouldFilter() { - return true; - } - - @Override - public Object run() throws ZuulException { - return this.doRun(RequestContext.getCurrentContext()); - } - - /** - * 过滤该请求,不往下级服务去转发请求,到此结束。并填充responseBody - * - * @param requestContext - * @param result - */ - public static void stopRouteAndReturn(RequestContext requestContext, Object result) { - requestContext.setSendZuulResponse(false); - requestContext.setResponseBody(JSON.toJSONString(result)); - } - - /** - * to classify a filter by type. Standard types in Zuul are "pre" for pre-routing filtering, - * "routeDefinition" for routing to an origin, "post" for post-routing filters, "error" for error handling. - * We also support a "static" type for static responses see StaticResponseFilter. - * Any filterType made be created or added and doRun by calling FilterProcessor.runFilters(type) - */ - public enum FilterType { - /** zuul过滤器pre类型 */ - PRE("pre"), - /** zuul过滤器route类型 */ - ROUTE("routeDefinition"), - /** zuul过滤器post类型 */ - POST("post"), - /** zuul过滤器error类型 */ - ERROR("error"), - /** zuul过滤器static类型 */ - STATIC("static"), - ; - - FilterType(String type) { - this.type = type; - } - - private String type; - - public String getType() { - return type; - } - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/ErrorFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/ErrorFilter.java deleted file mode 100644 index c5d0cd0d..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/ErrorFilter.java +++ /dev/null @@ -1,60 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.netflix.zuul.FilterProcessor; -import com.netflix.zuul.ZuulFilter; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.springframework.cloud.netflix.zuul.filters.post.SendErrorFilter; -import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; - -/** - * 处理来自post过滤器引起的异常 - * @author tanghc - */ -public class ErrorFilter extends SendErrorFilter { - - public static final String FAILED_FILTER = "failed.filter"; - - private int filterOrder = 10; - - public ErrorFilter() { - initFilterProcessor(); - } - - public void initFilterProcessor() { - FilterProcessor instance = FilterProcessor.getInstance(); - if (!(instance instanceof MyFilterProcessor)) { - FilterProcessor.setProcessor(new MyFilterProcessor()); - } - } - - @Override - public int filterOrder() { - return filterOrder; - } - - @Override - public boolean shouldFilter() { - // 判断:仅处理来自post过滤器引起的异常 - RequestContext ctx = RequestContext.getCurrentContext(); - ZuulFilter failedFilter = (ZuulFilter) ctx.get(FAILED_FILTER); - return failedFilter != null && failedFilter.filterType().equals(FilterConstants.POST_TYPE); - } - - public static class MyFilterProcessor extends FilterProcessor { - @Override - public Object processZuulFilter(ZuulFilter filter) throws ZuulException { - try { - return super.processZuulFilter(filter); - } catch (ZuulException e) { - RequestContext ctx = RequestContext.getCurrentContext(); - ctx.set(FAILED_FILTER, filter); - throw e; - } - } - } - - public void setFilterOrder(int filterOrder) { - this.filterOrder = filterOrder; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/FormBodyWrapperFilterExt.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/FormBodyWrapperFilterExt.java deleted file mode 100644 index 8091b7b2..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/FormBodyWrapperFilterExt.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import org.springframework.cloud.netflix.zuul.filters.pre.FormBodyWrapperFilter; - -/** - * @author tanghc - */ -public class FormBodyWrapperFilterExt extends FormBodyWrapperFilter { - @Override - public int filterOrder() { - return BaseZuulFilter.FORM_BODY_WRAPPER_FILTER_ORDER; - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PostResultFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PostResultFilter.java deleted file mode 100644 index bd2774dd..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PostResultFilter.java +++ /dev/null @@ -1,75 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.ApiContext; -import com.gitee.sop.gatewaycommon.bean.SopConstants; -import com.gitee.sop.gatewaycommon.result.ResultExecutor; -import com.gitee.sop.gatewaycommon.zuul.RequestContextUtil; -import com.netflix.util.Pair; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants; -import org.springframework.http.HttpHeaders; -import org.springframework.http.MediaType; - -import javax.servlet.http.HttpServletResponse; -import java.io.InputStream; - -/** - * 合并微服务结果,统一返回格式 - * - * @author tanghc - */ -public class PostResultFilter extends BaseZuulFilter { - - @Override - protected FilterType getFilterType() { - return FilterType.POST; - } - - @Override - protected int getFilterOrder() { - return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1; - } - - @Override - protected Object doRun(RequestContext requestContext) throws ZuulException { - HttpServletResponse response = requestContext.getResponse(); - if (response.isCommitted()) { - return null; - } - String contentType = RequestContextUtil.getZuulContentType(requestContext); - // 如果是文件下载直接返回 - if (StringUtils.containsIgnoreCase(contentType, MediaType.APPLICATION_OCTET_STREAM_VALUE)) { - return null; - } - ApiConfig apiConfig = ApiContext.getApiConfig(); - ResultExecutor resultExecutor = apiConfig.getZuulResultExecutor(); - String serviceResult = getServiceResponseBody(requestContext); - String finalResult = resultExecutor.mergeResult(requestContext, serviceResult); - requestContext.setResponseBody(finalResult); - requestContext.getZuulResponseHeaders().add(new Pair<>(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)); - return null; - } - - /** - * 获取微服务端返回的结果 - * - * @param requestContext RequestContext - * @return 返回结果 - */ - private String getServiceResponseBody(RequestContext requestContext) { - String serviceResult; - InputStream responseDataStream = requestContext.getResponseDataStream(); - try { - serviceResult = IOUtils.toString(responseDataStream, SopConstants.CHARSET_UTF8); - } catch (Exception e) { - log.error("业务方无数据返回", e); - serviceResult = SopConstants.EMPTY_JSON; - } - return serviceResult; - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreEnvGrayFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreEnvGrayFilter.java deleted file mode 100644 index cd00823f..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreEnvGrayFilter.java +++ /dev/null @@ -1,53 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.gitee.sop.gatewaycommon.bean.TargetRoute; -import com.gitee.sop.gatewaycommon.manager.EnvGrayManager; -import com.gitee.sop.gatewaycommon.manager.RouteRepositoryContext; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.param.ParamNames; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * 灰度发布判断,改变版本号 - * - * @author tanghc - * @deprecated - * @see com.gitee.sop.gatewaycommon.zuul.route.ZuulForwardChooser - */ -@Deprecated -public class PreEnvGrayFilter extends BaseZuulFilter { - - @Autowired - private EnvGrayManager envGrayManager; - - @Override - protected FilterType getFilterType() { - return FilterType.PRE; - } - - @Override - protected int getFilterOrder() { - return PRE_ENV_GRAY_FILTER_ORDER; - } - - @Override - protected Object doRun(RequestContext requestContext) throws ZuulException { - ApiParam apiParam = ZuulContext.getApiParam(); - String nameVersion = apiParam.fetchNameVersion(); - TargetRoute targetRoute = RouteRepositoryContext.getRouteRepository().get(nameVersion); - if (targetRoute == null) { - return null; - } - String serviceId = targetRoute.getServiceRouteInfo().fetchServiceIdLowerCase(); - // 如果服务在灰度阶段,返回一个灰度版本号 - String version = envGrayManager.getVersion(serviceId, nameVersion); - if (version != null && envGrayManager.containsKey(serviceId, apiParam.fetchAppKey())) { - requestContext.set(EnvGrayManager.ENV_GRAY, true); - requestContext.addZuulRequestHeader(ParamNames.HEADER_VERSION_NAME, version); - } - return null; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreHttpServletRequestWrapperFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreHttpServletRequestWrapperFilter.java deleted file mode 100644 index 3c1ed38a..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreHttpServletRequestWrapperFilter.java +++ /dev/null @@ -1,31 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import com.netflix.zuul.http.HttpServletRequestWrapper; - -import javax.servlet.http.HttpServletRequest; - -/** - * 包装一下Request,使得request.getInputStream()方法可以调用多次 - * @author tanghc - */ -public class PreHttpServletRequestWrapperFilter extends BaseZuulFilter { - @Override - protected FilterType getFilterType() { - return FilterType.PRE; - } - - @Override - protected int getFilterOrder() { - return HTTP_SERVLET_REQUEST_WRAPPER_FILTER_ORDER; - } - - @Override - protected Object doRun(RequestContext requestContext) throws ZuulException { - HttpServletRequest request = requestContext.getRequest(); - HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(request); - requestContext.setRequest(wrapper); - return null; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreLimitFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreLimitFilter.java deleted file mode 100644 index d00922ee..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreLimitFilter.java +++ /dev/null @@ -1,118 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.gitee.sop.gatewaycommon.bean.ApiConfig; -import com.gitee.sop.gatewaycommon.bean.ConfigLimitDto; -import com.gitee.sop.gatewaycommon.exception.ApiException; -import com.gitee.sop.gatewaycommon.limit.LimitManager; -import com.gitee.sop.gatewaycommon.limit.LimitType; -import com.gitee.sop.gatewaycommon.manager.LimitConfigManager; -import com.gitee.sop.gatewaycommon.message.ErrorEnum; -import com.gitee.sop.gatewaycommon.message.ErrorMeta; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.springframework.beans.factory.annotation.Autowired; - -import javax.servlet.http.HttpServletRequest; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; - -/** - * zuul限流过滤器 - * - * @author tanghc - */ -public class PreLimitFilter extends BaseZuulFilter { - - private static final ErrorMeta LIMIT_ERROR_META = ErrorEnum.ISV_REQUEST_LIMIT.getErrorMeta(); - - @Autowired - private LimitManager limitManager; - - @Autowired - private LimitConfigManager limitConfigManager; - - @Override - protected FilterType getFilterType() { - return FilterType.PRE; - } - - @Override - protected int getFilterOrder() { - return PRE_LIMIT_FILTER_ORDER; - } - - @Override - protected Object doRun(RequestContext requestContext) throws ZuulException { - ApiConfig apiConfig = ApiConfig.getInstance(); - // 限流功能未开启,直接返回 - if (!apiConfig.isOpenLimit()) { - return null; - } - ApiParam apiParam = ZuulContext.getApiParam(); - ConfigLimitDto configLimitDto = this.findConfigLimitDto(apiConfig, apiParam, requestContext.getRequest()); - if (configLimitDto == null) { - return null; - } - // 单个限流功能未开启 - if (configLimitDto.getLimitStatus() == ConfigLimitDto.LIMIT_STATUS_CLOSE) { - return null; - } - byte limitType = configLimitDto.getLimitType(); - // 如果是漏桶策略 - if (limitType == LimitType.LEAKY_BUCKET.getType()) { - boolean acquire = limitManager.acquire(configLimitDto); - // 被限流,返回错误信息 - if (!acquire) { - throw new ApiException(LIMIT_ERROR_META); - } - } else if (limitType == LimitType.TOKEN_BUCKET.getType()) { - limitManager.acquireToken(configLimitDto); - } - return null; - } - - protected ConfigLimitDto findConfigLimitDto(ApiConfig apiConfig, ApiParam apiParam, HttpServletRequest request) { - String routeId = apiParam.fetchNameVersion(); - String appKey = apiParam.fetchAppKey(); - String ip = RequestUtil.getIP(request); - - // 最多7种情况 - String[] limitKeys = new String[]{ - // 根据路由ID限流 - routeId, - // 根据appKey限流 - appKey, - // 根据路由ID + appKey限流 - routeId + appKey, - - // 根据ip限流 - ip, - // 根据ip+路由id限流 - ip + routeId, - // 根据ip+appKey限流 - ip + appKey, - // 根据ip+路由id+appKey限流 - ip + routeId + appKey, - }; - - List limitConfigList = new ArrayList<>(); - for (String limitKey : limitKeys) { - ConfigLimitDto configLimitDto = limitConfigManager.get(limitKey); - if (configLimitDto == null) { - continue; - } - if (configLimitDto.getLimitStatus().intValue() == ConfigLimitDto.LIMIT_STATUS_OPEN) { - limitConfigList.add(configLimitDto); - } - } - if (limitConfigList.isEmpty()) { - return null; - } - limitConfigList.sort(Comparator.comparing(ConfigLimitDto::getOrderIndex)); - return limitConfigList.get(0); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreParameterFormatterFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreParameterFormatterFilter.java deleted file mode 100644 index c58ec85c..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreParameterFormatterFilter.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.param.ParamNames; -import com.gitee.sop.gatewaycommon.param.ParameterFormatter; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.gitee.sop.gatewaycommon.zuul.param.ZuulParameterUtil; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import org.springframework.beans.factory.annotation.Autowired; - -/** - * 参数格式化过滤器,动态修改参数,此过滤器放在前面校验后面 - * - * @author tanghc - */ -public class PreParameterFormatterFilter extends BaseZuulFilter { - - @Autowired(required = false) - private ParameterFormatter parameterFormatter; - - @Override - protected FilterType getFilterType() { - return FilterType.PRE; - } - - @Override - protected int getFilterOrder() { - return PRE_PARAMETER_FORMATTER_FILTER_ORDER; - } - - @Override - protected Object doRun(RequestContext requestContext) throws ZuulException { - ApiParam apiParam = ZuulContext.getApiParam(); - // 校验成功后进行参数转换 - if (parameterFormatter != null) { - ZuulParameterUtil.format(apiParam, parameterFormatter::format); - requestContext.addZuulRequestHeader(ParamNames.HEADER_VERSION_NAME, apiParam.fetchVersion()); - } - return null; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreValidateFilter.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreValidateFilter.java deleted file mode 100644 index b72a6abf..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/PreValidateFilter.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import com.netflix.zuul.context.RequestContext; - -/** - * 校验工作转移到了 com.gitee.sop.gateway.controller.RedirectController - *

- * 将校验工作提前,如果在zuul过滤器中校验,抛出异常将会打印非常多的日志,并且无法实现自定义返回结果。 - * @deprecated see {@link com.gitee.sop.gatewaycommon.zuul.ValidateService} - * @author tanghc - */ -@Deprecated -public class PreValidateFilter extends BaseZuulFilter { - - @Override - protected FilterType getFilterType() { - return FilterType.PRE; - } - - @Override - protected int getFilterOrder() { - return PRE_VALIDATE_FILTER_ORDER; - } - - @Override - protected Object doRun(RequestContext requestContext) { - return null; - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/Servlet30WrapperFilterExt.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/Servlet30WrapperFilterExt.java deleted file mode 100644 index 791eedf8..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/filter/Servlet30WrapperFilterExt.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.filter; - -import org.springframework.cloud.netflix.zuul.filters.pre.Servlet30WrapperFilter; - -/** - * @author tanghc - */ -public class Servlet30WrapperFilterExt extends Servlet30WrapperFilter { - @Override - public int filterOrder() { - return BaseZuulFilter.SERVLET_30_WRAPPER_FILTER_ORDER; - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/EnvironmentServerChooser.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/EnvironmentServerChooser.java deleted file mode 100644 index a9a6c477..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/EnvironmentServerChooser.java +++ /dev/null @@ -1,55 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.loadbalancer; - -import com.gitee.sop.gatewaycommon.loadbalancer.ServerChooserContext; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.google.common.base.Optional; -import com.netflix.loadbalancer.Server; -import com.netflix.loadbalancer.ZoneAvoidanceRule; -import com.netflix.zuul.context.RequestContext; -import lombok.extern.slf4j.Slf4j; - -import javax.servlet.http.HttpServletRequest; -import java.util.List; - -/** - * 预发布、灰度环境选择,参考自:https://segmentfault.com/a/1190000017412946 - * - * @author tanghc - */ -@Slf4j -public class EnvironmentServerChooser extends ZoneAvoidanceRule implements ServerChooserContext { - - private ZuulLoadBalanceServerChooser loadBalanceServerChooser = new ZuulLoadBalanceServerChooser(); - - @Override - public String getHost(HttpServletRequest request) { - return request.getServerName(); - } - - @Override - public ApiParam getApiParam(HttpServletRequest request) { - return ZuulContext.getApiParam(); - } - - @Override - public Server choose(Object key) { - return loadBalanceServerChooser.choose( - String.valueOf(key) - , RequestContext.getCurrentContext().getRequest() - , getLoadBalancer() - , () -> super.choose(key) - , (servers) -> this.doChoose(servers, key) - ); - } - - protected Server doChoose(List servers, Object key) { - Optional server = getPredicate().chooseRoundRobinAfterFiltering(servers, key); - if (server.isPresent()) { - return server.get(); - } else { - return null; - } - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ZuulLoadBalanceServerChooser.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ZuulLoadBalanceServerChooser.java deleted file mode 100644 index b1046ee9..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/loadbalancer/ZuulLoadBalanceServerChooser.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.loadbalancer; - -import com.gitee.sop.gatewaycommon.loadbalancer.LoadBalanceServerChooser; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.loadbalancer.Server; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author tanghc - */ -public class ZuulLoadBalanceServerChooser extends LoadBalanceServerChooser { - - @Override - public String getHost(HttpServletRequest request) { - return request.getServerName(); - } - - @Override - public ApiParam getApiParam(HttpServletRequest request) { - return ZuulContext.getApiParam(); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParamBuilder.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParamBuilder.java deleted file mode 100644 index 458114b6..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParamBuilder.java +++ /dev/null @@ -1,67 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.param; - -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.param.BaseParamBuilder; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import com.netflix.zuul.context.RequestContext; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.fileupload.servlet.ServletFileUpload; -import org.apache.commons.lang3.StringUtils; -import org.springframework.http.MediaType; - -import javax.servlet.http.HttpServletRequest; -import java.util.Map; - -/** - * 参数解析默认实现 - * - * @author tanghc - */ -@Slf4j -public class ZuulParamBuilder extends BaseParamBuilder { - - private static final String GET = "get"; - - @Override - public ApiParam buildRequestParams(RequestContext ctx) { - HttpServletRequest request = ctx.getRequest(); - Map params; - ApiParam apiParam = new ApiParam(); - if (GET.equalsIgnoreCase(request.getMethod())) { - params = RequestUtil.convertRequestParamsToMap(request); - } else { - String contentType = request.getContentType(); - if (contentType == null) { - contentType = ""; - } - contentType = contentType.toLowerCase(); - // json或者纯文本形式 - if (StringUtils.containsAny(contentType, MediaType.APPLICATION_JSON_VALUE, MediaType.TEXT_PLAIN_VALUE)) { - params = RequestUtil.convertJsonRequestToMap(request); - } else if (ServletFileUpload.isMultipartContent(request)) { - RequestUtil.UploadInfo uploadInfo = RequestUtil.getUploadInfo(request); - params = uploadInfo.getUploadParams(); - apiParam.setUploadContext(uploadInfo.getUploadContext()); - } else { - params = RequestUtil.convertRequestParamsToMap(request); - } - } - apiParam.putAll(params); - return apiParam; - } - - @Override - public String getIP(RequestContext ctx) { - return RequestUtil.getIP(ctx.getRequest()); - } - - @Override - public void setVersionInHeader(RequestContext ctx, String headerName, String version) { - ctx.addZuulRequestHeader(headerName, version); - } - - @Override - protected void processApiParam(ApiParam apiParam, RequestContext ctx) { - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParameterUtil.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParameterUtil.java deleted file mode 100644 index 16af5225..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/param/ZuulParameterUtil.java +++ /dev/null @@ -1,141 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.param; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.gatewaycommon.manager.EnvironmentKeys; -import com.gitee.sop.gatewaycommon.param.FormHttpOutputMessage; -import com.gitee.sop.gatewaycommon.util.RequestUtil; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.http.HttpServletRequestWrapper; -import com.netflix.zuul.http.ServletInputStreamWrapper; -import lombok.extern.slf4j.Slf4j; -import org.apache.commons.lang.StringUtils; -import org.springframework.cloud.netflix.zuul.util.RequestContentDataExtractor; -import org.springframework.http.HttpMethod; -import org.springframework.http.MediaType; -import org.springframework.http.converter.FormHttpMessageConverter; -import org.springframework.util.MultiValueMap; -import org.springframework.web.multipart.MultipartHttpServletRequest; -import org.springframework.web.multipart.commons.CommonsMultipartResolver; - -import javax.servlet.ServletInputStream; -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -/** - * zuul参数工具 - * @author tanghc - */ -@Slf4j -public class ZuulParameterUtil { - - private static FormHttpMessageConverter formHttpMessageConverter = new FormHttpMessageConverter(); - - /** - * 格式化参数 - * @param apiParam 请求的参数 - * @param consumer 修改参数 - * @param 参数类型 - */ - public static > void format(T apiParam, Consumer consumer) { - String restfulEnableValue = EnvironmentKeys.SOP_RESTFUL_ENABLE.getValue(); - // restful请求不支持动态修改参数 - if ("true".equals(restfulEnableValue)) { - return; - } - RequestContext requestContext = RequestContext.getCurrentContext(); - consumer.accept(apiParam); - HttpServletRequest request = requestContext.getRequest(); - String contentType = request.getContentType(); - if (StringUtils.containsIgnoreCase(contentType, MediaType.APPLICATION_JSON_VALUE)) { - String json = (apiParam instanceof JSONObject) ? - ((JSONObject) apiParam).toJSONString() - : JSON.toJSONString(apiParam); - byte[] bytes = json.getBytes(StandardCharsets.UTF_8); - requestContext.setRequest(new BodyDataHttpServletRequestWrapper(request, bytes)); - } else if(StringUtils.containsIgnoreCase(contentType, MediaType.APPLICATION_FORM_URLENCODED_VALUE)) { - String paramsStr = RequestUtil.convertMapToQueryString(apiParam); - byte[] data = paramsStr.getBytes(StandardCharsets.UTF_8); - requestContext.setRequest(new BodyDataHttpServletRequestWrapper(request, data)); - } else if(RequestUtil.isMultipart(request)) { - FormHttpOutputMessage outputMessage = new FormHttpOutputMessage(); - try { - // 转成MultipartRequest - if (!(request instanceof MultipartHttpServletRequest)) { - CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getServletContext()); - request = commonsMultipartResolver.resolveMultipart(request); - } - // 重写新的值 - MultiValueMap builder = RequestContentDataExtractor.extract(request); - for (Map.Entry entry : apiParam.entrySet()) { - Object value = entry.getValue(); - if (value instanceof List) { - builder.put(entry.getKey(), (List)value); - } else { - builder.put(entry.getKey(), Collections.singletonList(String.valueOf(value))); - } - } - MediaType mediaType = MediaType.valueOf(request.getContentType()); - // 将字段以及上传文件重写写入到流中 - formHttpMessageConverter.write(builder, mediaType, outputMessage); - // 获取新的上传文件流 - byte[] data = outputMessage.getInput(); - - requestContext.setRequest(new BodyDataHttpServletRequestWrapper(request, data)); - // 必须要重新指定content-type,因为此时的boundary已经发生改变 - requestContext.getZuulRequestHeaders().put("content-type", outputMessage.getHeaders().getContentType().toString()); - } catch (Exception e) { - log.error("修改上传文件请求参数失败, apiParam:{}", apiParam, e); - } - } else if(HttpMethod.GET.name().equalsIgnoreCase(request.getMethod())) { - Map> newParams = new HashMap<>(apiParam.size() * 2); - for (Map.Entry entry : apiParam.entrySet()) { - Object value = entry.getValue(); - if (value instanceof List) { - List valueList = ((List) value).stream().map(String::valueOf).collect(Collectors.toList()); - newParams.put(entry.getKey(), valueList); - } else { - newParams.put(entry.getKey(), Collections.singletonList(String.valueOf(value))); - } - } - requestContext.setRequestQueryParams(newParams); - } - } - - public static class BodyDataHttpServletRequestWrapper extends HttpServletRequestWrapper { - private byte[] data; - - public BodyDataHttpServletRequestWrapper(HttpServletRequest request, byte[] data) { - super(request); - this.data = data; - } - - @Override - public ServletInputStream getInputStream() throws IOException { - return new ServletInputStreamWrapper(data); - } - - @Override - public byte[] getContentData() { - return data; - } - - @Override - public int getContentLength() { - return data.length; - } - - @Override - public long getContentLengthLong() { - return data.length; - } - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/result/ZuulResultExecutor.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/result/ZuulResultExecutor.java deleted file mode 100644 index 596e7984..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/result/ZuulResultExecutor.java +++ /dev/null @@ -1,115 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.result; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.gatewaycommon.interceptor.RouteInterceptorContext; -import com.gitee.sop.gatewaycommon.bean.SopConstants; -import com.gitee.sop.gatewaycommon.exception.ApiException; -import com.gitee.sop.gatewaycommon.message.Error; -import com.gitee.sop.gatewaycommon.message.ErrorEnum; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.result.BaseExecutorAdapter; -import com.gitee.sop.gatewaycommon.result.ResultExecutorForZuul; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.util.Pair; -import com.netflix.zuul.context.RequestContext; -import com.netflix.zuul.exception.ZuulException; -import lombok.extern.slf4j.Slf4j; -import org.springframework.util.StringUtils; -import org.springframework.web.util.UriUtils; - -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Locale; -import java.util.function.Consumer; - -/** - * @author tanghc - */ -@Slf4j -public class ZuulResultExecutor extends BaseExecutorAdapter implements ResultExecutorForZuul { - - @Override - public int getResponseStatus(RequestContext requestContext) { - List> bizHeaders = requestContext.getZuulResponseHeaders(); - - return bizHeaders.stream() - .filter(header -> SopConstants.X_SERVICE_ERROR_CODE.equals(header.first())) - .map(header -> Integer.valueOf(header.second())) - .findFirst() - .orElse(requestContext.getResponseStatusCode()); - } - - @Override - public String getResponseErrorMessage(RequestContext requestContext) { - String errorMsg = getHeader(requestContext, SopConstants.X_SERVICE_ERROR_MESSAGE, (index)->{ - if (index > -1) { - requestContext.getZuulResponseHeaders().remove(index); - } - }); - if (StringUtils.hasText(errorMsg)) { - errorMsg = UriUtils.decode(errorMsg, StandardCharsets.UTF_8); - } - return errorMsg; - } - - @Override - public ApiParam getApiParam(RequestContext requestContext) { - return ZuulContext.getApiParam(); - } - - @Override - protected Locale getLocale(RequestContext requestContext) { - return requestContext.getRequest().getLocale(); - } - - @Override - protected RouteInterceptorContext getRouteInterceptorContext(RequestContext requestContext) { - return (RouteInterceptorContext) requestContext.get(SopConstants.CACHE_ROUTE_INTERCEPTOR_CONTEXT); - } - - @Override - public String buildErrorResult(RequestContext requestContext, Throwable throwable) { - Locale locale = getLocale(requestContext); - Error error = getError(locale, throwable); - return isMergeResult(requestContext) ? this.merge(requestContext, (JSONObject) JSON.toJSON(error)) - : JSON.toJSONString(error); - } - - public static Error getError(Locale locale, Throwable throwable) { - Error error = null; - if (throwable instanceof ZuulException) { - ZuulException ex = (ZuulException) throwable; - Throwable cause = ex.getCause(); - if (cause instanceof ApiException) { - ApiException apiException = (ApiException) cause; - error = apiException.getError(locale); - } - } else if (throwable instanceof ApiException) { - ApiException apiException = (ApiException) throwable; - error = apiException.getError(locale); - } - if (error == null) { - error = ErrorEnum.ISP_UNKNOWN_ERROR.getErrorMeta().getError(locale); - } - return error; - } - - private String getHeader(RequestContext requestContext, String name, Consumer after) { - List> bizHeaders = requestContext.getZuulResponseHeaders(); - int index = -1; - String value = null; - for (int i = 0; i < bizHeaders.size(); i++) { - Pair header = bizHeaders.get(i); - if (name.equals(header.first())) { - value = header.second(); - index = i; - break; - } - } - if (after != null) { - after.accept(index); - } - return value; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/SopRouteLocator.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/SopRouteLocator.java deleted file mode 100644 index 34788f4e..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/SopRouteLocator.java +++ /dev/null @@ -1,63 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.route; - -import com.gitee.sop.gatewaycommon.bean.AbstractTargetRoute; -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.route.ForwardInfo; -import com.gitee.sop.gatewaycommon.param.ParamNames; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.cloud.netflix.zuul.filters.RouteLocator; -import org.springframework.core.Ordered; - -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -/** - * 路由定位 - * - * @author tanghc - */ -public class SopRouteLocator implements RouteLocator, Ordered { - - @Autowired - private ZuulRouteRepository zuulRouteRepository; - - @Autowired - private ZuulForwardChooser zuulForwardChooser; - - @Override - public Collection getIgnoredPaths() { - return Collections.emptyList(); - } - - @Override - public List getRoutes() { - return zuulRouteRepository.getAll() - .parallelStream() - .map(AbstractTargetRoute::getTargetRouteDefinition) - .collect(Collectors.toList()); - } - - /** - * 这里决定使用哪个路由 - * - * @param path 当前请求路径 - * @return 返回跳转的路由 - */ - @Override - public Route getMatchingRoute(String path) { - ForwardInfo forwardInfo = zuulForwardChooser.getForwardInfo(RequestContext.getCurrentContext()); - String version = forwardInfo.getVersion(); - RequestContext.getCurrentContext().addZuulRequestHeader(ParamNames.HEADER_VERSION_NAME, version); - return (Route)forwardInfo.getTargetRoute().getTargetRouteDefinition(); - } - - @Override - public int getOrder() { - return 0; - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulForwardChooser.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulForwardChooser.java deleted file mode 100644 index 625d129f..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulForwardChooser.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.route; - -import com.gitee.sop.gatewaycommon.param.ApiParam; -import com.gitee.sop.gatewaycommon.route.BaseForwardChooser; -import com.gitee.sop.gatewaycommon.zuul.ZuulContext; -import com.netflix.zuul.context.RequestContext; - -/** - * @author tanghc - */ -public class ZuulForwardChooser extends BaseForwardChooser { - - @Override - public ApiParam getApiParam(RequestContext requestContext) { - return ZuulContext.getApiParam(); - } - -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteCache.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteCache.java deleted file mode 100644 index df6c64b7..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteCache.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.route; - -import com.gitee.sop.gatewaycommon.bean.RouteDefinition; -import com.gitee.sop.gatewaycommon.bean.ServiceRouteInfo; -import com.gitee.sop.gatewaycommon.manager.BaseRouteCache; -import com.gitee.sop.gatewaycommon.manager.RouteRepository; -import com.gitee.sop.gatewaycommon.util.RouteUtil; -import org.springframework.cloud.netflix.zuul.filters.Route; - -/** - * @author tanghc - */ -public class ZuulRouteCache extends BaseRouteCache { - - /** 路由重试 */ - private static final boolean RETRYABLE = true; - - public ZuulRouteCache(RouteRepository routeRepository) { - super(routeRepository); - } - - @Override - protected ZuulTargetRoute buildTargetRoute(ServiceRouteInfo serviceRouteInfo, RouteDefinition gatewayRouteDefinition) { - Route route = new Route( - gatewayRouteDefinition.getId() - , gatewayRouteDefinition.getPath() - , RouteUtil.getZuulLocation(gatewayRouteDefinition.getUri()) - , "" - , RETRYABLE - , null - ); - return new ZuulTargetRoute(serviceRouteInfo, gatewayRouteDefinition, route); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteRepository.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteRepository.java deleted file mode 100644 index 632cdb83..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulRouteRepository.java +++ /dev/null @@ -1,98 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.route; - -import com.gitee.sop.gatewaycommon.manager.RouteRepository; -import org.springframework.cloud.netflix.zuul.filters.Route; -import org.springframework.util.AntPathMatcher; -import org.springframework.util.PathMatcher; - -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.stream.Collectors; - -/** - * 本地存放路由内容的地方 - * - * @author tanghc - */ -public class ZuulRouteRepository implements RouteRepository { - - private final PathMatcher pathMatcher = new AntPathMatcher(); - - /** - * key:nameVersion - */ - private static final Map nameVersionTargetRouteMap = new ConcurrentHashMap<>(128); - - @Override - public ZuulTargetRoute get(String id) { - if (id == null) { - return null; - } - ZuulTargetRoute zuulTargetRoute = nameVersionTargetRouteMap.get(id); - if (zuulTargetRoute != null) { - return zuulTargetRoute; - } - for (Map.Entry entry : nameVersionTargetRouteMap.entrySet()) { - String pattern = entry.getKey(); - if (this.pathMatcher.match(pattern, id)) { - return clone(id, entry.getValue()); - } - } - return null; - } - - private ZuulTargetRoute clone(String path, ZuulTargetRoute zuulTargetRoute) { - Route targetRouteDefinition = zuulTargetRoute.getTargetRouteDefinition(); - String prefix = "/" + zuulTargetRoute.getServiceRouteInfo().getServiceId(); - if (path.startsWith(prefix)) { - path = path.substring(prefix.length()); - } - Route route = new Route( - targetRouteDefinition.getId() - ,path - ,targetRouteDefinition.getLocation() - ,targetRouteDefinition.getPrefix() - ,targetRouteDefinition.getRetryable() - , null - ); - return new ZuulTargetRoute(zuulTargetRoute.getServiceRouteInfo() - , zuulTargetRoute.getRouteDefinition() - , route); - } - - @Override - public Collection getAll() { - return nameVersionTargetRouteMap.values(); - } - - @Override - public String add(ZuulTargetRoute targetRoute) { - nameVersionTargetRouteMap.put(targetRoute.getRouteDefinition().getId(), targetRoute); - return targetRoute.getRouteDefinition().getId(); - } - - @Override - public void update(ZuulTargetRoute targetRoute) { - nameVersionTargetRouteMap.put(targetRoute.getRouteDefinition().getId(), targetRoute); - } - - @Override - public void deleteAll(String serviceId) { - Collection values = nameVersionTargetRouteMap.values(); - List idList = values.stream() - .filter(zuulTargetRoute -> zuulTargetRoute.getServiceRouteInfo().getServiceId().equalsIgnoreCase(serviceId)) - .map(zuulTargetRoute -> zuulTargetRoute.getRouteDefinition().getId()) - .collect(Collectors.toList()); - - for (String id : idList) { - this.delete(id); - } - } - - @Override - public void delete(String id) { - nameVersionTargetRouteMap.remove(id); - } -} diff --git a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulTargetRoute.java b/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulTargetRoute.java deleted file mode 100644 index 5713a11d..00000000 --- a/sop-common/sop-gateway-common/src/main/java/com/gitee/sop/gatewaycommon/zuul/route/ZuulTargetRoute.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.gitee.sop.gatewaycommon.zuul.route; - -import com.gitee.sop.gatewaycommon.bean.AbstractTargetRoute; -import com.gitee.sop.gatewaycommon.bean.RouteDefinition; -import com.gitee.sop.gatewaycommon.bean.ServiceRouteInfo; -import lombok.Getter; -import org.springframework.cloud.netflix.zuul.filters.Route; - -/** - * @author tanghc - */ -@Getter -public class ZuulTargetRoute extends AbstractTargetRoute { - - public ZuulTargetRoute(ServiceRouteInfo serviceRouteInfo, RouteDefinition routeDefinition, Route targetRoute) { - super(serviceRouteInfo, routeDefinition, targetRoute); - } -} diff --git a/sop-common/sop-gateway-common/src/main/resources/sop-bridge.properties b/sop-common/sop-gateway-common/src/main/resources/sop-bridge.properties new file mode 100644 index 00000000..0535c7b5 --- /dev/null +++ b/sop-common/sop-gateway-common/src/main/resources/sop-bridge.properties @@ -0,0 +1,39 @@ +# 固定不变,不能改 +spring.application.name=sop-gateway +# 不用改,如果要改,请全局替换修改 +sop.secret=MZZOUSTua6LzApIWXCwEgbBmxSzpzC + +# 网关入口 +sop.gateway-index-path=/ + +# nacos cloud配置 +spring.cloud.nacos.discovery.server-addr=${register.url} + +# 数据库配置 +spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver +spring.datasource.url=jdbc:mysql://${mysql.host}/sop?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&serverTimezone=Asia/Shanghai +spring.datasource.username=${mysql.username} +spring.datasource.password=${mysql.password} + +# https://blog.csdn.net/qq_36872046/article/details/81058045 +# 路由转发超时时间,毫秒,默认值1000,详见:RibbonClientConfiguration.DEFAULT_READ_TIMEOUT。 +# 如果微服务端 处理时间过长,会导致ribbon read超时,解决办法将这个值调大一点 +ribbon.ReadTimeout=2000 +# 设置为true(默认false),则所有请求都重试,默认只支持get请求重试 +# 请谨慎设置,因为post请求大多都是写入请求,如果要支持重试,确保服务的幂等性 +ribbon.OkToRetryOnAllOperations=false + +spring.cloud.gateway.discovery.locator.lower-case-service-id=true +spring.cloud.gateway.discovery.locator.enabled=true + +# 不用改 +mybatis.fill.com.gitee.fastmybatis.core.support.DateFillInsert=gmt_create +mybatis.fill.com.gitee.fastmybatis.core.support.DateFillUpdate=gmt_modified + +# 文件上传配置 +spring.servlet.multipart.enabled=true +# 这里设置大一点没关系,真实大小由upload.max-file-size控制 +spring.servlet.multipart.max-file-size=50MB + +# 允许上传文件大小,不能超过这个值,单位:B,KB,MB +upload.max-file-size=2MB \ No newline at end of file diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiMapping.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiMapping.java deleted file mode 100644 index db9b9af8..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiMapping.java +++ /dev/null @@ -1,92 +0,0 @@ -package com.gitee.sop.servercommon.annotation; - -import org.springframework.core.annotation.AliasFor; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; - -import java.lang.annotation.Documented; -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -/** - * 接口申明注解,使用方式同RequestMapping一样,多了一个版本号属性, - * 用了此注解具备开放平台接口提供能力。 - * @author tanghc - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@RequestMapping -public @interface ApiMapping { - - // ------------ 自定义属性 ------------ - - /** - * 版本号,默认版本号是""
- * 改默认版本号:ServiceConfig.getInstance().setDefaultVersion("1.0"); - */ - String version() default ""; - - /** - * 忽略验证,业务参数除外 - */ - boolean ignoreValidate() default false; - - /** - * 告诉网关是否对结果进行合并,默认合并。设置为false,客户端将直接收到微服务端的结果。 - */ - boolean mergeResult() default true; - - /** - * 指定接口是否需要授权才能访问,可在admin中进行修改 - */ - boolean permission() default false; - - /** - * 是否需要appAuthToken,设置为true,网关端会校验token是否存在 - */ - boolean needToken() default false; - - // ------------ 自定义属性 end ------------ - - - - // ============ 以下是springmvc自带的属性 ============ - - /** - * 接口名 - * Alias for {@link RequestMapping#value}. - */ - @AliasFor(annotation = RequestMapping.class) - String[] value() default {}; - - - @AliasFor(annotation = RequestMapping.class) - RequestMethod[] method() default {}; - - /** - * Alias for {@link RequestMapping#params}. - */ - @AliasFor(annotation = RequestMapping.class) - String[] params() default {}; - - /** - * Alias for {@link RequestMapping#headers}. - */ - @AliasFor(annotation = RequestMapping.class) - String[] headers() default {}; - - /** - * Alias for {@link RequestMapping#consumes}. - */ - @AliasFor(annotation = RequestMapping.class) - String[] consumes() default {}; - - /** - * Alias for {@link RequestMapping#produces}. - */ - @AliasFor(annotation = RequestMapping.class) - String[] produces() default {}; -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiAbility.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/Open.java similarity index 73% rename from sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiAbility.java rename to sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/Open.java index 9283a3d6..661471fe 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/ApiAbility.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/annotation/Open.java @@ -7,17 +7,21 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * 设置接口能力。 - * 如果想把已经存在的接口开放出去,可用此注解。
- * 作用于Controller类上或方法上。如果作用在类上,则类中的所有方法将具备开放平台接口提供能力。 * @author tanghc */ -@Target({ElementType.METHOD, ElementType.TYPE}) +@Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) @Documented -public @interface ApiAbility { +public @interface Open { + + /** + * 接口名,如:member.user.get + */ + String value(); + /** - * 版本号,如:1.0 + * 版本号,默认版本号是""
+ * 改默认版本号:ServiceConfig.getInstance().setDefaultVersion("1.0"); */ String version() default ""; diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContext.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContext.java deleted file mode 100644 index b3f2d3d3..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContext.java +++ /dev/null @@ -1,108 +0,0 @@ -package com.gitee.sop.servercommon.bean; - -import java.util.Date; - -/** - * 获取开放平台请求参数。 - * 可当做接口方法参数,泛型参数填业务参数类,如: - *

- * @ApiMapping(value = "alipay.goods.get")
- * public Goods getGoods(OpenRequest<GoodsParam> openRequest){...} 
- *
- * 可通过OpenRequest openRequest = ServiceContext.getCurrentContext().getOpenRequest();方式进行获取 - * OpenContext - * OpenParam - * - * @author tanghc - */ -public interface OpenContext extends OpenBeanFactory { - - /** - * 返回appid - * - * @return 返回appid - */ - String getAppId(); - - /** - * 返回业务参数json字符串 - * - * @return 返回字符串业务参数 - */ - String getBizContent(); - - /** - * 返回业务对象 - * - * @return 业务对象 - */ - T getBizObject(); - - /** - * 返回字符编码 - * - * @return 如UTF-8 - */ - String getCharset(); - - /** - * 返回接口名 - * - * @return 如:alipay.goods.get - */ - String getMethod(); - - /** - * 返回版本号 - * - * @return 如:1.0 - */ - String getVersion(); - - /** - * 返回参数格式化 - * - * @return 如:json - */ - String getFormat(); - - /** - * 返回签名类型 - * - * @return 如:RSA2 - */ - String getSignType(); - - /** - * 返回时间戳 - * - * @return - */ - Date getTimestamp(); - - /** - * 返回token,即access_token. - * - * @deprecated 废弃,使用getAppAuthToken() - * @return 返回token - */ - @Deprecated - String appAuthToken(); - - /** - * 返回token,即access_token - * - * @return 返回token - */ - default String getAppAuthToken() { - return appAuthToken(); - } - - /** - * 返回回调地址 - * - * @return 返回回调地址 - */ - String getNotifyUrl(); - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContextImpl.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContextImpl.java deleted file mode 100644 index a71bf45b..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/OpenContextImpl.java +++ /dev/null @@ -1,124 +0,0 @@ -package com.gitee.sop.servercommon.bean; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import org.apache.commons.lang3.time.DateUtils; - -import java.text.ParseException; -import java.util.Date; - -import static com.gitee.sop.servercommon.bean.ParamNames.API_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.APP_AUTH_TOKEN_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.APP_KEY_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.BIZ_CONTENT_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.CHARSET_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.FORMAT_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.NOTIFY_URL_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.SIGN_TYPE_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.TIMESTAMP_NAME; -import static com.gitee.sop.servercommon.bean.ParamNames.TIMESTAMP_PATTERN; -import static com.gitee.sop.servercommon.bean.ParamNames.VERSION_NAME; - -/** - * @author tanghc - */ -public class OpenContextImpl implements OpenContext { - private JSONObject rootJsonObject; - private T bizObject; - - public OpenContextImpl(JSONObject rootJsonObject) { - this(rootJsonObject, null); - } - - public OpenContextImpl(JSONObject rootJsonObject, Class bizClass) { - if (rootJsonObject == null) { - throw new IllegalArgumentException("rootJsonObject can not be null"); - } - this.rootJsonObject = rootJsonObject; - if (bizClass != null) { - String bizContent = getBizContent(); - if (bizContent != null) { - bizObject = (T) JSON.parseObject(bizContent, bizClass); - } else { - bizObject = (T) rootJsonObject.toJavaObject(bizClass); - } - } - } - - @Override - public String getAppId() { - return rootJsonObject.getString(APP_KEY_NAME); - } - - @Override - public T getBizObject() { - return bizObject; - } - - @Override - public String getBizContent() { - return rootJsonObject.getString(BIZ_CONTENT_NAME); - } - - @Override - public String getCharset() { - return rootJsonObject.getString(CHARSET_NAME); - } - - @Override - public String getMethod() { - return rootJsonObject.getString(API_NAME); - } - - @Override - public String getVersion() { - return rootJsonObject.getString(VERSION_NAME); - } - - @Override - public String getFormat() { - return rootJsonObject.getString(FORMAT_NAME); - } - - @Override - public String getSignType() { - return rootJsonObject.getString(SIGN_TYPE_NAME); - } - - @Override - public Date getTimestamp() { - String timestampStr = rootJsonObject.getString(TIMESTAMP_NAME); - try { - return DateUtils.parseDate(timestampStr, TIMESTAMP_PATTERN); - } catch (ParseException e) { - return null; - } - } - - @Override - public String appAuthToken() { - return rootJsonObject.getString(APP_AUTH_TOKEN_NAME); - } - - @Override - public String getNotifyUrl() { - return rootJsonObject.getString(NOTIFY_URL_NAME); - } - - @Override - public E getBizObject(Class clazz) { - if (bizObject != null && bizObject.getClass() == clazz) { - return (E) bizObject; - } - String bizContent = getBizContent(); - if (bizContent == null) { - return null; - } - return JSON.parseObject(bizContent, clazz); - } - - @Override - public String toString() { - return rootJsonObject.toString(); - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceApiInfo.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceApiInfo.java index d200c4b4..4e099f6c 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceApiInfo.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceApiInfo.java @@ -34,10 +34,6 @@ public class ServiceApiInfo { private int permission; /** 是否需要token */ private int needToken; - /** 是否是兼容模式,即使用了@ApiAbility注解 */ - private int compatibleMode; - /** 是否是原始Mapping */ - private boolean originalMapping; public ApiMeta() { } diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceConfig.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceConfig.java index 0da39ab9..5969048d 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceConfig.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceConfig.java @@ -63,9 +63,5 @@ public class ServiceConfig { */ private boolean permission; - /** - * 是否传统web开发模式 - */ - private boolean webappMode; } diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceContext.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceContext.java index 16e8520f..0ccca740 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceContext.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/bean/ServiceContext.java @@ -12,10 +12,6 @@ public class ServiceContext extends ConcurrentHashMap { public static final String REQUEST_KEY = "request"; public static final String RESPONSE_KEY = "response"; - public static final String OPEN_CONTEXT_KEY = "openContext"; - public static final String SOP_MVC = "sop.mvc"; - - public static final String RESTFUL_KEY = "sop-restful"; protected static Class contextClass = ServiceContext.class; @@ -35,14 +31,6 @@ public class ServiceContext extends ConcurrentHashMap { super(); } - public void setOpenContext(OpenContext openContext) { - this.set(OPEN_CONTEXT_KEY, openContext); - } - - public OpenContext getOpenContext() { - return (OpenContext) this.get(OPEN_CONTEXT_KEY); - } - public Locale getLocale() { HttpServletRequest request = getRequest(); if (request == null) { diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/BaseServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/BaseServiceConfiguration.java index fcd56bfe..cef31249 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/BaseServiceConfiguration.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/BaseServiceConfiguration.java @@ -1,129 +1,11 @@ package com.gitee.sop.servercommon.configuration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosWatch; -import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.interceptor.ServiceContextInterceptor; -import com.gitee.sop.servercommon.manager.EnvironmentContext; -import com.gitee.sop.servercommon.manager.ServiceRouteController; -import com.gitee.sop.servercommon.mapping.ApiMappingHandlerMapping; -import com.gitee.sop.servercommon.message.ServiceErrorFactory; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.web.servlet.WebMvcRegistrations; -import org.springframework.context.annotation.Bean; -import org.springframework.core.env.Environment; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.StringHttpMessageConverter; -import org.springframework.scheduling.TaskScheduler; -import org.springframework.web.servlet.config.annotation.InterceptorRegistry; -import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; -import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import javax.annotation.PostConstruct; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Map; /** * @author tanghc */ @Slf4j -public class BaseServiceConfiguration implements WebMvcConfigurer, WebMvcRegistrations { - - public BaseServiceConfiguration() { - ServiceConfig.getInstance().getI18nModules().add("i18n/isp/bizerror"); - } - - private final ApiMappingHandlerMapping apiMappingHandlerMapping = new ApiMappingHandlerMapping(); - - @Autowired - private Environment environment; - - @Override - public void addResourceHandlers(ResourceHandlerRegistry registry) { - // 支持swagger-bootstrap-ui首页 - registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); - // 支持默认swagger - registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); - registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); - } - - @Override - public void addInterceptors(InterceptorRegistry registry) { - // 添加拦截器 - registry.addInterceptor(new ServiceContextInterceptor()); - } - - @Override - public void extendMessageConverters(List> converters) { - // 解决controller返回字符串中文乱码问题 - for (HttpMessageConverter converter : converters) { - if (converter instanceof StringHttpMessageConverter) { - ((StringHttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8); - } - } - } - - /** - * 自定义Mapping,详见@ApiMapping - * @return 返回RequestMappingHandlerMapping - */ - @Override - public RequestMappingHandlerMapping getRequestMappingHandlerMapping() { - return apiMappingHandlerMapping; - } - - @Bean - @ConditionalOnMissingBean - GlobalExceptionHandler globalExceptionHandler() { - return new GlobalExceptionHandler(); - } - - @Bean - @ConditionalOnMissingBean - ServiceRouteController serviceRouteInfoHandler() { - return new ServiceRouteController(); - } - - @Bean - @ConditionalOnMissingBean - @ConditionalOnProperty("spring.cloud.nacos.discovery.server-addr") - public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties, ObjectProvider taskScheduler, Environment environment) { - Map metadata = nacosDiscoveryProperties.getMetadata(); - String contextPath = environment.getProperty("server.servlet.context-path"); - // 将context-path信息加入到metadata中 - if (contextPath != null) { - metadata.put("context-path", contextPath); - } - // 在元数据中新增启动时间,不能修改这个值,不然网关拉取接口会有问题 - metadata.put("time.startup", String.valueOf(System.currentTimeMillis())); - return new NacosWatch(nacosDiscoveryProperties, taskScheduler); - } - - @PostConstruct - public final void after() { - log.info("-----spring容器加载完毕-----"); - EnvironmentContext.setEnvironment(environment); - initMessage(); - doAfter(); - } - - - /** - * spring容器加载完毕后执行 - */ - protected void doAfter() { - - } - - - protected void initMessage() { - ServiceErrorFactory.initMessageSource(ServiceConfig.getInstance().getI18nModules()); - } +public class BaseServiceConfiguration extends ServiceConfiguration { } diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/EasyopenDocSupportController.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/EasyopenDocSupportController.java deleted file mode 100644 index 5e49208f..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/EasyopenDocSupportController.java +++ /dev/null @@ -1,58 +0,0 @@ -package com.gitee.sop.servercommon.configuration; - -import com.gitee.easyopen.doc.ApiDocHolder; -import com.gitee.sop.servercommon.swagger.SwaggerValidator; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; - -import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - -/** - * 文档支持 - * @author tanghc - */ -public abstract class EasyopenDocSupportController { - - private SwaggerValidator swaggerValidator; - - /** - * 获取文档标题 - * @return 返回文档标题 - */ - public abstract String getDocTitle(); - - public EasyopenDocSupportController() { - swaggerValidator = new SwaggerValidator(this.swaggerAccessProtected()); - } - - @RequestMapping("/v2/api-docs") - @ResponseBody - public Map getDocInfo(HttpServletRequest request, HttpServletResponse response) throws IOException { - if (swaggerValidator.swaggerAccessProtected() && !swaggerValidator.validate(request)) { - swaggerValidator.writeForbidden(response); - return null; - } - Map context = this.getContext(); - context.put("easyopen", "1.16.3"); - context.put("apiModules", ApiDocHolder.getApiDocBuilder().getApiModules()); - context.put("title", getDocTitle()); - return context; - } - - public Map getContext() { - return new HashMap<>(8); - } - - /** - * swagger访问是否加密保护 - * @return - */ - protected boolean swaggerAccessProtected() { - return true; - } - -} \ No newline at end of file diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/GlobalExceptionHandler.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/GlobalExceptionHandler.java index 135175cb..610fc271 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/GlobalExceptionHandler.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/GlobalExceptionHandler.java @@ -1,8 +1,6 @@ package com.gitee.sop.servercommon.configuration; -import com.gitee.sop.servercommon.bean.OpenContext; import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.bean.ServiceContext; import com.gitee.sop.servercommon.exception.ServiceException; import com.gitee.sop.servercommon.result.ServiceResultBuilder; import lombok.extern.slf4j.Slf4j; @@ -66,8 +64,7 @@ public class GlobalExceptionHandler { @ResponseBody public Object exceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception exception) { response.addHeader(X_SERVICE_ERROR_HEADER_NAME, String.valueOf(SYSTEM_ERROR_CODE)); - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - log.error("系统错误, openContext:{}", openContext == null ? "null" : openContext, exception); + log.error("系统错误", exception); StringBuilder msg = new StringBuilder(); msg.append(exception.getMessage()); StackTraceElement[] stackTrace = exception.getStackTrace(); diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/ServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/ServiceConfiguration.java new file mode 100644 index 00000000..217a3614 --- /dev/null +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/ServiceConfiguration.java @@ -0,0 +1,94 @@ +package com.gitee.sop.servercommon.configuration; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosWatch; +import com.gitee.sop.servercommon.bean.ServiceConfig; +import com.gitee.sop.servercommon.interceptor.ServiceContextInterceptor; +import com.gitee.sop.servercommon.message.ServiceErrorFactory; +import com.gitee.sop.servercommon.route.ServiceRouteController; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.StringHttpMessageConverter; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +import javax.annotation.PostConstruct; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +/** + * @author tanghc + */ +@Slf4j +public class ServiceConfiguration implements WebMvcConfigurer { + + public ServiceConfiguration() { + ServiceConfig.getInstance().getI18nModules().add("i18n/isp/bizerror"); + } + + @Override + public void addResourceHandlers(ResourceHandlerRegistry registry) { + // 支持swagger-bootstrap-ui首页 + registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/"); + // 支持默认swagger + registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/"); + registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/"); + } + + @Override + public void extendMessageConverters(List> converters) { + // 解决controller返回字符串中文乱码问题 + for (HttpMessageConverter converter : converters) { + if (converter instanceof StringHttpMessageConverter) { + ((StringHttpMessageConverter)converter).setDefaultCharset(StandardCharsets.UTF_8); + } + } + } + + @Override + public void addInterceptors(InterceptorRegistry registry) { + // 添加拦截器 + registry.addInterceptor(new ServiceContextInterceptor()); + } + + @Bean + @ConditionalOnMissingBean + GlobalExceptionHandler globalExceptionHandler() { + return new GlobalExceptionHandler(); + } + + @Bean + @ConditionalOnMissingBean + ServiceRouteController serviceRouteInfoHandler() { + return new ServiceRouteController(); + } + + @PostConstruct + public final void after() { + log.info("-----spring容器加载完毕-----"); + initMessage(); + doAfter(); + } + + + /** + * spring容器加载完毕后执行 + */ + protected void doAfter() { + + } + + + protected void initMessage() { + ServiceErrorFactory.initMessageSource(ServiceConfig.getInstance().getI18nModules()); + } + +} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/SpringMvcServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/SpringMvcServiceConfiguration.java deleted file mode 100644 index d5bb8bdc..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/SpringMvcServiceConfiguration.java +++ /dev/null @@ -1,90 +0,0 @@ -package com.gitee.sop.servercommon.configuration; - -import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.servercommon.manager.EnvironmentContext; -import com.gitee.sop.servercommon.manager.ServiceRouteController; -import com.gitee.sop.servercommon.mapping.ApiMappingHandlerMapping; -import com.gitee.sop.servercommon.message.ServiceErrorFactory; -import com.gitee.sop.servercommon.param.SopHandlerMethodArgumentResolver; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Primary; -import org.springframework.core.env.Environment; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import javax.annotation.PostConstruct; - -/** - * 提供给springmvc工程 - * @author tanghc - */ -@Slf4j -public class SpringMvcServiceConfiguration { - - static { - System.setProperty(ServiceContext.SOP_MVC, "true"); - // 默认版本号为1.0 - ServiceConfig.getInstance().setDefaultVersion("1.0"); - } - - public SpringMvcServiceConfiguration() { - ServiceConfig.getInstance().getI18nModules().add("i18n/isp/bizerror"); - } - - private ApiMappingHandlerMapping apiMappingHandlerMapping = new ApiMappingHandlerMapping(); - - @Autowired - private RequestMappingHandlerAdapter requestMappingHandlerAdapter; - - @Autowired - private Environment environment; - - /** - * 自定义Mapping,详见@ApiMapping - * - * @return 返回RequestMappingHandlerMapping - */ - @Bean - @Primary - public RequestMappingHandlerMapping requestMappingHandlerMapping() { - return apiMappingHandlerMapping; - } - - - @Bean - @ConditionalOnMissingBean - GlobalExceptionHandler globalExceptionHandler() { - return new GlobalExceptionHandler(); - } - - @Bean - @ConditionalOnMissingBean - ServiceRouteController serviceRouteInfoHandler() { - return new ServiceRouteController(); - } - - @PostConstruct - public final void after() { - log.info("-----spring容器加载完毕-----"); - EnvironmentContext.setEnvironment(environment); - initMessage(); - doAfter(); - } - - /** - * spring容器加载完毕后执行 - */ - protected void doAfter() { - SopHandlerMethodArgumentResolver sopHandlerMethodArgumentResolver = ServiceConfig.getInstance().getMethodArgumentResolver(); - sopHandlerMethodArgumentResolver.setRequestMappingHandlerAdapter(requestMappingHandlerAdapter); - } - - protected void initMessage() { - ServiceErrorFactory.initMessageSource(ServiceConfig.getInstance().getI18nModules()); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/TaobaoServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/TaobaoServiceConfiguration.java deleted file mode 100644 index eeb7eb0a..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/TaobaoServiceConfiguration.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.gitee.sop.servercommon.configuration; - -/** - * 具备淘宝开放平台服务提供能力 - * @author tanghc - */ -public class TaobaoServiceConfiguration extends BaseServiceConfiguration { - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/WebappServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/WebappServiceConfiguration.java deleted file mode 100644 index db42e8d1..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/configuration/WebappServiceConfiguration.java +++ /dev/null @@ -1,16 +0,0 @@ -package com.gitee.sop.servercommon.configuration; - -import com.gitee.sop.servercommon.bean.ServiceConfig; - -/** - * 通用web - * @author tanghc - */ -public class WebappServiceConfiguration extends BaseServiceConfiguration { - static { - // 默认版本号为1.0 - ServiceConfig.getInstance().setDefaultVersion("1.0"); - ServiceConfig.getInstance().setIgnoreValidate(true); - ServiceConfig.getInstance().setWebappMode(true); - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenApiMetaBuilder.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenApiMetaBuilder.java deleted file mode 100644 index adcd450f..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenApiMetaBuilder.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.gitee.sop.servercommon.easyopen; - -import com.gitee.easyopen.annotation.Api; -import com.gitee.easyopen.util.ReflectionUtil; -import com.gitee.sop.servercommon.bean.ServiceApiInfo; -import com.gitee.sop.servercommon.manager.ApiMetaBuilder; -import org.apache.commons.lang3.BooleanUtils; -import org.springframework.context.ApplicationContext; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.function.Consumer; - -/** - * @author tanghc - */ -public class EasyopenApiMetaBuilder extends ApiMetaBuilder { - - /** IndexController上面的@RequestMapping()中的值,如:/api */ - private final String prefixPath; - - private final String contextPath; - - private ApplicationContext applicationContext; - - private Environment environment; - - public EasyopenApiMetaBuilder(ApplicationContext applicationContext, Environment environment) { - this.applicationContext = applicationContext; - this.environment = environment; - String path = environment.getProperty("easyopen.prefix-path"); - if (path == null) { - throw new IllegalArgumentException("请在application.propertis中设置easyopen.prefix-path属性,填IndexController上面的@RequestMapping()中的值"); - } - if (!path.startsWith("/")) { - path = "/" + path; - } - this.prefixPath = path; - this.contextPath = environment.getProperty("server.servlet.context-path", "/"); - } - - @Override - protected List buildApiMetaList(RequestMappingHandlerMapping requestMappingHandlerMapping) { - String[] apiServiceNames = ReflectionUtil.findApiServiceNames(applicationContext); - List apiMetaList = new ArrayList<>(); - for (String apiServiceName : apiServiceNames) { - Object bean = applicationContext.getBean(apiServiceName); - doWithMethods(bean.getClass(), method -> { - Api api = AnnotationUtils.findAnnotation(method, Api.class); - ServiceApiInfo.ApiMeta apiMeta = new ServiceApiInfo.ApiMeta(); - apiMeta.setName(api.name()); - apiMeta.setVersion(api.version()); - apiMeta.setIgnoreValidate(BooleanUtils.toInteger(api.ignoreValidate())); - // 对结果不合并 - apiMeta.setMergeResult(BooleanUtils.toInteger(false)); - // /api/goods.get/ - String servletPath = this.buildPath(api); - apiMeta.setPath(servletPath); - apiMetaList.add(apiMeta); - }); - } - return apiMetaList; - } - - protected void doWithMethods(Class clazz, Consumer consumer) { - // Keep backing up the inheritance hierarchy. - Method[] methods = clazz.getDeclaredMethods(); - for (Method method : methods) { - boolean match = !method.isSynthetic() && AnnotationUtils.findAnnotation(method, Api.class) != null; - if (match) { - consumer.accept(method); - } - } - } - - protected String buildPath(Api api) { - // /api/goods.get/ - String servletPath = prefixPath + "/" + api.name() + "/"; - String version = api.version(); - if (StringUtils.hasLength(version)) { - // /api/goods.get/1.0/ - servletPath = servletPath + version + "/"; - } - return contextPath + prefixPath + servletPath; - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceConfiguration.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceConfiguration.java deleted file mode 100644 index a84bf30f..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceConfiguration.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.gitee.sop.servercommon.easyopen; - -import com.gitee.easyopen.ApiContext; -import com.gitee.sop.servercommon.configuration.BaseServiceConfiguration; -import com.gitee.sop.servercommon.manager.ServiceRouteController; -import org.springframework.context.annotation.Bean; - -/** - * 提供给easyopen项目使用 - * - * @author tanghc - */ -public class EasyopenServiceConfiguration extends BaseServiceConfiguration { - - static { - ApiContext.getApiConfig().setIgnoreValidate(true); - } - - @Bean - ServiceRouteController serviceRouteController() { - return new EasyopenServiceRouteController(); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceRouteController.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceRouteController.java deleted file mode 100644 index afff6f8d..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/easyopen/EasyopenServiceRouteController.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.gitee.sop.servercommon.easyopen; - -import com.gitee.sop.servercommon.manager.ApiMetaBuilder; -import com.gitee.sop.servercommon.manager.ServiceRouteController; -import org.springframework.beans.BeansException; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author tanghc - */ -@RestController -public class EasyopenServiceRouteController extends ServiceRouteController implements ApplicationContextAware { - - private ApplicationContext applicationContext; - - @Override - protected ApiMetaBuilder getApiMetaBuilder() { - return new EasyopenApiMetaBuilder(applicationContext, getEnvironment()); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { - this.applicationContext = applicationContext; - } -} \ No newline at end of file diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/interceptor/ServiceContextInterceptor.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/interceptor/ServiceContextInterceptor.java index e5da2b2a..f02e54ed 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/interceptor/ServiceContextInterceptor.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/interceptor/ServiceContextInterceptor.java @@ -1,11 +1,6 @@ package com.gitee.sop.servercommon.interceptor; -import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.servercommon.bean.OpenContext; -import com.gitee.sop.servercommon.bean.OpenContextImpl; import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.servercommon.util.OpenUtil; -import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.handler.HandlerInterceptorAdapter; import javax.servlet.http.HttpServletRequest; @@ -21,28 +16,9 @@ public class ServiceContextInterceptor extends HandlerInterceptorAdapter { ServiceContext context = ServiceContext.getCurrentContext(); context.setRequest(request); context.setResponse(response); - if (handler instanceof HandlerMethod) { - HandlerMethod handlerMethod = (HandlerMethod) handler; - // 修复方法参数个数为0,OpenContext获取null问题 - if (handlerMethod.getMethodParameters().length == 0) { - initOpenContext(request); - } - } return true; } - - /** - * 初始化OpenContext - * - * @param request request - */ - protected void initOpenContext(HttpServletRequest request) { - JSONObject requestParams = OpenUtil.getRequestParams(request); - OpenContext openContext = new OpenContextImpl(requestParams); - ServiceContext.getCurrentContext().setOpenContext(openContext); - } - @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { ServiceContext.getCurrentContext().unset(); diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaBuilder.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaBuilder.java deleted file mode 100644 index 55c2bf58..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaBuilder.java +++ /dev/null @@ -1,146 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import com.gitee.sop.servercommon.bean.ServiceApiInfo; -import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.servercommon.mapping.ApiMappingInfo; -import com.gitee.sop.servercommon.mapping.ApiMappingRequestCondition; -import com.gitee.sop.servercommon.mapping.RouteUtil; -import org.apache.commons.lang3.BooleanUtils; -import org.springframework.util.StringUtils; -import org.springframework.web.method.HandlerMethod; -import org.springframework.web.servlet.mvc.condition.RequestCondition; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * @author tanghc - */ -public class ApiMetaBuilder { - - /** 接口名规则:允许字母、数字、点、下划线 */ - private static final String REGEX_API_NAME = "^[a-zA-Z0-9\\.\\_\\-]+$"; - - private static final List IGNORE_PATTERN_KEYWORDS = Arrays.asList("swagger","sop/routes"); - - public ServiceApiInfo getServiceApiInfo(String serviceId, RequestMappingHandlerMapping requestMappingHandlerMapping) { - if (serviceId == null) { - throw new IllegalArgumentException("请在application.properties中指定spring.application.name属性"); - } - List apis = this.buildApiMetaList(requestMappingHandlerMapping); - // 排序 - apis.sort(Comparator.comparing(ServiceApiInfo.ApiMeta::fetchNameVersion)); - - ServiceApiInfo serviceApiInfo = new ServiceApiInfo(); - serviceApiInfo.setServiceId(serviceId); - serviceApiInfo.setApis(apis); - - return serviceApiInfo; - } - - protected List buildApiMetaList(RequestMappingHandlerMapping requestMappingHandlerMapping) { - Map handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); - Set requestMappingInfos = handlerMethods.keySet(); - List store = new ArrayList<>(); - List apis = new ArrayList<>(requestMappingInfos.size()); - Set restfulApis = new HashSet<>(requestMappingInfos.size()); - - for (Map.Entry handlerMethodEntry : handlerMethods.entrySet()) { - ServiceApiInfo.ApiMeta apiMeta = this.buildApiMeta(handlerMethodEntry); - if (apiMeta == null) { - continue; - } - String key = apiMeta.fetchNameVersion(); - if (apiMeta.isOriginalMapping()) { - restfulApis.add(apiMeta); - } else { - if (store.contains(key)) { - throw new IllegalArgumentException("重复申明接口,请检查path和version,path:" + apiMeta.getPath() + ", version:" + apiMeta.getVersion()); - } else { - store.add(key); - } - apis.add(apiMeta); - } - } - apis.addAll(restfulApis); - return apis; - } - - protected ServiceApiInfo.ApiMeta buildApiMeta(Map.Entry handlerMethodEntry) { - RequestMappingInfo requestMappingInfo = handlerMethodEntry.getKey(); - Set patterns = requestMappingInfo.getPatternsCondition().getPatterns(); - RequestCondition customCondition = requestMappingInfo.getCustomCondition(); - if (customCondition instanceof ApiMappingRequestCondition) { - ApiMappingRequestCondition condition = (ApiMappingRequestCondition) customCondition; - ApiMappingInfo apiMappingInfo = condition.getApiMappingInfo(); - String name = apiMappingInfo.getName(); - String version = apiMappingInfo.getVersion(); - // 方法完整的path,如: /goods/listGoods,/users/user/get - String path = patterns.iterator().next(); - // 不是ApiMapping注解的接口,name属性是null - if (name == null || ServiceConfig.getInstance().isWebappMode()) { - name = buildName(path); - } - this.checkApiName(name); - ServiceApiInfo.ApiMeta apiMeta = new ServiceApiInfo.ApiMeta(name, path, version); - apiMeta.setIgnoreValidate(BooleanUtils.toInteger(apiMappingInfo.isIgnoreValidate())); - apiMeta.setMergeResult(BooleanUtils.toInteger(apiMappingInfo.isMergeResult())); - apiMeta.setPermission(BooleanUtils.toInteger(apiMappingInfo.isPermission())); - apiMeta.setNeedToken(BooleanUtils.toInteger(apiMappingInfo.isNeedToken())); - apiMeta.setCompatibleMode(BooleanUtils.toInteger(apiMappingInfo.isCompatibleMode())); - return apiMeta; - } else { - if (!ServiceContext.getCurrentContext().getBoolean(ServiceContext.RESTFUL_KEY, false)) { - return null; - } - String path = patterns.iterator().next(); - if (path.contains("$") || isIgnorePattern(path)) { - return null; - } - // 如果是restful服务 - String name = path; - String prefix = EnvironmentKeys.SOP_RESTFUL_PREFIX.getValue(); - if (StringUtils.isEmpty(prefix)) { - prefix = EnvironmentKeys.SPRING_APPLICATION_NAME.getValue(); - } - String oldModel = EnvironmentKeys.SOP_RESTFUL_OLD_MODEL.getValue(); - if (!"true".equals(oldModel) && StringUtils.hasText(prefix)) { - name = "/" + prefix + "/" + StringUtils.trimLeadingCharacter(path, '/'); - } - ServiceApiInfo.ApiMeta apiMeta = new ServiceApiInfo.ApiMeta(name, path, ""); - apiMeta.setIgnoreValidate(BooleanUtils.toInteger(true)); - apiMeta.setMergeResult(BooleanUtils.toInteger(false)); - apiMeta.setPermission(BooleanUtils.toInteger(false)); - apiMeta.setOriginalMapping(true); - return apiMeta; - } - } - - private boolean isIgnorePattern(String pattern) { - for (String keyword : IGNORE_PATTERN_KEYWORDS) { - if (pattern.contains(keyword)) { - return true; - } - } - return false; - } - - protected void checkApiName(String name) { - if (!name.matches(REGEX_API_NAME)) { - throw new IllegalArgumentException("接口名称只允许【字母、数字、点(.)、下划线(_)、减号(-)】,错误接口:" + name); - } - } - - - protected String buildName(String path) { - return RouteUtil.buildApiName(path); - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaManager.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaManager.java deleted file mode 100644 index da689771..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ApiMetaManager.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import com.gitee.sop.servercommon.bean.ServiceApiInfo; - -/** - * @author tanghc - */ -public interface ApiMetaManager { - /** - * 上传API - * @param serviceApiInfo - */ - void uploadApi(ServiceApiInfo serviceApiInfo); -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/DefaultRequestMappingEvent.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/DefaultRequestMappingEvent.java deleted file mode 100644 index 3e3a59bb..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/DefaultRequestMappingEvent.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import com.gitee.sop.servercommon.bean.ServiceApiInfo; -import lombok.Getter; -import org.springframework.core.env.Environment; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -/** - * @author tanghc - */ -@Getter -public class DefaultRequestMappingEvent extends ApiMetaBuilder implements RequestMappingEvent { - - private ApiMetaManager apiMetaManager; - private Environment environment; - - public DefaultRequestMappingEvent(ApiMetaManager apiMetaManager, Environment environment) { - this.apiMetaManager = apiMetaManager; - this.environment = environment; - } - - @Override - public void onRegisterSuccess(RequestMappingHandlerMapping requestMappingHandlerMapping) { - String serviceId = environment.getProperty("spring.application.name"); - ServiceApiInfo serviceApiInfo = getServiceApiInfo(serviceId, requestMappingHandlerMapping); - apiMetaManager.uploadApi(serviceApiInfo); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentContext.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentContext.java deleted file mode 100644 index 8a4f8679..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentContext.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import org.springframework.core.env.Environment; - -/** - * @author tanghc - */ -public class EnvironmentContext { - private static Environment environment; - - public static Environment getEnvironment() { - return environment; - } - - public static void setEnvironment(Environment environment) { - EnvironmentContext.environment = environment; - } - - public static String getValue(String key, String defaultValue) { - return environment.getProperty(key, defaultValue); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentKeys.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentKeys.java deleted file mode 100644 index c3721019..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/EnvironmentKeys.java +++ /dev/null @@ -1,42 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import javax.annotation.Nullable; - -public enum EnvironmentKeys { - SPRING_PROFILES_ACTIVE("spring.profiles.active", "default"), - /** - * spring.application.name - */ - SPRING_APPLICATION_NAME("spring.application.name"), - - /** - * sop.restful.prefix=xxx,指定web开发模式前缀,不指定默认为service-id - */ - SOP_RESTFUL_PREFIX("sop.restful.prefix"), - - /** - * sop.restful.old-model=true,兼容老的restful调用方式(2.4.1之前) - */ - SOP_RESTFUL_OLD_MODEL("sop.restful.old-model", "false"); - - private String key; - private String defaultValue; - - public String getKey() { - return key; - } - - EnvironmentKeys(String key) { - this.key = key; - } - - EnvironmentKeys(String key, String defaultValue) { - this.key = key; - this.defaultValue = defaultValue; - } - - @Nullable - public String getValue() { - return EnvironmentContext.getValue(key, defaultValue); - } -} \ No newline at end of file diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/RequestMappingEvent.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/RequestMappingEvent.java deleted file mode 100644 index d117a793..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/RequestMappingEvent.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.sop.servercommon.manager; - -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -/** - * @author tanghc - */ -public interface RequestMappingEvent { - /** - * 注册成功后回调 - * @param apiMappingHandlerMapping - */ - void onRegisterSuccess(RequestMappingHandlerMapping apiMappingHandlerMapping); -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingHandlerMapping.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingHandlerMapping.java deleted file mode 100644 index 1a3696b3..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingHandlerMapping.java +++ /dev/null @@ -1,100 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import com.gitee.sop.servercommon.annotation.ApiAbility; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.servercommon.util.OpenUtil; -import org.springframework.core.PriorityOrdered; -import org.springframework.util.StringValueResolver; -import org.springframework.web.servlet.mvc.condition.RequestCondition; -import org.springframework.web.servlet.mvc.method.RequestMappingInfo; -import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; - -import java.lang.reflect.Method; - -/** - * @author tanghc - */ -public class ApiMappingHandlerMapping extends RequestMappingHandlerMapping implements PriorityOrdered { - - private static StringValueResolver stringValueResolverMVC = new ApiMappingStringValueResolverMVC(); - - @Override - protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) { - String sopMvc = System.getProperty(ServiceContext.SOP_MVC); - boolean isMvc = sopMvc != null; - ApiMapping apiMapping = method.getAnnotation(ApiMapping.class); - ApiAbility apiAbility = OpenUtil.getAnnotationFromMethodOrClass(method, ApiAbility.class); - StringValueResolver valueResolver = null; - if (apiMapping != null) { - String version = apiMapping.version(); - if ("".equals(version)) { - version = ServiceConfig.getInstance().getDefaultVersion(); - } - valueResolver = new ApiMappingStringValueResolverVersion(version); - } - if (isMvc || apiAbility != null) { - valueResolver = stringValueResolverMVC; - } - this.setEmbeddedValueResolver(valueResolver); - return super.getMappingForMethod(method, handlerType); - } - - @Override - protected RequestCondition getCustomMethodCondition(Method method) { - method.setAccessible(true); - String name = null; - String version; - boolean ignoreValidate; - boolean mergeResult; - boolean permission; - boolean needToken; - boolean compatibleMode = false; - ApiMapping apiMapping = method.getAnnotation(ApiMapping.class); - if (apiMapping != null) { - name = apiMapping.value()[0]; - version = apiMapping.version(); - ignoreValidate = apiMapping.ignoreValidate(); - mergeResult = apiMapping.mergeResult(); - permission = apiMapping.permission(); - needToken = apiMapping.needToken(); - } else { - ApiAbility apiAbility = OpenUtil.getAnnotationFromMethodOrClass(method, ApiAbility.class); - if (apiAbility != null) { - version = apiAbility.version(); - ignoreValidate = apiAbility.ignoreValidate(); - mergeResult = apiAbility.mergeResult(); - permission = apiAbility.permission(); - needToken = apiAbility.needToken(); - compatibleMode = true; - } else { - return super.getCustomMethodCondition(method); - } - } - if ("".equals(version)) { - version = ServiceConfig.getInstance().getDefaultVersion(); - } - ApiMappingInfo apiMappingInfo = new ApiMappingInfo(name, version); - // 如果是默认配置,则采用全局配置 - if (!ignoreValidate) { - ignoreValidate = ServiceConfig.getInstance().isIgnoreValidate(); - } - // 如果是默认配置,则采用全局配置 - if (mergeResult) { - mergeResult = ServiceConfig.getInstance().isMergeResult(); - } - // 如果是默认配置,则采用全局配置 - if (!permission) { - permission = ServiceConfig.getInstance().isPermission(); - } - apiMappingInfo.setIgnoreValidate(ignoreValidate); - apiMappingInfo.setMergeResult(mergeResult); - apiMappingInfo.setPermission(permission); - apiMappingInfo.setNeedToken(needToken); - apiMappingInfo.setCompatibleMode(compatibleMode); - logger.info("注册接口,name:" + method + ", version:" + version); - return new ApiMappingRequestCondition(apiMappingInfo); - } - -} \ No newline at end of file diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingInfo.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingInfo.java deleted file mode 100644 index 765de153..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingInfo.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import lombok.Data; - -/** - * @author tanghc - */ -@Data -public class ApiMappingInfo { - private String name; - private String version; - private boolean ignoreValidate; - private boolean mergeResult; - private boolean permission; - private boolean needToken; - private boolean compatibleMode; - - - public ApiMappingInfo(String name, String version) { - this.name = name; - this.version = version; - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingRequestCondition.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingRequestCondition.java deleted file mode 100644 index 6ef894ea..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingRequestCondition.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import com.gitee.sop.servercommon.bean.ParamNames; -import com.gitee.sop.servercommon.bean.ServiceConfig; -import lombok.Getter; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.servlet.mvc.condition.RequestCondition; - -import javax.servlet.http.HttpServletRequest; - -/** - * @author tanghc - */ -@Getter -@Slf4j -public class ApiMappingRequestCondition implements RequestCondition { - - private String defaultVersion = ServiceConfig.getInstance().getDefaultVersion(); - - private ApiMappingInfo apiMappingInfo; - - public ApiMappingRequestCondition(ApiMappingInfo apiMappingInfo) { - this.apiMappingInfo = apiMappingInfo; - } - - @Override - public ApiMappingRequestCondition combine(ApiMappingRequestCondition other) { - return this; - } - - /** - * 如果版本号跟当前对象中的版本号匹配,则表是命中的对应的方法 - * 否则返回null,表示不匹配 - * - * @param request - * @return 返回ApiMappingRequestCondition - */ - @Override - public ApiMappingRequestCondition getMatchingCondition(HttpServletRequest request) { - String servletPath = request.getServletPath(); - String path = apiMappingInfo.getName() + "/" + apiMappingInfo.getVersion() + "/"; - if (servletPath.contains(path)) { - return this; - } - String version = this.getVersion(request); - if (version.equals(this.apiMappingInfo.getVersion())) { - return this; - } - return null; - } - - protected String getVersion(HttpServletRequest request) { - String version = request.getHeader(ParamNames.HEADER_VERSION_NAME); - if (version == null) { - version = request.getParameter(ParamNames.VERSION_NAME); - } - return version == null ? defaultVersion : version; - } - - - /** - * 对两个RequestCondition对象进行比较,这里主要是如果存在两个注册的一样的Mapping, - * 那么就会对这两个Mapping进行排序,以判断哪个Mapping更适合处理当前request请求 - * - * @param other - * @param request - * @return 返回-1,0,1 - */ - @Override - public int compareTo(ApiMappingRequestCondition other, HttpServletRequest request) { - return this.apiMappingInfo.getVersion().compareTo(other.apiMappingInfo.getVersion()); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolver.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolver.java deleted file mode 100644 index 0e394d7b..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolver.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import org.springframework.util.StringValueResolver; - -/** - * @author tanghc - */ -public class ApiMappingStringValueResolver implements StringValueResolver { - - private static final String END = "/"; - - @Override - public String resolveStringValue(String strVal) { - if (strVal == null) { - return null; - } - return strVal + END; - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverMVC.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverMVC.java deleted file mode 100644 index 9e5da2be..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverMVC.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import org.springframework.util.StringValueResolver; - -/** - * @author tanghc - */ -public class ApiMappingStringValueResolverMVC implements StringValueResolver { - - @Override - public String resolveStringValue(String strVal) { - return strVal; - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverVersion.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverVersion.java deleted file mode 100644 index 7e4714b4..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/ApiMappingStringValueResolverVersion.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import org.springframework.util.StringValueResolver; - -/** - * @author tanghc - */ -public class ApiMappingStringValueResolverVersion implements StringValueResolver { - - private static final String SPLIT = "/"; - - private String version; - - public ApiMappingStringValueResolverVersion(String version) { - this.version = version; - } - - @Override - public String resolveStringValue(String strVal) { - if (strVal == null) { - return null; - } - return strVal + SPLIT + version + SPLIT; - } -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/RouteUtil.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/RouteUtil.java deleted file mode 100644 index d83f55c8..00000000 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/mapping/RouteUtil.java +++ /dev/null @@ -1,23 +0,0 @@ -package com.gitee.sop.servercommon.mapping; - -import org.springframework.util.StringUtils; - -/** - * @author tanghc - */ -public class RouteUtil { - - /** - * 将springmvc接口路径转换成SOP方法名 - * - * @param path springmvc路径,如:/goods/listGoods - * @return 返回接口方法名,/goods/listGoods -> goods.listGoods - */ - public static String buildApiName(String path) { - char separatorChar = '/'; - path = StringUtils.trimLeadingCharacter(path, separatorChar); - path = StringUtils.trimTrailingCharacter(path, separatorChar); - return path.replace(separatorChar, '.'); - } - -} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/param/ApiArgumentResolver.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/param/ApiArgumentResolver.java index d099b0b5..afcb2fc5 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/param/ApiArgumentResolver.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/param/ApiArgumentResolver.java @@ -1,11 +1,10 @@ package com.gitee.sop.servercommon.param; +import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.servercommon.annotation.ApiAbility; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.bean.OpenContext; -import com.gitee.sop.servercommon.bean.OpenContextImpl; -import com.gitee.sop.servercommon.bean.ServiceContext; +import com.alibaba.fastjson.JSONValidator; +import com.gitee.sop.servercommon.annotation.Open; +import com.gitee.sop.servercommon.bean.ParamNames; import com.gitee.sop.servercommon.util.OpenUtil; import lombok.extern.slf4j.Slf4j; import org.springframework.core.MethodParameter; @@ -31,8 +30,6 @@ import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; -import java.lang.reflect.ParameterizedType; -import java.lang.reflect.Type; import java.security.Principal; import java.time.ZoneId; import java.util.ArrayList; @@ -50,7 +47,7 @@ import java.util.concurrent.ConcurrentHashMap; @Slf4j public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { - private Map argumentResolverCache = new ConcurrentHashMap<>(256); + private final Map argumentResolverCache = new ConcurrentHashMap<>(256); private ParamValidator paramValidator = new ServiceParamValidator(); @@ -58,7 +55,7 @@ public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { private RequestMappingHandlerAdapter requestMappingHandlerAdapter; - private static List openApiParams = new ArrayList<>(64); + private static final List openApiParams = new ArrayList<>(64); static { try { @@ -87,9 +84,6 @@ public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { openApiParams.add(methodParameter); } Class paramType = methodParameter.getParameterType(); - if (paramType == OpenContext.class) { - return true; - } // 排除的 boolean exclude = ( WebRequest.class.isAssignableFrom(paramType) || @@ -113,8 +107,7 @@ public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { } private boolean hasApiAnnotation(MethodParameter methodParameter) { - return methodParameter.hasMethodAnnotation(ApiMapping.class) - || OpenUtil.getAnnotationFromMethodOrClass(methodParameter.getMethod(), ApiAbility.class) != null; + return methodParameter.hasMethodAnnotation(Open.class); } @Override @@ -125,14 +118,10 @@ public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { , WebDataBinderFactory webDataBinderFactory ) throws Exception { if (openApiParams.contains(methodParameter)) { - Object ret = this.getParamObject(methodParameter, nativeWebRequest); - Object paramObj = ret; - if (paramObj instanceof OpenContext) { - paramObj = ((OpenContext) paramObj).getBizObject(); - } + Object paramObj = this.getParamObject(methodParameter, nativeWebRequest); // JSR-303验证 paramValidator.validateBizParam(paramObj); - return ret; + return paramObj; } HandlerMethodArgumentResolver resolver = getOtherArgumentResolver(methodParameter); if (resolver != null) { @@ -157,57 +146,45 @@ public class ApiArgumentResolver implements SopHandlerMethodArgumentResolver { protected Object getParamObject(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) { HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest(); JSONObject requestParams = OpenUtil.getRequestParams(request); + String bizContent = requestParams.getString(ParamNames.BIZ_CONTENT_NAME); // 方法参数类型 Class parameterType = methodParameter.getParameterType(); - boolean isOpenContextParam = parameterType == OpenContext.class; - Class bizObjClass = parameterType; - // 参数是OpenRequest,则取OpenRequest的泛型参数类型 - if (isOpenContextParam) { - bizObjClass = this.getOpenRequestGenericParameterClass(methodParameter); - } - OpenContext openContext = new OpenContextImpl(requestParams, bizObjClass); - ServiceContext.getCurrentContext().setOpenContext(openContext); - Object bizObj = openContext.getBizObject(); - this.bindUploadFile(bizObj, request); - return isOpenContextParam ? openContext : bizObj; - } - - /** - * 获取泛型参数类型 - * - * @param methodParameter 参数 - * @return 返回泛型参数class - */ - protected Class getOpenRequestGenericParameterClass(MethodParameter methodParameter) { - Type genericParameterType = methodParameter.getGenericParameterType(); - Class bizObjClass = null; - if (genericParameterType instanceof ParameterizedType) { - Type[] params = ((ParameterizedType) genericParameterType).getActualTypeArguments(); - if (params != null && params.length >= 1) { - bizObjClass = (Class) params[0]; + Object param; + if (bizContent != null) { + // 如果是json字符串 + if (JSONValidator.from(bizContent).validate()) { + param = JSON.parseObject(bizContent, parameterType); + } else { + // 否则认为是 aa=1&bb=33 形式 + Map query = OpenUtil.parseQueryToMap(bizContent); + param = new JSONObject(query).toJavaObject(parameterType); } + } else { + param = requestParams.toJavaObject(parameterType); } - return bizObjClass; + this.bindUploadFile(param, request); + return param; } + /** * 将上传文件对象绑定到属性中 * - * @param bizObj 业务参数 + * @param param 业务参数 * @param httpServletRequest */ - protected void bindUploadFile(Object bizObj, HttpServletRequest httpServletRequest) { - if (bizObj == null) { + protected void bindUploadFile(Object param, HttpServletRequest httpServletRequest) { + if (param == null) { return; } if (this.isMultipartRequest(httpServletRequest)) { MultipartHttpServletRequest request = (MultipartHttpServletRequest) httpServletRequest; - Class bizClass = bizObj.getClass(); + Class bizClass = param.getClass(); ReflectionUtils.doWithFields(bizClass, field -> { ReflectionUtils.makeAccessible(field); String name = field.getName(); MultipartFile multipartFile = request.getFile(name); - ReflectionUtils.setField(field, bizObj, multipartFile); + ReflectionUtils.setField(field, param, multipartFile); }, field -> field.getType() == MultipartFile.class); } } diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ApiMetaBuilder.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ApiMetaBuilder.java new file mode 100644 index 00000000..fc2ee5e6 --- /dev/null +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ApiMetaBuilder.java @@ -0,0 +1,93 @@ +package com.gitee.sop.servercommon.route; + +import com.gitee.sop.servercommon.annotation.Open; +import com.gitee.sop.servercommon.bean.ServiceApiInfo; +import com.gitee.sop.servercommon.bean.ServiceConfig; +import org.apache.commons.lang3.BooleanUtils; +import org.springframework.web.method.HandlerMethod; +import org.springframework.web.servlet.mvc.method.RequestMappingInfo; +import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * @author tanghc + */ +public class ApiMetaBuilder { + + /** + * 接口名规则:允许字母、数字、点、下划线 + */ + private static final String REGEX_API_NAME = "^[a-zA-Z0-9\\.\\_\\-]+$"; + + public ServiceApiInfo getServiceApiInfo(String serviceId, RequestMappingHandlerMapping requestMappingHandlerMapping) { + if (serviceId == null) { + throw new IllegalArgumentException("请在application.properties中指定spring.application.name属性"); + } + List apis = this.buildApiMetaList(requestMappingHandlerMapping); + // 排序 + apis.sort(Comparator.comparing(ServiceApiInfo.ApiMeta::fetchNameVersion)); + + ServiceApiInfo serviceApiInfo = new ServiceApiInfo(); + serviceApiInfo.setServiceId(serviceId); + serviceApiInfo.setApis(apis); + + return serviceApiInfo; + } + + protected List buildApiMetaList(RequestMappingHandlerMapping requestMappingHandlerMapping) { + Map handlerMethods = requestMappingHandlerMapping.getHandlerMethods(); + Set requestMappingInfos = handlerMethods.keySet(); + List store = new ArrayList<>(); + List apis = new ArrayList<>(requestMappingInfos.size()); + + for (Map.Entry handlerMethodEntry : handlerMethods.entrySet()) { + ServiceApiInfo.ApiMeta apiMeta = this.buildApiMeta(handlerMethodEntry); + if (apiMeta == null) { + continue; + } + String key = apiMeta.fetchNameVersion(); + if (store.contains(key)) { + throw new IllegalArgumentException("重复申明接口,请检查path和version,path:" + apiMeta.getPath() + ", version:" + apiMeta.getVersion()); + } else { + store.add(key); + } + apis.add(apiMeta); + } + return apis; + } + + protected ServiceApiInfo.ApiMeta buildApiMeta(Map.Entry handlerMethodEntry) { + RequestMappingInfo requestMappingInfo = handlerMethodEntry.getKey(); + Set patterns = requestMappingInfo.getPatternsCondition().getPatterns(); + Open open = handlerMethodEntry.getValue().getMethodAnnotation(Open.class); + ServiceApiInfo.ApiMeta apiMeta = null; + if (open != null) { + String name = open.value(); + String version = open.version(); + if ("".equals(version)) { + version = ServiceConfig.getInstance().getDefaultVersion(); + } + // 方法完整的path,如: /goods/listGoods,/users/user/get + String path = patterns.iterator().next(); + this.checkApiName(name); + apiMeta = new ServiceApiInfo.ApiMeta(name, path, version); + apiMeta.setIgnoreValidate(BooleanUtils.toInteger(open.ignoreValidate())); + apiMeta.setMergeResult(BooleanUtils.toInteger(open.mergeResult())); + apiMeta.setPermission(BooleanUtils.toInteger(open.permission())); + apiMeta.setNeedToken(BooleanUtils.toInteger(open.needToken())); + } + return apiMeta; + } + + + protected void checkApiName(String name) { + if (!name.matches(REGEX_API_NAME)) { + throw new IllegalArgumentException("接口名称只允许【字母、数字、点(.)、下划线(_)、减号(-)】,错误接口:" + name); + } + } +} diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteController.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteController.java similarity index 82% rename from sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteController.java rename to sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteController.java index 2d484611..3a6289e4 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteController.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteController.java @@ -1,8 +1,6 @@ -package com.gitee.sop.servercommon.manager; +package com.gitee.sop.servercommon.route; import com.gitee.sop.servercommon.bean.ServiceApiInfo; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.servercommon.route.ServiceRouteInfo; import com.gitee.sop.servercommon.util.OpenUtil; import lombok.Getter; import lombok.extern.slf4j.Slf4j; @@ -26,6 +24,8 @@ public class ServiceRouteController { private static final String SECRET = "a3d9sf!1@odl90zd>fkASwq"; private static final String HEADER_RESTFUL = "restful"; + private static final ApiMetaBuilder apiMetaBuilder = new ApiMetaBuilder(); + @Autowired private RequestMappingHandlerMapping requestMappingHandlerMapping; @@ -51,10 +51,6 @@ public class ServiceRouteController { if (serviceId == null) { throw new IllegalArgumentException("未指定spring.application.name参数"); } - ApiMetaBuilder apiMetaBuilder = getApiMetaBuilder(); - String restful = request.getHeader(HEADER_RESTFUL); - boolean enableRestful = "true".equals(restful); - ServiceContext.getCurrentContext().set(ServiceContext.RESTFUL_KEY, enableRestful); ServiceApiInfo serviceApiInfo = apiMetaBuilder.getServiceApiInfo(serviceId, requestMappingHandlerMapping); ServiceRouteInfoBuilder serviceRouteInfoBuilder = new ServiceRouteInfoBuilder(environment); return serviceRouteInfoBuilder.build(serviceApiInfo); diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteInfoBuilder.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteInfoBuilder.java similarity index 94% rename from sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteInfoBuilder.java rename to sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteInfoBuilder.java index 2c2d7a68..b664bfd1 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/manager/ServiceRouteInfoBuilder.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/route/ServiceRouteInfoBuilder.java @@ -1,4 +1,4 @@ -package com.gitee.sop.servercommon.manager; +package com.gitee.sop.servercommon.route; import com.gitee.sop.servercommon.bean.ServiceApiInfo; import com.gitee.sop.servercommon.route.RouteDefinition; @@ -26,7 +26,7 @@ public class ServiceRouteInfoBuilder { private static final String DEFAULT_CONTEXT_PATH = "/"; - private Environment environment; + private final Environment environment; public ServiceRouteInfoBuilder(Environment environment) { this.environment = environment; @@ -60,9 +60,6 @@ public class ServiceRouteInfoBuilder { RouteDefinition routeDefinition = new RouteDefinition(); // 唯一id规则:接口名 + 版本号 String routeId = apiMeta.fetchNameVersion(); - if (!apiMeta.isOriginalMapping()) { - this.checkPath(routeId, "接口定义(" + routeId + ")不能有斜杠字符'/'"); - } BeanUtils.copyProperties(apiMeta, routeDefinition); routeDefinition.setId(routeId); routeDefinition.setFilters(Collections.emptyList()); diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/DocumentationPluginsManagerExt.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/DocumentationPluginsManagerExt.java index d3db16dc..b138c3de 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/DocumentationPluginsManagerExt.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/DocumentationPluginsManagerExt.java @@ -1,9 +1,7 @@ package com.gitee.sop.servercommon.swagger; -import com.gitee.sop.servercommon.annotation.ApiAbility; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.mapping.RouteUtil; import com.google.common.base.Optional; import io.swagger.annotations.Api; import org.springframework.core.annotation.Order; @@ -33,23 +31,13 @@ public class DocumentationPluginsManagerExt extends DocumentationPluginsManager private void setVendorExtension(Operation operation, OperationContext operationContext) { List vendorExtensions = operation.getVendorExtensions(); - Optional mappingOptional = operationContext.findAnnotation(ApiMapping.class); + Optional mappingOptional = operationContext.findAnnotation(Open.class); if (mappingOptional.isPresent()) { - ApiMapping apiMapping = mappingOptional.get(); - String name = apiMapping.value()[0]; - String version = buildVersion(apiMapping.version()); + Open open = mappingOptional.get(); + String name = open.value(); + String version = buildVersion(open.version()); vendorExtensions.add(new StringVendorExtension(SOP_NAME, name)); vendorExtensions.add(new StringVendorExtension(SOP_VERSION, version)); - } else { - Optional abilityOptional = operationContext.findAnnotation(ApiAbility.class); - if (abilityOptional.isPresent()) { - ApiAbility apiAbility = abilityOptional.get(); - String mappingPattern = operationContext.requestMappingPattern(); - String name = RouteUtil.buildApiName(mappingPattern); - String version = buildVersion(apiAbility.version()); - vendorExtensions.add(new StringVendorExtension(SOP_NAME, name)); - vendorExtensions.add(new StringVendorExtension(SOP_VERSION, version)); - } } Optional apiOptional = operationContext.findControllerAnnotation(Api.class); int order = 0; diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/SwaggerValidator.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/SwaggerValidator.java index ac2a9e8f..888d351e 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/SwaggerValidator.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/swagger/SwaggerValidator.java @@ -12,7 +12,7 @@ import java.io.PrintWriter; */ public class SwaggerValidator { - private String secret = "b749a2ec000f4f29"; + private final String secret = "b749a2ec000f4f29"; private boolean swaggerAccessProtected = true; @@ -20,9 +20,6 @@ public class SwaggerValidator { this.swaggerAccessProtected = swaggerAccessProtected; } - public SwaggerValidator() { - } - /** * swagger访问是否加密保护 * @return diff --git a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/util/OpenUtil.java b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/util/OpenUtil.java index 04a8461e..b048ea7b 100644 --- a/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/util/OpenUtil.java +++ b/sop-common/sop-service-common/src/main/java/com/gitee/sop/servercommon/util/OpenUtil.java @@ -5,13 +5,12 @@ import com.alibaba.fastjson.JSONObject; import lombok.extern.slf4j.Slf4j; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; -import org.springframework.core.annotation.AnnotationUtils; import org.springframework.http.MediaType; import org.springframework.util.DigestUtils; import javax.servlet.http.HttpServletRequest; -import java.lang.annotation.Annotation; -import java.lang.reflect.Method; +import java.io.UnsupportedEncodingException; +import java.net.URLDecoder; import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.HashMap; @@ -24,6 +23,33 @@ import java.util.Set; @Slf4j public class OpenUtil { + /** + * 将get类型的参数转换成map, + * + * @param query charset=utf-8&biz_content=xxx + * @return 返回map参数 + */ + public static Map parseQueryToMap(String query) { + if (query == null) { + return Collections.emptyMap(); + } + String[] queryList = StringUtils.split(query, '&'); + Map params = new HashMap<>(16); + for (String param : queryList) { + String[] paramArr = param.split("\\="); + if (paramArr.length == 2) { + try { + params.put(paramArr[0], URLDecoder.decode(paramArr[1], "UTF-8")); + } catch (UnsupportedEncodingException e) { + throw new RuntimeException(e); + } + } else if (paramArr.length == 1) { + params.put(paramArr[0], ""); + } + } + return params; + } + /** * 获取request中的参数 * @@ -94,21 +120,4 @@ public class OpenUtil { return serverSign.equals(sign); } - /** - * 在方法或方法对应的类上找指定的注解 - * @param method 方法 - * @param annotationClass 指定的注解 - * @param - * @return 返回指定注解,没有返回null - */ - public static T getAnnotationFromMethodOrClass(Method method, Class annotationClass) { - if (method == null) { - return null; - } - T annotation = AnnotationUtils.findAnnotation(method, annotationClass); - if (annotation == null) { - annotation = AnnotationUtils.findAnnotation(method.getDeclaringClass(), annotationClass); - } - return annotation; - } } diff --git a/sop-example/sop-springmvc/pom.xml b/sop-example/sop-springmvc/pom.xml index 43efd3c4..a241b294 100644 --- a/sop-example/sop-springmvc/pom.xml +++ b/sop-example/sop-springmvc/pom.xml @@ -35,6 +35,7 @@ 0.3.3
+ diff --git a/sop-example/sop-springmvc/src/main/java/com/gitee/app/config/OpenServiceConfig.java b/sop-example/sop-springmvc/src/main/java/com/gitee/app/config/OpenServiceConfig.java index 1e1703b3..331d0d46 100644 --- a/sop-example/sop-springmvc/src/main/java/com/gitee/app/config/OpenServiceConfig.java +++ b/sop-example/sop-springmvc/src/main/java/com/gitee/app/config/OpenServiceConfig.java @@ -8,7 +8,7 @@ import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.client.naming.utils.NetUtils; import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery; import com.gitee.sop.servercommon.bean.ServiceConfig; -import com.gitee.sop.servercommon.configuration.SpringMvcServiceConfiguration; +import com.gitee.sop.servercommon.configuration.ServiceConfiguration; import lombok.extern.slf4j.Slf4j; /** @@ -18,7 +18,7 @@ import lombok.extern.slf4j.Slf4j; */ @Slf4j @EnableNacosDiscovery(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848")) -public class OpenServiceConfig extends SpringMvcServiceConfiguration { +public class OpenServiceConfig extends ServiceConfiguration { public static final String SPRING_APPLICATION_NAME = "spring.application.name"; @@ -31,9 +31,9 @@ public class OpenServiceConfig extends SpringMvcServiceConfiguration { } /** 对应tomcat中的contextPath */ - private String contextPath = "/sop-springmvc"; - private String serviceId = "sop-springmvc"; - private int port = 2223; + private final String contextPath = "/sop-springmvc"; + private final String serviceId = "sop-springmvc"; + private final int port = 2223; @NacosInjected private NamingService namingService; diff --git a/sop-example/sop-springmvc/src/main/java/com/gitee/app/controller/HomeController.java b/sop-example/sop-springmvc/src/main/java/com/gitee/app/controller/HomeController.java index 7028c51b..2500930b 100644 --- a/sop-example/sop-springmvc/src/main/java/com/gitee/app/controller/HomeController.java +++ b/sop-example/sop-springmvc/src/main/java/com/gitee/app/controller/HomeController.java @@ -1,7 +1,7 @@ package com.gitee.app.controller; import com.gitee.app.model.Goods; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.slf4j.Logger; @@ -45,7 +45,8 @@ public class HomeController { @ApiOperation(value="获取商品", notes = "获取商品说明") - @ApiMapping(value = "springmvc.goods.get") + @Open("springmvc.goods.get") + @RequestMapping("/goods/get") @ResponseBody public Goods getGoods(Goods param) { Goods goods = new Goods(); diff --git a/sop-example/sop-story/pom.xml b/sop-example/sop-story/pom.xml index 5fdc63bd..3aafff93 100644 --- a/sop-example/sop-story/pom.xml +++ b/sop-example/sop-story/pom.xml @@ -32,7 +32,12 @@ com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery - + + + org.springframework.cloud diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/config/OpenServiceConfig.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/config/OpenServiceConfig.java index b1f4c6a0..d1a0fb7d 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/config/OpenServiceConfig.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/config/OpenServiceConfig.java @@ -4,10 +4,11 @@ import com.gitee.sop.servercommon.bean.ServiceConfig; import com.gitee.sop.servercommon.configuration.AlipayServiceConfiguration; import com.gitee.sop.servercommon.swagger.SwaggerSupport; import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; import springfox.documentation.swagger2.annotations.EnableSwagger2; /** - * 使用支付宝开放平台功能 + * 开放平台功能 * @author tanghc */ @Configuration @@ -38,11 +39,3 @@ public class OpenServiceConfig extends AlipayServiceConfiguration { } -/** - * 使用淘宝开放平台功能 - * @author tanghc - */ -//@Configuration -//public class OpenServiceConfig extends TaobaoServiceConfiguration { -// -//} diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController.java deleted file mode 100644 index 8614540e..00000000 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController.java +++ /dev/null @@ -1,297 +0,0 @@ -package com.gitee.sop.storyweb.controller; - -import com.alibaba.fastjson.JSON; -import com.alibaba.fastjson.JSONObject; -import com.gitee.sop.servercommon.annotation.ApiAbility; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.bean.OpenContext; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.storyweb.controller.param.CategoryParam; -import com.gitee.sop.storyweb.controller.param.StoryParam; -import com.gitee.sop.storyweb.controller.result.CategoryResult; -import com.gitee.sop.storyweb.controller.result.StoryResult; -import com.gitee.sop.storyweb.controller.result.TreeResult; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import lombok.Data; -import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PostMapping; -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; - -import javax.servlet.http.HttpServletRequest; -import java.util.Arrays; -import java.util.Date; -import java.util.List; - -/** - * 支付宝服务端,假设签名验证通过后,到达这里进行具体的业务处理。 - * - * @author tanghc - */ -@RestController -@Slf4j -@Api(tags = "故事接口") -public class AlipayController { - - @Autowired - private Environment environment; - - // http://localhost:2222/story_get - // 原生的接口,可正常调用 - @RequestMapping("story_get") - public StoryResult story_get() { - StoryResult result = new StoryResult(); - result.setId(1L); - result.setName("海底小纵队(原生)"); - return result; - } - - // http://localhost:2222/story.get/1.0/ - // 接口名,使用默认版本号 - @ApiMapping(value = "story.get") - public StoryResult storyget() { - // 获取开放平台参数 - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - String appId = openContext.getAppId(); - StoryResult result = new StoryResult(); - result.setId(1L); - result.setName("海底小纵队(默认版本号), app_id:" + appId); - return result; - } - - // http://localhost:2222/story.get/1.1/ - // 接口名 + 版本号 - @ApiMapping(value = "story.get", version = "1.1") - public StoryResult getStory2() { - StoryResult result = new StoryResult(); - result.setId(1L); - result.setName("海底小纵队1.0"); - return result; - } - - // http://localhost:2222/story.get/2.0/?name=111 - // 接口名 + 版本号 - // StoryParam对应biz_content内容 - @ApiMapping(value = "story.get", version = "2.0") - public StoryResult getStory20(StoryParam param) { - StoryResult result = new StoryResult(); - BeanUtils.copyProperties(param, result); - return result; - } - - // 忽略验证 - @ApiMapping(value = "story.get", version = "2.1", ignoreValidate = true) - public StoryResult getStory21(StoryParam story) { - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - // 此处的param和story参数是一样的 - StoryParam param = openContext.getBizObject(StoryParam.class); - boolean isSame = story == param; - StoryResult result = new StoryResult(); - result.setName(story.getName() + ", story.get2.1, ignoreValidate = true, story==param:" + isSame); - return result; - } - - /** - * 另一种方式,OpenContext泛型参数填bizObject类
- * 调用openContext.getBizObject()可直接获得对象
- * 此方式等价于: - *
-     * public Story getStory22(Story bizObject) {
-     *     OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext();
-     *     // 获取appid,更多方法查看OpenContext类
-     *     String appId = openContext.getAppId();
-     *     System.out.println(appId);
-     *     return bizObject;
-     * }
-     * 
- * - * @param openContext - * @return - */ - @ApiMapping(value = "story.get", version = "2.2") - public StoryResult getStory22(OpenContext openContext) { - StoryParam bizObject = openContext.getBizObject(); - // 获取appid,更多方法查看OpenContext类 - String appId = openContext.getAppId(); - StoryResult result = new StoryResult(); - result.setName("appId:" + appId + ", " + bizObject.getName()); - return result; - } - - @ApiMapping(value = "story.get", version = "2.3") - public StoryResult getStory23(StoryParam param, HttpServletRequest request) { - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - String appId = openContext.getAppId(); - System.out.println(appId); - StoryResult story = new StoryResult(); - story.setName("appId:" + appId + ", " + param.getName() + ",ip:" + request.getLocalAddr()); - return story; - } - - // http://localhost:2222/getStory2 - // 遗留接口具备开放平台能力 - @ApiAbility - @GetMapping("getStory2") - public StoryResult getStory2_0(@RequestBody JSONObject param) { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("海底小纵队(默认版本号),param:" + param); - return story; - } - - // http://localhost:2222/getStory33 - // 遗留接口具备开放平台能力 - @ApiAbility - @PostMapping("getStory33") - public StoryResult getStory22(@RequestBody StoryParam param) { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("遗留接口,param:" + param); - return story; - } - - // http://localhost:2222/getStory2?version=2.1 - // 遗留接口具备开放平台能力,在原来的基础上加版本号 - @ApiAbility(version = "2.1") - @GetMapping("getStory2") - public StoryResult getStory2_1() { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("海底小纵队2.1"); - return story; - } - - @ApiAbility(ignoreValidate = true) - @GetMapping("/empinfo/get") - @ApiOperation(value="遗留接口", notes = "遗留接口") - public StoryResult getEmpInfo() { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("遗留接口"); - return story; - } - - // http://localhost:2222/alipay.story.get/1.0/?name=Jim - @ApiOperation(value="获取故事信息", notes = "获取故事信息的详细信息") - @ApiMapping(value = "alipay.story.get") - public StoryResult getStory(StoryParam param) { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("海底小纵队(alipay.story.get1.0), port:" + environment.getProperty("server.port") + ", param:" + param); - return story; - } - - /** - * @param param 对应biz_content中的内容,并自动JSR-303校验 - * @return - */ - @ApiOperation(value="获取故事信息", notes = "获取故事信息的详细信息") - @ApiMapping(value = "alipay.story.get", version = "1.2") - public StoryResult getStory11(StoryParam param) { - StoryResult story2 = new StoryResult(); - story2.setId(1L); - story2.setName("海底小纵队(alipay.story.get1.2), param:" + param); - return story2; - } - - /** - * 验证字符串乱码问题 - * - * @param param - * @return - */ - @ApiMapping(value = "story.string.get", version = "1.0") - public String string(StoryParam param) { - StoryResult story2 = new StoryResult(); - story2.setId(1L); - story2.setName("海底小纵队"); - return JSON.toJSONString(story2); - } - - /** - * 参数绑定 - * - * @param story 对应biz_content中的内容,并自动JSR-303校验 - * @return - */ - @ApiOperation(value = "获取故事信息", notes = "说明接口的详细信息,介绍,用途,注意事项等。") - @ApiMapping(value = "alipay.story.find") - public StoryResult getStory2(StoryParam story) { - log.info("获取故事信息参数, story: {}", story); - // 获取其它参数 - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - String app_id = openContext.getAppId(); - StoryResult result = new StoryResult(); - result.setName("白雪公主, app_id:" + app_id); - result.setGmt_create(new Date()); - return result; - } - - @ApiOperation(value = "返回数组结果", notes = "返回数组结果") - @ApiMapping(value = "alipay.story.find2") - public List getStory3(StoryParam story) { - int index = 0; - StoryResult storyVO = new StoryResult(); - storyVO.setId(1L); - storyVO.setName("白雪公主, index:" + index++); - storyVO.setGmt_create(new Date()); - - StoryResult storyVO2 = new StoryResult(); - storyVO2.setId(1L); - storyVO2.setName("白雪公主, index:" + index++); - storyVO2.setGmt_create(new Date()); - - return Arrays.asList(storyVO, storyVO2); - } - - @ApiAbility - @RequestMapping("getJson") - public Object getJson(@RequestBody JSONObject param) { - return param; - } - - - /** - * 演示文档表格树 - * - * @param param - * @return - */ - @ApiOperation(value = "获取分类信息", notes = "演示表格树") - @ApiMapping(value = "alipay.category.get", method = RequestMethod.POST) - public CategoryResult getCategory(CategoryParam param) { - System.out.println(param); - StoryResult result = new StoryResult(); - result.setId(1L); - result.setName("白雪公主"); - result.setGmt_create(new Date()); - CategoryResult categoryResult = new CategoryResult(); - categoryResult.setCategoryName("娱乐"); - categoryResult.setStoryResult(result); - return categoryResult; - } - - /** - * 树状返回 - * - * @param param - * @return - */ - @ApiOperation(value = "树状返回", notes = "树状返回") - @ApiMapping(value = "alipay.tree.get", method = RequestMethod.POST) - public TreeResult tree(StoryParam param) { - return new TreeResult(); - } - - @Data - public static class P { - private String name; - } -} diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController2.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController2.java deleted file mode 100644 index 88629888..00000000 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/AlipayController2.java +++ /dev/null @@ -1,32 +0,0 @@ -package com.gitee.sop.storyweb.controller; - -import com.gitee.sop.servercommon.annotation.ApiAbility; -import com.gitee.sop.storyweb.controller.param.StoryParam; -import com.gitee.sop.storyweb.controller.result.StoryResult; -import io.swagger.annotations.Api; -import lombok.extern.slf4j.Slf4j; -import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -/** - * 支付宝服务端,假设签名验证通过后,到达这里进行具体的业务处理。 - * - * @author tanghc - */ -@RestController -@Slf4j -// 注解放在这里,表示类中的方法都具备接口开放能力 -@ApiAbility -public class AlipayController2 { - - // http://localhost:2222/getStory44 - // 遗留接口具备开放平台能力 - @PostMapping("/getStory44") - public StoryResult getStory22(@RequestBody StoryParam param) { - StoryResult story = new StoryResult(); - story.setId(1L); - story.setName("遗留接口44,param:" + param); - return story; - } -} diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DemoOrderController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DemoOrderController.java deleted file mode 100644 index 4dab0d29..00000000 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DemoOrderController.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.gitee.sop.storyweb.controller; - -import com.alibaba.fastjson.JSON; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.util.UploadUtil; -import lombok.Data; -import org.apache.commons.io.IOUtils; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.multipart.MultipartFile; - -import javax.servlet.http.HttpServletRequest; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collection; - -/** - * @author tanghc - */ -@RestController -public class DemoOrderController { - - @Value("${server.port}") - private String port; - - @ApiMapping("member.info.get") - public Object member(MemberInfoGetParam param, HttpServletRequest request) { - if ("tom".equals(param.name)) { - throw new IllegalArgumentException("name参数错误"); - } - Collection uploadFiles = UploadUtil.getUploadFiles(request); - for (MultipartFile uploadFile : uploadFiles) { - try { - System.out.println("文件名称:" + uploadFile.getOriginalFilename() - + " 表单名称:" + uploadFile.getName() - + " 文件内容:" + - IOUtils.toString(uploadFile.getInputStream(), StandardCharsets.UTF_8)); - } catch (IOException e) { - e.printStackTrace(); - } - } - System.out.println(param); - return JSON.parseObject("{\n" + - " \"id\": 123,\n" + - " \"name\": \"jim\",\n" + - " \"member_info\": {\n" + - " \"is_vip\": 1,\n" + - " \"vip_endtime\": \"2020-11-11 11:11:11\"\n" + - " }\n" + - "}", MemberInfoGetResult.class); - } - - - @Data - public static class MemberInfoGetParam { - private String name; - private Integer age; - private String address; - } - - @Data - public static class MemberInfoGetResult { - private Integer id; - private String name; - private MemberInfoGetResultMemberInfo member_info; - } - - @Data - public static class MemberInfoGetResultMemberInfo { - private Byte is_vip; - private String vip_endtime; - } - -} diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1001_BaseController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1001_BaseController.java new file mode 100644 index 00000000..87db552f --- /dev/null +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1001_BaseController.java @@ -0,0 +1,133 @@ +package com.gitee.sop.storyweb.controller; + +import com.gitee.sop.servercommon.annotation.Open; +import com.gitee.sop.storyweb.controller.param.CategoryParam; +import com.gitee.sop.storyweb.controller.param.StoryParam; +import com.gitee.sop.storyweb.controller.result.CategoryResult; +import com.gitee.sop.storyweb.controller.result.StoryResult; +import com.gitee.sop.storyweb.controller.result.TreeResult; +import io.swagger.annotations.Api; +import io.swagger.annotations.ApiOperation; +import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +import java.util.Arrays; +import java.util.Date; +import java.util.List; + +/** + * 签名验证通过后,到达这里进行具体的业务处理。 + * + * @author tanghc + */ +@RestController +@RequestMapping("story") +@Slf4j +@Api(tags = "故事接口") +public class Example1001_BaseController { + + // http://localhost:2222/stroy/get + // 原生的接口,可正常调用 + @RequestMapping("/get") + public StoryResult get() { + StoryResult result = new StoryResult(); + result.setId(1L); + result.setName("海底小纵队(原生)"); + return result; + } + + // 基础用法 + @ApiOperation(value = "获取故事信息", notes = "获取故事信息的详细信息") + @Open("story.get") + @RequestMapping("/get/v1") + public StoryResult get_v1(StoryParam param) { + StoryResult story = new StoryResult(); + story.setId(1L); + story.setName("海底小纵队(story.get1.0), " + "param:" + param); + return story; + } + + // 指定版本号 + @ApiOperation(value = "获取故事信息", notes = "获取故事信息的详细信息") + @Open(value = "story.get", version = "2.0") + @RequestMapping("/get/v2") + public StoryResult get_v2(StoryParam param) { + StoryResult story = new StoryResult(); + story.setId(1L); + story.setName("海底小纵队(story.get2.0), " + "param:" + param); + return story; + } + + // 忽略验证 + @Open(value = "story.get.ignore", ignoreValidate = true) + @RequestMapping("/get/ignore/v1") + public StoryResult getStory21(StoryParam story) { + StoryResult result = new StoryResult(); + result.setName(story.getName() + ", ignoreValidate = true"); + return result; + } + + // 返回数组结果 + @ApiOperation(value = "返回数组结果", notes = "返回数组结果") + @Open("story.list") + @RequestMapping("/list/v1") + public List getStory3(StoryParam story) { + int index = 0; + StoryResult storyVO = new StoryResult(); + storyVO.setId(1L); + storyVO.setName("白雪公主, index:" + index++); + storyVO.setGmt_create(new Date()); + + StoryResult storyVO2 = new StoryResult(); + storyVO2.setId(1L); + storyVO2.setName("白雪公主, index:" + index++); + storyVO2.setGmt_create(new Date()); + + return Arrays.asList(storyVO, storyVO2); + } + + // 演示文档表格树 + @ApiOperation(value = "获取分类信息", notes = "演示表格树") + @Open("category.get") + @PostMapping("/category/get/v1") + public CategoryResult getCategory(CategoryParam param) { + System.out.println(param); + StoryResult result = new StoryResult(); + result.setId(1L); + result.setName("白雪公主"); + result.setGmt_create(new Date()); + CategoryResult categoryResult = new CategoryResult(); + categoryResult.setCategoryName("娱乐"); + categoryResult.setStoryResult(result); + return categoryResult; + } + + // 演示文档页树状返回 + @ApiOperation(value = "树状返回", notes = "树状返回") + @Open("story.tree.get") + @PostMapping("/tree/v1") + public TreeResult tree(StoryParam param) { + int id = 0; + TreeResult parent = new TreeResult(); + parent.setId(++id); + parent.setName("父节点"); + parent.setPid(0); + + TreeResult child1 = new TreeResult(); + child1.setId(++id); + child1.setName("子节点1"); + child1.setPid(1); + + TreeResult child2 = new TreeResult(); + child2.setId(++id); + child2.setName("子节点2"); + child2.setPid(1); + + parent.setChildren(Arrays.asList(child1, child2)); + + return parent; + } + +} diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/FileUploadDemoController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1002_FileUploadController.java similarity index 90% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/FileUploadDemoController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1002_FileUploadController.java index e25608b9..815f1eb1 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/FileUploadDemoController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1002_FileUploadController.java @@ -1,6 +1,6 @@ package com.gitee.sop.storyweb.controller; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.servercommon.util.UploadUtil; import com.gitee.sop.storyweb.controller.param.FileUploadParam; import com.gitee.sop.storyweb.controller.param.FileUploadParam2; @@ -10,12 +10,14 @@ import io.swagger.annotations.ApiOperation; import io.swagger.annotations.Extension; import io.swagger.annotations.ExtensionProperty; import org.apache.commons.io.IOUtils; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletRequest; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Optional; @@ -25,8 +27,9 @@ import java.util.Optional; * @author tanghc */ @RestController +@RequestMapping("upload") @Api(tags = "文件上传", position = 2) -public class FileUploadDemoController { +public class Example1002_FileUploadController { /** * 方式1:将文件写在参数中,可直接获取。好处是可以校验是否上传 @@ -34,7 +37,8 @@ public class FileUploadDemoController { * @return */ @ApiOperation(value = "文件上传例1", notes = "上传文件demo") - @ApiMapping(value = "demo.file.upload") + @Open("file.upload") + @RequestMapping("file1") public FileUploadResult file1(FileUploadParam param) { // 获取上传的文件 MultipartFile file1 = param.getFile1(); @@ -59,7 +63,8 @@ public class FileUploadDemoController { @ApiOperation(value = "文件上传例2", notes = "可上传多个文件" // 多文件上传、不确定文件数量上传,必须申明下面这句,否则沙盒界面不会出现上传控件 , extensions = @Extension(properties = @ExtensionProperty(name = "multiple", value = "multiple"))) - @ApiMapping(value = "demo.file.upload2") + @Open("file.upload2") + @RequestMapping("file2") public FileUploadResult file2(FileUploadParam2 param, HttpServletRequest request) { System.out.println(param.getRemark()); FileUploadResult result = new FileUploadResult(); @@ -72,7 +77,8 @@ public class FileUploadDemoController { return result; } - @ApiMapping(value = "demo.file.upload3") + @Open("file.upload3") + @RequestMapping("file3") public FileUploadResult file3(FileUploadParam2 param, HttpServletRequest request) { System.out.println(param.getRemark()); FileUploadResult result = new FileUploadResult(); @@ -99,7 +105,7 @@ public class FileUploadDemoController { // 文件内容 String fileContent = null; try { - fileContent = IOUtils.toString(multipartFile.getInputStream(), "UTF-8"); + fileContent = IOUtils.toString(multipartFile.getInputStream(), StandardCharsets.UTF_8); } catch (IOException e) { e.printStackTrace(); } diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DownloadController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1003_DownloadController.java similarity index 77% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DownloadController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1003_DownloadController.java index 2b41bb9d..54441368 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/DownloadController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1003_DownloadController.java @@ -1,6 +1,6 @@ package com.gitee.sop.storyweb.controller; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.storyweb.controller.param.StoryParam; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; @@ -10,6 +10,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; +import org.springframework.web.bind.annotation.RequestMapping; import java.io.IOException; @@ -20,10 +21,12 @@ import java.io.IOException; */ @Api(tags = "文件下载", position = 3) @Controller -public class DownloadController { +@RequestMapping("download") +public class Example1003_DownloadController { @ApiOperation(value = "文件下载", notes = "演示文件下载") - @ApiMapping(value = "story.download", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE/* 这个一定要加,不然沙箱文档不起作用 */) + @Open("file.download") + @RequestMapping(value = "file1", produces = MediaType.APPLICATION_OCTET_STREAM_VALUE/* 这个一定要加,不然沙箱文档不起作用 */) public ResponseEntity download(StoryParam param) throws IOException { HttpHeaders headers = new HttpHeaders(); diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/JSR303DemoController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1004_JSR303Controller.java similarity index 67% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/JSR303DemoController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1004_JSR303Controller.java index 7551cd7a..d7f69249 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/JSR303DemoController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1004_JSR303Controller.java @@ -1,7 +1,8 @@ package com.gitee.sop.storyweb.controller; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.storyweb.controller.param.GoodsParam; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; @@ -11,9 +12,10 @@ import javax.servlet.http.HttpServletRequest; * @author tanghc */ @RestController -public class JSR303DemoController { +public class Example1004_JSR303Controller { - @ApiMapping(value = "goods.add") + @Open("goods.add") + @RequestMapping("jsr303") public Object addGoods(GoodsParam param, HttpServletRequest request) { System.out.println(request.getParameter("method")); return param; diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PermissionDemoController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_PermissionController.java similarity index 60% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PermissionDemoController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_PermissionController.java index 86321f14..7d3e2ea1 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PermissionDemoController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_PermissionController.java @@ -1,7 +1,8 @@ package com.gitee.sop.storyweb.controller; -import com.gitee.sop.servercommon.annotation.ApiMapping; +import com.gitee.sop.servercommon.annotation.Open; import com.gitee.sop.storyweb.controller.result.StoryResult; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** @@ -10,13 +11,14 @@ import org.springframework.web.bind.annotation.RestController; * @author tanghc */ @RestController -public class PermissionDemoController { +public class Example1005_PermissionController { - @ApiMapping(value = "permission.story.get", permission = true) + @Open(value = "story.get.permission", permission = true) + @RequestMapping("perm/get") public StoryResult getStory() { StoryResult story = new StoryResult(); story.setId(1L); - story.setName("海底小纵队(permission.story.get)"); + story.setName("海底小纵队(story.get.permission)"); return story; } diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/ThrowExceptionDemoController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_ThrowExceptionController.java similarity index 82% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/ThrowExceptionDemoController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_ThrowExceptionController.java index b43e647e..1f58d8e6 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/ThrowExceptionDemoController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1005_ThrowExceptionController.java @@ -1,10 +1,11 @@ package com.gitee.sop.storyweb.controller; +import com.gitee.sop.servercommon.annotation.Open; +import com.gitee.sop.servercommon.exception.ServiceException; import com.gitee.sop.storyweb.controller.param.GoodsUpdateParam; import com.gitee.sop.storyweb.message.GoodsErrorEnum; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.exception.ServiceException; import org.apache.commons.lang3.StringUtils; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** @@ -12,9 +13,10 @@ import org.springframework.web.bind.annotation.RestController; * @author tanghc */ @RestController -public class ThrowExceptionDemoController { +public class Example1005_ThrowExceptionController { - @ApiMapping(value = "goods.update") + @Open("goods.update") + @RequestMapping("ex") public Object updateGoods(GoodsUpdateParam param) { // 方式1 if ("iphone6".equals(param.getGoods_name())) { diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TokenController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1007_TokenController.java similarity index 52% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TokenController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1007_TokenController.java index ab28ff9b..4d966e28 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TokenController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1007_TokenController.java @@ -1,28 +1,30 @@ package com.gitee.sop.storyweb.controller; -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.bean.OpenContext; -import com.gitee.sop.servercommon.bean.ServiceContext; +import com.gitee.sop.servercommon.annotation.Open; +import com.gitee.sop.servercommon.bean.ParamNames; import com.gitee.sop.storyweb.controller.param.StoryParam; import com.gitee.sop.storyweb.controller.result.StoryResult; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; +import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; +import javax.servlet.http.HttpServletRequest; + /** * @author tanghc */ @RestController @Slf4j @Api(tags = "故事接口") -public class TokenController { +public class Example1007_TokenController { @ApiOperation(value="传递token", notes = "传递token") - @ApiMapping(value = "story.token.get", needToken = true/* 设置true,网关会校验token是否存在 */) - public StoryResult token(StoryParam story) { - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - String appAuthToken = openContext.getAppAuthToken(); + @Open(value = "story.get.token", needToken = true/* 设置true,网关会校验token是否存在 */) + @RequestMapping("token") + public StoryResult token(StoryParam story, HttpServletRequest request) { + String appAuthToken = request.getParameter(ParamNames.APP_AUTH_TOKEN_NAME); StoryResult result = new StoryResult(); result.setName("appAuthToken:" + appAuthToken); return result; diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TraditionalWebappController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1008_RestfulController.java similarity index 98% rename from sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TraditionalWebappController.java rename to sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1008_RestfulController.java index 08e88f8e..36de18b0 100644 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/TraditionalWebappController.java +++ b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/Example1008_RestfulController.java @@ -23,7 +23,7 @@ import java.util.Collection; @RestController @RequestMapping("food") @Api(tags = "食物接口") -public class TraditionalWebappController { +public class Example1008_RestfulController { // http://localhost:8081/rest/story-service/food/getFoodById?id=1 网关入口 diff --git a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PostJsonController.java b/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PostJsonController.java deleted file mode 100644 index 9ef28264..00000000 --- a/sop-example/sop-story/src/main/java/com/gitee/sop/storyweb/controller/PostJsonController.java +++ /dev/null @@ -1,41 +0,0 @@ -package com.gitee.sop.storyweb.controller; - -import com.gitee.sop.servercommon.annotation.ApiMapping; -import com.gitee.sop.servercommon.bean.OpenContext; -import com.gitee.sop.servercommon.bean.ServiceContext; -import com.gitee.sop.storyweb.controller.param.StoryParam; -import com.gitee.sop.storyweb.controller.result.StoryResult; -import org.apache.commons.lang3.StringUtils; -import org.springframework.web.bind.annotation.RequestBody; -import org.springframework.web.bind.annotation.RestController; - -import java.util.Arrays; -import java.util.List; - -/** - * @author tanghc - */ -@RestController -public class PostJsonController { - - /** - * 演示客户端使用json方式请求(application/json) - * @param param - * @return - */ - @ApiMapping("demo.post.json") - public StoryResult postJson(@RequestBody StoryParam param) { - // 获取开放平台请求参数 - OpenContext openContext = ServiceContext.getCurrentContext().getOpenContext(); - List params = Arrays.asList( - openContext.getAppId(), - openContext.getMethod(), - openContext.getVersion() - ); - StoryResult result = new StoryResult(); - result.setId(1L); - result.setName("参数:" + param.getName() + ", openParams:" + StringUtils.join(params)); - return result; - } - -} diff --git a/sop-example/sop-story/src/main/resources/application-dev.properties b/sop-example/sop-story/src/main/resources/application-dev.properties index 8957bc3f..435c9b99 100644 --- a/sop-example/sop-story/src/main/resources/application-dev.properties +++ b/sop-example/sop-story/src/main/resources/application-dev.properties @@ -1,4 +1,6 @@ server.port=2222 spring.application.name=story-service -# nacos注册中心 +# 注册中心 spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 +eureka.client.serviceUrl.defaultZone=http://localhost:1111/eureka/ + diff --git a/sop-gateway/pom.xml b/sop-gateway/pom.xml index cd7f9651..a4ebbf3d 100644 --- a/sop-gateway/pom.xml +++ b/sop-gateway/pom.xml @@ -17,16 +17,29 @@ com.gitee.sop - sop-bridge-gateway - + sop-bridge-nacos + 3.2.0-SNAPSHOT + + org.springframework.cloud + spring-cloud-starter-gateway + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-actuator + + com.gitee.sop - sop-gateway-common + sop-bridge-nacos + 3.2.0-SNAPSHOT - - com.alibaba.cloud - spring-cloud-starter-alibaba-nacos-discovery - - org.springframework.boot spring-boot-starter-web diff --git a/sop-website/src/main/java/com/gitee/sop/websiteserver/config/WebsiteConfig.java b/sop-website/src/main/java/com/gitee/sop/websiteserver/config/WebsiteConfig.java index 0142a941..d84c7fb5 100644 --- a/sop-website/src/main/java/com/gitee/sop/websiteserver/config/WebsiteConfig.java +++ b/sop-website/src/main/java/com/gitee/sop/websiteserver/config/WebsiteConfig.java @@ -4,8 +4,6 @@ import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; import com.gitee.sop.gatewaycommon.manager.EnvironmentContext; -import com.gitee.sop.gatewaycommon.route.EurekaRegistryListener; -import com.gitee.sop.gatewaycommon.route.NacosRegistryListener; import com.gitee.sop.gatewaycommon.route.RegistryListener; import com.gitee.sop.gatewaycommon.route.ServiceListener; import com.gitee.sop.websiteserver.listener.ServiceDocListener; @@ -14,7 +12,6 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.context.ApplicationEvent; @@ -65,21 +62,6 @@ public class WebsiteConfig implements ApplicationRunner { registryListener.onEvent(heartbeatEvent); } - /** - * 微服务路由加载 - */ - @Bean - @ConditionalOnProperty("spring.cloud.nacos.discovery.server-addr") - RegistryListener registryListenerNacos() { - return new NacosRegistryListener(); - } - - @Bean - @ConditionalOnProperty("eureka.client.serviceUrl.defaultZone") - RegistryListener registryListenerEureka() { - return new EurekaRegistryListener(); - } - @Bean @ConditionalOnMissingBean ServiceListener serviceListener() { diff --git a/sop-website/src/main/resources/META-INF/spring.factories b/sop-website/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..557afd6f --- /dev/null +++ b/sop-website/src/main/resources/META-INF/spring.factories @@ -0,0 +1,2 @@ +# 自定义自动配置类,如果有多个类,使用逗号(,)分隔,\正斜杠标示换行还可以读取到指定的类 +org.springframework.boot.autoconfigure.EnableAutoConfiguration=com.gitee.sop.bridge.SopRegisterAutoConfiguration diff --git a/sop-website/src/main/resources/application-dev.properties b/sop-website/src/main/resources/application-dev.properties index cce940d2..49feb0aa 100644 --- a/sop-website/src/main/resources/application-dev.properties +++ b/sop-website/src/main/resources/application-dev.properties @@ -2,8 +2,8 @@ server.port=8083 spring.application.name=sop-website # ------- 需要改的配置 ------- -# nacos地址 -nacos.url=127.0.0.1:8848 +# 注册中心地址 +register.url=127.0.0.1:8848 # 网关内网地址 # !!沙箱环境是提供给外部的测试环境,不能把正式环境当做沙箱环境来使用。 @@ -11,7 +11,9 @@ gateway.url=http://localhost:8081 # ------- 需要改的配置end ------- ## nacos cloud配置 -spring.cloud.nacos.discovery.server-addr=${nacos.url} +spring.cloud.nacos.discovery.server-addr=${register.url} +# eureka地址 +eureka.client.serviceUrl.defaultZone=${register.url} # 页面上显示的测试环境地址 api.url-test=http://open-test.yourdomain.com