diff --git a/.circleci/config.yml b/.circleci/config.yml index 4a705eee..3f260a24 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -24,7 +24,7 @@ jobs: - ~/.m2 - run: name: "Running build" - command: ./mvnw -Pspring -Pdocs clean install -U -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn -Dgpg.skip + command: ./mvnw -Pdocs clean install -U -nsu --batch-mode -Dmaven.test.redirectTestOutputToFile=true -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn -Dgpg.skip - run: name: "Aggregate test results" when: always diff --git a/.codecov.yml b/.codecov.yml new file mode 100644 index 00000000..20ecf1f1 --- /dev/null +++ b/.codecov.yml @@ -0,0 +1,5 @@ + +coverage: + status: + project: off + patch: off \ No newline at end of file diff --git a/eclipse/checkstyle-suppressions.xml b/eclipse/checkstyle-suppressions.xml new file mode 100644 index 00000000..a83004af --- /dev/null +++ b/eclipse/checkstyle-suppressions.xml @@ -0,0 +1,8 @@ + + + + + + \ No newline at end of file diff --git a/eclipse/eclipse-code-formatter.xml b/eclipse/eclipse-code-formatter.xml index b2dfe8ca..b6057671 100644 --- a/eclipse/eclipse-code-formatter.xml +++ b/eclipse/eclipse-code-formatter.xml @@ -1,296 +1,296 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/pom.xml b/pom.xml index 019e29cc..93be9ecf 100644 --- a/pom.xml +++ b/pom.xml @@ -17,7 +17,8 @@ 2.0.1.RELEASE pom Spring Cloud Alibaba - + Spring Cloud Alibaba + https://github.com/alibaba/spring-cloud-alibaba/tree/finchley @@ -83,7 +84,6 @@ 1.7.25 - 2.7.3 2.7.3 4.0.1 @@ -95,30 +95,15 @@ 2.8.2 2.21.0 1.6 + 0.8.3 spring-cloud-alibaba-dependencies - spring-cloud-alibaba-sentinel - spring-cloud-alibaba-sentinel-datasource - spring-cloud-alibaba-sentinel-gateway - spring-cloud-alibaba-nacos-config - spring-cloud-alibaba-nacos-discovery - spring-cloud-alibaba-seata - spring-cloud-stream-binder-rocketmq - spring-cloud-alibaba-nacos-config-server - spring-cloud-alibaba-dubbo - spring-cloud-alicloud-context spring-cloud-alibaba-examples spring-cloud-alibaba-docs - spring-cloud-starter-alibaba - spring-cloud-starter-alicloud - spring-cloud-alicloud-oss - spring-cloud-alicloud-acm - spring-cloud-alicloud-ans - spring-cloud-alicloud-schedulerx - spring-cloud-alicloud-sms - spring-cloud-alibaba-sidecar + spring-cloud-alibaba-starters + spring-cloud-alibaba-coverage @@ -207,7 +192,13 @@ org.apache.dubbo dubbo-spring-boot-starter - ${dubbo-spring-boot.version} + ${dubbo.version} + + + + org.apache.dubbo + dubbo-spring-boot-actuator + ${dubbo.version} diff --git a/spring-cloud-alibaba-coverage/pom.xml b/spring-cloud-alibaba-coverage/pom.xml new file mode 100644 index 00000000..1b460f9a --- /dev/null +++ b/spring-cloud-alibaba-coverage/pom.xml @@ -0,0 +1,115 @@ + + + + 4.0.0 + + + com.alibaba.cloud + spring-cloud-alibaba + 2.0.1.RELEASE + ../pom.xml + + + spring-cloud-alibaba-coverage + Spring Cloud Alibaba Coverage + + + + com.alibaba.cloud + spring-cloud-alibaba-sentinel-datasource + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + ${project.version} + + + + com.alibaba.cloud + spring-cloud-circuitbreaker-sentinel + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-seata + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config + ${project.version} + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-config-server + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-stream-rocketmq + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-bus-rocketmq + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sidecar + ${project.version} + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + ${project.version} + + + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + report-aggregate + test + + report-aggregate + + + ${basedir}/../target/site/jacoco + + + + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + true + + + + + + diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml index b2a3e81a..8210127c 100644 --- a/spring-cloud-alibaba-dependencies/pom.xml +++ b/spring-cloud-alibaba-dependencies/pom.xml @@ -19,19 +19,16 @@ 1.7.0 - 3.1.0 0.9.0 1.2.1 0.8.0 - 1.0.9 - 1.0.1 4.4.1 1.0.5 2.44.0 - 2.1.6 1.1.0 1.1.8.6 1.1.1 + 1.0.5 @@ -59,21 +56,6 @@ aliyun-java-sdk-core ${aliyun.sdk.version} - - com.alibaba.ans - ans-sdk - ${ans.version} - - - com.alibaba.edas.acm - acm-sdk - ${acm.version} - - - com.alibaba.edas - schedulerX-client - ${schedulerX.client.version} - @@ -172,6 +154,13 @@ sentinel-apache-dubbo-adapter ${sentinel.version} + + + com.alibaba.csp + sentinel-reactor-adapter + ${sentinel.version} + + com.alibaba.csp sentinel-cluster-server-default @@ -193,21 +182,19 @@ ${sentinel.version} + + com.alibaba.csp + sentinel-spring-webmvc-adapter + ${sentinel.version} + io.seata - seata-all + seata-spring-boot-starter ${seata.version} - - - com.aliyun.oss - aliyun-sdk-oss - ${oss.version} - - com.alibaba.cloud @@ -296,9 +283,10 @@ spring-cloud-starter-alibaba-sentinel ${project.version} + com.alibaba.cloud - spring-cloud-starter-alicloud-oss + spring-cloud-circuitbreaker-sentinel ${project.version} @@ -361,13 +349,6 @@ ${project.version} - - - com.alibaba.cloud - spring-cloud-starter-alicloud-sms - ${project.version} - - com.alibaba.cloud @@ -375,6 +356,11 @@ ${project.version} + + com.alibaba.spring + spring-context-support + ${spring.context.support.version} + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dubbo.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dubbo.adoc index 3dc8bc9e..c6222251 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dubbo.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dubbo.adoc @@ -26,7 +26,7 @@ Dubbo Spring Cloud 基于 Dubbo Spring Boot 2.7.3[1] 和 Spring Cloud 2.x 开发 [2]: Preview releases of Spring Cloud Alibaba are available: 0.9.0, 0.2.2, and 0.1.2 - https://spring.io/blog/2011/04/11/preview-releases-of-spring-cloud-alibaba-are-available-0-9-0-0-2-2-and-0-1-2 -[3]: 目前最新的 Spring Cloud “F” 版的版本为:`Finchley.SR2` - https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html +[3]: 目前最新的 Spring Cloud “F” 版的版本为:`Finchley.SR4` - https://cloud.spring.io/spring-cloud-static/Finchley.SR4/single/spring-cloud.html [4]: 当前Spring Cloud “G” 版为 `Greenwich.RELEASE` diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc index 74ad66ce..2a8832f5 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc @@ -1,10 +1,11 @@ == Spring Cloud Alibaba Sidecar -`Spring Cloud Alibaba Sidecar` 是一个用来快速**完美整合** Spring Cloud 与 *异构微服务* 的框架,灵感来自 -https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-sidecar[Spring Cloud Netflix Sidecar] 。目前支持的服务发现组件: +`Spring Cloud Alibaba Sidecar` 是一个用来快速**完美整合** Spring Cloud +与 *异构微服务* 的框架,灵感来自 +https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-netflix-sidecar[Spring +Cloud Netflix Sidecar] 。目前支持的服务发现组件: * Nacos - * Consul === 术语 @@ -25,26 +26,42 @@ https://github.com/spring-cloud/spring-cloud-netflix/tree/master/spring-cloud-ne 原因有两点: -* Spring Cloud子项目 `Spring Cloud Netflix Sidecar` 是可以快速整合异构微服务的。然而,Sidecar只支持使用Eureka作为服务发现,*如果使用其他服务发现组件就抓瞎了*。 -* *Sidecar是基于Zuul 1.x的*,Spring Cloud官方明确声明,未来将会逐步淘汰Zuul。今年早些时候,我有给Spring Cloud官方提出需求,希望官方实现一个基于Spring Cloud Gateway的新一代Sidecar,然而官方表示并没有该计划。详见:https://github.com/spring-cloud/spring-cloud-gateway/issues/735 +* Spring Cloud子项目 `Spring Cloud Netflix Sidecar` +是可以快速整合异构微服务的。然而,Sidecar只支持使用Eureka作为服务发现,*如果使用其他服务发现组件就抓瞎了*。 +* *Sidecar是基于Zuul 1.x的*,Spring +Cloud官方明确声明,未来将会逐步淘汰Zuul。今年早些时候,我有给Spring +Cloud官方提出需求,希望官方实现一个基于Spring Cloud +Gateway的新一代Sidecar,然而官方表示并没有该计划。详见:https://github.com/spring-cloud/spring-cloud-gateway/issues/735 既然没有,索性自己写了。 ==== 为什么不用Service Mesh? -* 目前Mesh主要使用场景在Kubernetes领域(Istio、Linkerd)等,大多将Kubernetes作为First Class支持,虽然Istio也可部署在非Kubernetes环境),而目前业界,Spring Cloud应用未必有试试Mesh的环境; -* 使用Alibaba Sidecar一个小组件就能解决问题了(核心代码不超过200行),引入整套Mesh方案,颇有点屠龙刀杀黄鳝的意思。 +* 目前Mesh主要使用场景在Kubernetes领域(Istio、Linkerd +2等,大多将Kubernetes作为First +Class支持,虽然Istio也可部署在非Kubernetes环境),而目前业界,Spring +Cloud应用未必有试试Mesh的环境; +* 使用Alibaba +Sidecar一个小组件就能解决问题了(核心代码不超过200行),引入整套Mesh方案,颇有点屠龙刀杀黄鳝的意思。 === 原理 * Alibaba -Sidecar根据配置的异构微服务的IP、端口等信息,*将异构微服务的IP/端口注册到服务发现组件上*。 -* Alibaba Sidecar实现了 *健康检查* ,Alibaba Sidecar会定时检测异构微服务是否健康。如果发现异构微服务不健康,Alibaba Sidecar会自动将代表异构微服务的Alibaba Sidecar实例下线;如果异构微服务恢复正常,则会自动上线。最长延迟是30秒,详见 `Alibaba SidecarChecker#check` 。 +Sidecar根据配置的异构微服务的IP、端口等信息,*将异构微服务的IP/端口注册到服务发现组件上* +。 +* Alibaba Sidecar实现了 *健康检查* ,Alibaba +Sidecar会定时检测异构微服务是否健康。如果发现异构微服务不健康,Alibaba +Sidecar会自动将代表异构微服务的Alibaba +Sidecar实例下线;如果异构微服务恢复正常,则会自动上线。最长延迟是30秒,详见 +`Alibaba SidecarChecker#check` 。 === 要求 -* 【必须】你的异构微服务需使用HTTP通信。这一点严格来说不算要求,因为Spring Cloud本身就是基于HTTP的; -* 【可选】如果微服务配置了 `sidecar.health-check-url`,则表示开启健康检查,此时,你的异构微服务需实现健康检查(可以是空实现,只要暴露一个端点,返回类似 `{"status": "UP"}` 的字符串即可)。 +* 【必须】你的异构微服务需使用HTTP通信。这一点严格来说不算要求,因为Spring +Cloud本身就是基于HTTP的; +* 【可选】如果微服务配置了 `sidecar.health-check-url` +,则表示开启健康检查,此时,你的异构微服务需实现健康检查(可以是空实现,只要暴露一个端点,返回类似 +`{"status": "UP"}` 的字符串即可)。 === 使用示例 @@ -92,7 +109,8 @@ endpoint: show-details: always ---- + -配置比较简单,就是把Alibaba Sidecar注册到Nacos上,然后添加了几行Alibaba Sidecar的配置。 +配置比较简单,就是把Alibaba Sidecar注册到Nacos上,然后添加了几行Alibaba +Sidecar的配置。 ==== 异构微服务 @@ -132,13 +150,16 @@ server.listen(8060, function() { ===== 测试1:Spring Cloud微服务完美调用异构微服务 -为你的Spring Cloud微服务整合Ribbon,然后构建 `http://node-service/\\**`,就可以请求到异构微服务的 `/**` 了。 +为你的Spring Cloud微服务整合Ribbon,然后构建 `http://node-service/**` +,就可以请求到异构微服务的 `/**` 了。 示例: -Ribbon请求 `http://node-service/` 会请求到 `http://localhost:8060/`,以此类推。 +Ribbon请求 `http://node-service/` 会请求到 `http://localhost:8060/` +,以此类推。 -至于断路器,正常为你的Spring Cloud微服务整合Sentinel或者Hystirx、Resilience4J即可 。 +至于断路器,正常为你的Spring +Cloud微服务整合Sentinel或者Hystirx、Resilience4J即可 。 ===== 测试2:异构微服务完美调用Spring Cloud微服务 @@ -146,13 +167,18 @@ Ribbon请求 `http://node-service/` 会请求到 `http://localhost:8060/`,以 示例: -如果你有一个Spring Cloud微服务叫做 `spring-cloud-microservice`,那么NodeJS应用只需构建 `http://localhost:8070/spring-cloud-microservice/\\**` ,Alibaba Sidecar就会把请求转发到 `spring-cloud-microservice` 的 `/**` 。 +如果你有一个Spring Cloud微服务叫做 `spring-cloud-microservice` +,那么NodeJS应用只需构建 +`http://localhost:8070/spring-cloud-microservice/**` ,Alibaba +Sidecar就会把请求转发到 `spring-cloud-microservice` 的 `/**` 。 -而Spring Cloud Gateway是整合了Ribbon的,所以实现了负载均衡;Spring Cloud Gateway还可以整合Sentinel或者Hystirx、Resilience4J,所以也带有了断路器。 +而Spring Cloud Gateway是整合了Ribbon的,所以实现了负载均衡;Spring Cloud +Gateway还可以整合Sentinel或者Hystirx、Resilience4J,所以也带有了断路器。 === Alibaba Sidecar优缺点分析 -Alibaba Sidecar的设计和Sidecar基本一致,优缺点和Sidecar的优缺点也是一样的。 +Alibaba +Sidecar的设计和Sidecar基本一致,优缺点和Sidecar的优缺点也是一样的。 优点: @@ -161,5 +187,8 @@ Alibaba Sidecar的设计和Sidecar基本一致,优缺点和Sidecar的优缺点 缺点: -* 每接入一个异构微服务实例,都需要额外部署一个Alibaba Sidecar实例,增加了部署成本(虽然这个成本在Kubernetes环境中几乎可以忽略不计(只需将Alibaba Sidecar实例和异构微服务作为一个Pod部署即可)); -* 异构微服务调用Spring Cloud微服务时,本质是把Alibaba Sidecar当网关在使用,经过了一层转发,性能有一定下降。 +* 每接入一个异构微服务实例,都需要额外部署一个Alibaba +Sidecar实例,增加了部署成本(虽然这个成本在Kubernetes环境中几乎可以忽略不计(只需将Alibaba +Sidecar实例和异构微服务作为一个Pod部署即可)); +* 异构微服务调用Spring Cloud微服务时,本质是把Alibaba +Sidecar当网关在使用,经过了一层转发,性能有一定下降。 diff --git a/spring-cloud-alibaba-examples/acm-example/acm-local-example/pom.xml b/spring-cloud-alibaba-examples/acm-example/acm-local-example/pom.xml deleted file mode 100644 index e0868c37..00000000 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - spring-cloud-alibaba-examples - com.alibaba.cloud - 2.0.1.RELEASE - ../../pom.xml - - 4.0.0 - acm-local-example - - - - com.alibaba.cloud - spring-cloud-starter-alicloud-acm - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/acm-example/acm-local-example/readme-zh.md b/spring-cloud-alibaba-examples/acm-example/acm-local-example/readme-zh.md deleted file mode 100644 index f76577aa..00000000 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/readme-zh.md +++ /dev/null @@ -1,46 +0,0 @@ -# ACM Local Example - -## 项目说明 - -本项目展示了,在Spring Cloud规范下,如何以最简单且免费的方式,使用ACM产品,将配置统一管理。 - -应用配置管理(Application Configuration Management,简称 ACM),其前身为淘宝内部配置中心 Diamond,是一款应用配置中心产品。基于该应用配置中心产品,您可以在微服务、DevOps、大数据等场景下极大地减轻配置管理的工作量的同时,保证配置的安全合规。更多 ACM 相关的信息,请参考 [ACM官网](https://www.aliyun.com/product/acm)。 - -## 示例 - -### 准备工作 - -ACM支持直接使用免费的轻量版配置中心,进行开发和调试工作。本示例也是基于轻量版配置中心的,因此我们需要首先安装和启动轻量版配置中心。 - -1. [下载轻量版配置中心](https://edas-public.oss-cn-hangzhou.aliyuncs.com/install_package/LCC/2018-11-01/edas-lite-configcenter.tar.gz?file=edas-lite-configcenter.tar.gz) - -2. 解压 edas-lite-configcenter.tar.gz ,然后执行以下命令。 - - cd edas-config-center && sh startup.sh - -出现以下内容说明轻量版配置中心启动成功。 - - Edas-config-center has been started successfully. - You can see more details in logs/config-center.log. - -3. 进入页面 http://127.0.0.1:8080,在左侧"配置列表"页面中,点击"添加"按钮,添加如下配置。 - - Group:DEFAULT_GROUP - DataId:acm-local.properties - Content:user.id=xiaolongzuo - -### 启动应用 - -直接运行main class,即`AcmApplication`。 - -### 查看效果 - -1. 使用`curl`可以看到在配置中心配置的user.id。 - - curl http://127.0.0.1:18089/ - -2. 进入页面 http://127.0.0.1:8080,在左侧"配置列表"页面中,更改user.id的值以后,再次使用`curl`命令,可以看到配置变化。 - - -如果您对 Spring Cloud ACM Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/AcmApplication.java b/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/AcmApplication.java deleted file mode 100644 index 16f3ef09..00000000 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/AcmApplication.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.cloud.client.discovery.EnableDiscoveryClient; - -/** - * @author xiaolongzuo - */ -@SpringBootApplication -@EnableDiscoveryClient -public class AcmApplication { - - public static void main(String[] args) { - SpringApplication.run(AcmApplication.class, args); - } - -} diff --git a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/EchoController.java b/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/EchoController.java deleted file mode 100644 index 74abd424..00000000 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/java/com/alibaba/cloud/examples/EchoController.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.cloud.context.config.annotation.RefreshScope; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author xiaolongzuo - */ -@RestController -@RefreshScope -public class EchoController { - - private static final Logger LOGGER = LoggerFactory.getLogger(EchoController.class); - - @Value("${user.id}") - private String userId; - - @RequestMapping(value = "/") - public String echo() { - LOGGER.info("User id is " + userId); - return userId; - } -} diff --git a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/resources/bootstrap.properties b/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/resources/bootstrap.properties deleted file mode 100644 index e6169cab..00000000 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/src/main/resources/bootstrap.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.application.name=acm-local -server.port=18089 -spring.cloud.alicloud.acm.server-list=127.0.0.1 -spring.cloud.alicloud.acm.server-port=8080 -management.endpoints.web.exposure.include=* \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/pom.xml b/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/pom.xml deleted file mode 100644 index b00f016f..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/pom.xml +++ /dev/null @@ -1,32 +0,0 @@ - - - - spring-cloud-alibaba-examples - com.alibaba.cloud - 2.0.1.RELEASE - ../../pom.xml - - 4.0.0 - ans-consumer-feign-example - - - - com.alibaba.cloud - spring-cloud-starter-alicloud-ans - - - org.springframework.cloud - spring-cloud-starter-openfeign - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/readme-zh.md b/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/readme-zh.md deleted file mode 100644 index 4b8ad372..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/readme-zh.md +++ /dev/null @@ -1,25 +0,0 @@ -# ANS Consumer Feign Example - -## 项目说明 - -本项目展示了,在Spring Cloud规范下,如何以最简单且免费的方式,使用Feign客户端,调用一个服务。 - -## 示例 - -### 准备工作 - -ans-provider-example已经成功启动,并发布服务成功。 - -### 启动应用 - -直接运行main class,即`ConsumerApplication`。 - -### 查看效果 - -使用`curl`命令可以看到应用打印出相应的调用日志,命令如下。 - - curl http://127.0.0.1:18082/ - - -如果您对 Spring Cloud ANS Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/EchoService.java b/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/EchoService.java deleted file mode 100644 index fb462f09..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/EchoService.java +++ /dev/null @@ -1,32 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.springframework.cloud.openfeign.FeignClient; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; - -/** - * @author xiaolongzuo - */ -@FeignClient(value = "ans-provider") -public interface EchoService { - - @RequestMapping(path = "echo/{str}") - String echo(@RequestParam("str") String param); - -} diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/HomeController.java b/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/HomeController.java deleted file mode 100644 index efe964b5..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/HomeController.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author xiaolongzuo - */ -@RestController -public class HomeController { - - private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); - - @Autowired - private EchoService echoService; - - @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json") - public String home() { - LOGGER.info("-----------------consumer调用开始-----------------"); - String param = "Nice to meet you."; - LOGGER.info("消费者传递参数:" + param); - String result = echoService.echo(param); - LOGGER.info("收到提供者响应:" + result); - return param + "
" + result; - } -} diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/resources/application.properties deleted file mode 100644 index ac697b88..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.application.name=feign-consumer -server.port=18083 -# The following configuration can be omitted. -spring.cloud.alicloud.ans.server-list=127.0.0.1 -spring.cloud.alicloud.ans.server-port=8080 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/pom.xml b/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/pom.xml deleted file mode 100644 index df401da4..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-alibaba-examples - 2.0.1.RELEASE - ../../pom.xml - - 4.0.0 - ans-consumer-ribbon-example - - - - com.alibaba.cloud - spring-cloud-starter-alicloud-ans - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/readme-zh.md b/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/readme-zh.md deleted file mode 100644 index b15eb89c..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/readme-zh.md +++ /dev/null @@ -1,25 +0,0 @@ -# ANS Consumer Ribbon Example - -## 项目说明 - -本项目展示了,在Spring Cloud规范下,如何以最简单且免费的方式,使用Ribbon客户端,调用一个服务。 - -## 示例 - -### 准备工作 - -ans-provider-example已经成功启动,并发布服务成功。 - -### 启动应用 - -直接运行main class,即`ConsumerApplication`。 - -### 查看效果 - -使用`curl`命令可以看到应用打印出相应的调用日志,命令如下。 - - curl http://127.0.0.1:18082/ - - -如果您对 Spring Cloud ANS Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/HomeController.java b/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/HomeController.java deleted file mode 100644 index 8827d2b4..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/HomeController.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import org.springframework.web.client.RestTemplate; - -/** - * @author xiaolongzuo - */ -@RestController -public class HomeController { - - private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); - - @Autowired - private RestTemplate restTemplate; - - @RequestMapping(value = "/", method = RequestMethod.GET, produces = "application/json") - public String home() { - LOGGER.info("-----------------consumer调用开始-----------------"); - String param = "Nice to meet you."; - LOGGER.info("消费者传递参数:" + param); - String result = restTemplate.getForObject("http://ans-provider/echo/" + param, - String.class); - LOGGER.info("收到提供者响应:" + result); - return param + "
" + result; - } -} diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/resources/application.properties deleted file mode 100644 index 33a7e5aa..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/resources/application.properties +++ /dev/null @@ -1,5 +0,0 @@ -spring.application.name=ribbon-consumer -server.port=18082 -# The following configuration can be omitted. -spring.cloud.alicloud.ans.server-list=127.0.0.1 -spring.cloud.alicloud.ans.server-port=8080 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/readme-zh.md b/spring-cloud-alibaba-examples/ans-example/ans-provider-example/readme-zh.md deleted file mode 100644 index 82b15874..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/readme-zh.md +++ /dev/null @@ -1,35 +0,0 @@ -# ANS Provider Example - -## 项目说明 - -本项目展示了,在Spring Cloud规范下,如何以最简单且免费的方式,发布一个服务。 - -## 示例 - -### 准备工作 - -ANS支持直接使用免费的轻量版配置中心,进行开发和调试工作。本示例也是基于轻量版配置中心的,因此我们需要首先安装和启动轻量版配置中心。 - -1. [下载轻量版配置中心](https://edas-public.oss-cn-hangzhou.aliyuncs.com/install_package/LCC/2018-11-01/edas-lite-configcenter.tar.gz?file=edas-lite-configcenter.tar.gz) - -2. 解压 edas-lite-configcenter.tar.gz ,然后执行以下命令。 - - cd edas-config-center && sh startup.sh - -出现以下内容说明轻量版配置中心启动成功。 - - Edas-config-center has been started successfully. - You can see more details in logs/config-center.log. - - -### 启动应用 - -直接运行main class,即`ProviderApplication`。 - -### 查看效果 - -进入页面 http://127.0.0.1:8080,在左侧"服务列表"页面中,可以看到一条名为`ans-provider`的服务。 - - -如果您对 Spring Cloud ANS Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/EchoController.java b/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/EchoController.java deleted file mode 100644 index 1430df9e..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/EchoController.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; - -/** - * @author xiaolongzuo - */ -@RestController -public class EchoController { - - private static final Logger LOGGER = LoggerFactory.getLogger(EchoController.class); - - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET, produces = "application/json") - public String echo(@PathVariable String str) { - LOGGER.info("-----------收到消费者请求-----------"); - LOGGER.info("收到消费者传递的参数:" + str); - String result = "Nice to meet you, too."; - LOGGER.info("提供者返回结果:" + result); - return result; - } -} diff --git a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/resources/application.properties deleted file mode 100644 index e5f6cdef..00000000 --- a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/resources/application.properties +++ /dev/null @@ -1,4 +0,0 @@ -spring.application.name=ans-provider -server.port=18081 -spring.cloud.alicloud.ans.server-list=127.0.0.1 -spring.cloud.alicloud.ans.server-port=8080 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/java/com/alibaba/cloud/examples/Application.java b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/java/com/alibaba/cloud/examples/Application.java index b94cf48e..ce693054 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/java/com/alibaba/cloud/examples/Application.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/java/com/alibaba/cloud/examples/Application.java @@ -1,11 +1,28 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import java.io.IOException; import java.io.StringReader; +import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; -import com.alibaba.cloud.nacos.NacosConfigProperties; +import com.alibaba.cloud.nacos.NacosConfigManager; import com.alibaba.nacos.api.config.listener.Listener; import org.springframework.beans.factory.annotation.Autowired; @@ -14,7 +31,9 @@ import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.context.config.annotation.RefreshScope; +import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @@ -24,9 +43,57 @@ import org.springframework.web.bind.annotation.RestController; */ @SpringBootApplication public class Application { + public static void main(String[] args) { SpringApplication.run(Application.class, args); } + + @Bean + public UserConfig userConfig() { + return new UserConfig(); + } + +} + +@ConfigurationProperties(prefix = "user") +class UserConfig { + + private int age; + + private String name; + + private Map map; + + public int getAge() { + return age; + } + + public void setAge(int age) { + this.age = age; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Map getMap() { + return map; + } + + public void setMap(Map map) { + this.map = map; + } + + @Override + public String toString() { + return "UserConfig{" + "age=" + age + ", name='" + name + '\'' + ", map=" + map + + '}'; + } + } @Component @@ -39,14 +106,14 @@ class SampleRunner implements ApplicationRunner { int userAge; @Autowired - private NacosConfigProperties nacosConfigProperties; + private NacosConfigManager nacosConfigManager; @Override public void run(ApplicationArguments args) throws Exception { System.out.println( String.format("Initial username=%s, userAge=%d", userName, userAge)); - nacosConfigProperties.configServiceInstance().addListener( + nacosConfigManager.getConfigService().addListener( "nacos-config-example.properties", "DEFAULT_GROUP", new Listener() { /** @@ -55,9 +122,8 @@ class SampleRunner implements ApplicationRunner { * For example, config data in Nacos is: * * user.name=Nacos user.age=25 - * * @param configInfo latest config data for specific dataId in Nacos - * server + * server */ @Override public void receiveConfigInfo(String configInfo) { @@ -77,20 +143,34 @@ class SampleRunner implements ApplicationRunner { } }); } + } @RestController @RefreshScope class SampleController { + @Autowired + UserConfig userConfig; + + @Autowired + private NacosConfigManager nacosConfigManager; + @Value("${user.name}") String userName; @Value("${user.age:25}") - int age; + Integer age; @RequestMapping("/user") public String simple() { - return "Hello Nacos Config!" + "Hello " + userName + " " + age + "!"; + return "Hello Nacos Config!" + "Hello " + userName + " " + age + " [UserConfig]: " + + userConfig + "!" + nacosConfigManager.getConfigService(); } -} \ No newline at end of file + + @RequestMapping("/bool") + public boolean bool() { + return (Boolean) (userConfig.getMap().get("2")); + } + +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/application.properties index c6e216ad..95efafd6 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/application.properties @@ -1,2 +1,3 @@ server.port=18084 -management.endpoints.web.exposure.include=* \ No newline at end of file +management.endpoints.web.exposure.include=* +management.endpoint.health.show-details=always diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties index 96890537..cea78476 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/src/main/resources/bootstrap.properties @@ -1,6 +1,25 @@ spring.application.name=nacos-config-example spring.cloud.nacos.config.server-addr=127.0.0.1:8848 + +#nacos certification information spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos -spring.cloud.nacos.config.shared-data-ids=base-common.properties,common.properties -spring.cloud.nacos.config.refreshable-dataids=common.properties \ No newline at end of file + +#spring.cloud.nacos.config.refreshable-dataids=common.properties +#spring.cloud.nacos.config.shared-data-ids=common.properties,base-common.properties +spring.cloud.nacos.config.shared-configs[0]= common333.properties +spring.cloud.nacos.config.shared-configs[1].data-id= common111.properties +spring.cloud.nacos.config.shared-configs[1].group= GROUP_APP1 +spring.cloud.nacos.config.shared-configs[1].refresh= true +spring.cloud.nacos.config.shared-configs[2]= common222.properties + +#spring.cloud.nacos.config.ext-config[0]=ext.properties +spring.cloud.nacos.config.extension-configs[0].data-id= extension1.properties +spring.cloud.nacos.config.extension-configs[0].refresh= true +spring.cloud.nacos.config.extension-configs[1]= extension2.properties +spring.cloud.nacos.config.extension-configs[2].data-id= extension3.json + + + +#spring.cloud.nacos.config.refresh-enabled=true + diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java index 6b12938d..b57ca0c0 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.cloud.examples.ConsumerApplication.EchoService; @@ -19,7 +35,7 @@ import org.springframework.web.client.RestTemplate; * @author xiaojing */ @SpringBootApplication -@EnableDiscoveryClient +@EnableDiscoveryClient(autoRegister = true) @EnableFeignClients public class ConsumerApplication { @@ -41,32 +57,38 @@ public class ConsumerApplication { SpringApplication.run(ConsumerApplication.class, args); } - @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class) + @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, + configuration = FeignConfiguration.class) public interface EchoService { - @GetMapping(value = "/echo/{str}") + + @GetMapping("/echo/{str}") String echo(@PathVariable("str") String str); - @GetMapping(value = "/divide") + @GetMapping("/divide") String divide(@RequestParam("a") Integer a, @RequestParam("b") Integer b); default String divide(Integer a) { return divide(a, 0); } - @GetMapping(value = "/notFound") + @GetMapping("/notFound") String notFound(); + } } class FeignConfiguration { + @Bean public EchoServiceFallback echoServiceFallback() { return new EchoServiceFallback(); } + } class EchoServiceFallback implements EchoService { + @Override public String echo(@PathVariable("str") String str) { return "echo fallback"; @@ -81,4 +103,5 @@ class EchoServiceFallback implements EchoService { public String notFound() { return "notFound fallback"; } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/TestController.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/TestController.java index 214fe52e..3e9946c4 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/TestController.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/TestController.java @@ -1,12 +1,27 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.cloud.examples.ConsumerApplication.EchoService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -44,54 +59,55 @@ public class TestController { // }); // } - @RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET) + @GetMapping("/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } - @RequestMapping(value = "/index", method = RequestMethod.GET) + @GetMapping("/index") public String index() { return restTemplate1.getForObject("http://service-provider", String.class); } - @RequestMapping(value = "/test", method = RequestMethod.GET) + @GetMapping("/test") public String test() { return restTemplate1.getForObject("http://service-provider/test", String.class); } - @RequestMapping(value = "/sleep", method = RequestMethod.GET) + @GetMapping("/sleep") public String sleep() { return restTemplate1.getForObject("http://service-provider/sleep", String.class); } - @RequestMapping(value = "/notFound-feign", method = RequestMethod.GET) + @GetMapping("/notFound-feign") public String notFound() { return echoService.notFound(); } - @RequestMapping(value = "/divide-feign", method = RequestMethod.GET) + @GetMapping("/divide-feign") public String divide(@RequestParam Integer a, @RequestParam Integer b) { return echoService.divide(a, b); } - @RequestMapping(value = "/divide-feign2", method = RequestMethod.GET) + @GetMapping("/divide-feign2") public String divide(@RequestParam Integer a) { return echoService.divide(a); } - @RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET) + @GetMapping("/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } - @RequestMapping(value = "/services/{service}", method = RequestMethod.GET) + @GetMapping("/services/{service}") public Object client(@PathVariable String service) { return discoveryClient.getInstances(service); } - @RequestMapping(value = "/services", method = RequestMethod.GET) + @GetMapping("/services") public Object services() { return discoveryClient.getServices(); } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java index b6d4af14..e0c691af 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,6 +17,7 @@ package com.alibaba.cloud.examples; public class UrlCleaner { + public static String clean(String url) { System.out.println("enter urlCleaner"); if (url.matches(".*/echo/.*")) { @@ -25,4 +26,5 @@ public class UrlCleaner { } return url; } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/application.properties index b8ec2bf4..cd4cc01d 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/application.properties @@ -1,8 +1,8 @@ spring.application.name=service-consumer server.port=18083 management.endpoints.web.exposure.include=* -#spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 -spring.cloud.nacos.server-addr=127.0.0.1:8848 +spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos @@ -17,4 +17,4 @@ spring.cloud.sentinel.datasource.ds1.file.rule-type=flow spring.cloud.sentinel.datasource.ds2.file.file=classpath: degraderule.json spring.cloud.sentinel.datasource.ds2.file.data-type=json -spring.cloud.sentinel.datasource.ds2.file.rule-type=degrade \ No newline at end of file +spring.cloud.sentinel.datasource.ds2.file.rule-type=degrade diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/flowrule.json b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/flowrule.json index 3dd01162..5fe40fcf 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/flowrule.json +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-example/src/main/resources/flowrule.json @@ -7,4 +7,4 @@ "limitApp": "default", "strategy": 0 } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/pom.xml new file mode 100644 index 00000000..f38168ad --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/pom.xml @@ -0,0 +1,79 @@ + + + + + com.alibaba.cloud + nacos-discovery-example + 2.0.1.RELEASE + + 4.0.0 + + + nacos-discovery-consumer-sclb-example + jar + Example demonstrating how to use nacos discovery + + + + + org.springframework.boot + spring-boot-starter-web + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + true + + + + + + diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/error.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/error.sh new file mode 100644 index 00000000..5602a98d --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/error.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/test` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-defaultmethod-error.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-defaultmethod-error.sh new file mode 100644 index 00000000..6efb8368 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-defaultmethod-error.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/divide-feign2?a=1` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-error.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-error.sh new file mode 100644 index 00000000..09db2477 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/feign-error.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/divide-feign?a=1\&b=0` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/index.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/index.sh new file mode 100644 index 00000000..7db176b8 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/index.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/index` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/resttemplate.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/resttemplate.sh new file mode 100644 index 00000000..e9d2e630 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/resttemplate.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/echo-rest/resttemplate` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/sleep.sh b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/sleep.sh new file mode 100644 index 00000000..423c3d15 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/scripts/sleep.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +n=1 +while [ $n -le 10 ] +do + echo `curl -s http://localhost:18083/sleep` + let n++ +done diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/ConsumerSCLBApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/ConsumerSCLBApplication.java new file mode 100644 index 00000000..9cb57f9b --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/ConsumerSCLBApplication.java @@ -0,0 +1,243 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples; + +import java.util.List; +import java.util.Random; + +import com.alibaba.cloud.examples.ConsumerSCLBApplication.EchoService; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Mono; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.client.loadbalancer.reactive.DefaultResponse; +import org.springframework.cloud.client.loadbalancer.reactive.EmptyResponse; +import org.springframework.cloud.client.loadbalancer.reactive.Request; +import org.springframework.cloud.client.loadbalancer.reactive.Response; +import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient; +import org.springframework.cloud.loadbalancer.core.NoopServiceInstanceListSupplier; +import org.springframework.cloud.loadbalancer.core.ReactorServiceInstanceLoadBalancer; +import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.client.RestTemplate; + +/** + * @author Jim + */ +@SpringBootApplication +@EnableDiscoveryClient(autoRegister = false) +@EnableFeignClients +public class ConsumerSCLBApplication { + + @LoadBalanced + @Bean + @SentinelRestTemplate(urlCleanerClass = UrlCleaner.class, urlCleaner = "clean") + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + @LoadBalanced + @Bean + @SentinelRestTemplate + public RestTemplate restTemplate1() { + return new RestTemplate(); + } + + public static void main(String[] args) { + SpringApplication.run(ConsumerSCLBApplication.class, args); + } + + @Configuration + @LoadBalancerClient(value = "service-provider", + configuration = MyLoadBalancerConfiguration.class) + class MySCLBConfiguration { + + } + + static class RandomLoadBalancer implements ReactorServiceInstanceLoadBalancer { + + private static final Logger log = LoggerFactory + .getLogger(RandomLoadBalancer.class); + + private ObjectProvider serviceInstanceListSupplierProvider; + + private final String serviceId; + + private final Random random; + + RandomLoadBalancer( + ObjectProvider serviceInstanceListSupplierProvider, + String serviceId) { + this.serviceInstanceListSupplierProvider = serviceInstanceListSupplierProvider; + this.serviceId = serviceId; + this.random = new Random(); + } + + @Override + public Mono> choose(Request request) { + log.info("random spring cloud loadbalacer active -.-"); + ServiceInstanceListSupplier supplier = serviceInstanceListSupplierProvider + .getIfAvailable(NoopServiceInstanceListSupplier::new); + return supplier.get().next().map(this::getInstanceResponse); + } + + private Response getInstanceResponse( + List instances) { + if (instances.isEmpty()) { + return new EmptyResponse(); + } + ServiceInstance instance = instances.get(random.nextInt(instances.size())); + + return new DefaultResponse(instance); + } + + } + + @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, + configuration = FeignConfiguration.class) + public interface EchoService { + + @GetMapping("/echo/{str}") + String echo(@PathVariable("str") String str); + + @GetMapping("/divide") + String divide(@RequestParam("a") Integer a, @RequestParam("b") Integer b); + + default String divide(Integer a) { + return divide(a, 0); + } + + @GetMapping("/notFound") + String notFound(); + + } + + @RestController + class TestController { + + @Autowired + private RestTemplate restTemplate; + + @Autowired + private RestTemplate restTemplate1; + + @Autowired + private EchoService echoService; + + @Autowired + private DiscoveryClient discoveryClient; + + @GetMapping("/echo-rest/{str}") + public String rest(@PathVariable String str) { + return restTemplate.getForObject("http://service-provider/echo/" + str, + String.class); + } + + @GetMapping("/echo-feign/{str}") + public String feign(@PathVariable String str) { + return echoService.echo(str); + } + + @GetMapping("/index") + public String index() { + return restTemplate1.getForObject("http://service-provider", String.class); + } + + @GetMapping("/test") + public String test() { + return restTemplate1.getForObject("http://service-provider/test", + String.class); + } + + @GetMapping("/sleep") + public String sleep() { + return restTemplate1.getForObject("http://service-provider/sleep", + String.class); + } + + @GetMapping("/notFound-feign") + public String notFound() { + return echoService.notFound(); + } + + @GetMapping("/divide-feign") + public String divide(@RequestParam Integer a, @RequestParam Integer b) { + return echoService.divide(a, b); + } + + @GetMapping("/divide-feign2") + public String divide(@RequestParam Integer a) { + return echoService.divide(a); + } + + @GetMapping("/services/{service}") + public Object client(@PathVariable String service) { + return discoveryClient.getInstances(service); + } + + @GetMapping("/services") + public Object services() { + return discoveryClient.getServices(); + } + + } + +} + +class FeignConfiguration { + + @Bean + public EchoServiceFallback echoServiceFallback() { + return new EchoServiceFallback(); + } + +} + +class EchoServiceFallback implements EchoService { + + @Override + public String echo(@PathVariable("str") String str) { + return "echo fallback"; + } + + @Override + public String divide(@RequestParam Integer a, @RequestParam Integer b) { + return "divide fallback"; + } + + @Override + public String notFound() { + return "notFound fallback"; + } + +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/MyLoadBalancerConfiguration.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/MyLoadBalancerConfiguration.java new file mode 100644 index 00000000..8ff96657 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/MyLoadBalancerConfiguration.java @@ -0,0 +1,44 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples; + +import com.alibaba.cloud.examples.ConsumerSCLBApplication.RandomLoadBalancer; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer; +import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier; +import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.core.env.Environment; + +/** + * @author Jim + */ +public class MyLoadBalancerConfiguration { + + @Bean + @ConditionalOnMissingBean + public ReactorLoadBalancer reactorServiceInstanceLoadBalancer( + Environment environment, + LoadBalancerClientFactory loadBalancerClientFactory) { + String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME); + return new RandomLoadBalancer(loadBalancerClientFactory.getLazyProvider(name, + ServiceInstanceListSupplier.class), name); + } + +} diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestService.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java similarity index 60% rename from spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestService.java rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java index 7681b3ad..e0c691af 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestService.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/java/com/alibaba/cloud/examples/UrlCleaner.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,15 +16,15 @@ package com.alibaba.cloud.examples; -import org.springframework.stereotype.Service; +public class UrlCleaner { -/** - * @author xiaolongzuo - */ -@Service -public class TestService { - - public void test() { - TestController.atomicInteger.incrementAndGet(); + public static String clean(String url) { + System.out.println("enter urlCleaner"); + if (url.matches(".*/echo/.*")) { + System.out.println("change url"); + url = url.replaceAll("/echo/.*", "/echo/{str}"); + } + return url; } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/application.properties new file mode 100644 index 00000000..656e35c5 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/application.properties @@ -0,0 +1,22 @@ +spring.application.name=service-consumer-sclb +server.port=18083 +management.endpoints.web.exposure.include=* +spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + +spring.cloud.nacos.username=nacos +spring.cloud.nacos.password=nacos + +spring.cloud.loadbalancer.ribbon.enabled=false + +feign.sentinel.enabled=true + +spring.cloud.sentinel.transport.dashboard=localhost:8080 +spring.cloud.sentinel.eager=true + +spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json +spring.cloud.sentinel.datasource.ds1.file.data-type=json +spring.cloud.sentinel.datasource.ds1.file.rule-type=flow + +spring.cloud.sentinel.datasource.ds2.file.file=classpath: degraderule.json +spring.cloud.sentinel.datasource.ds2.file.data-type=json +spring.cloud.sentinel.datasource.ds2.file.rule-type=degrade diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/degraderule.json b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/degraderule.json new file mode 100644 index 00000000..75e9d3b3 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/degraderule.json @@ -0,0 +1,26 @@ +[ + { + "resource": "GET:http://service-provider/test", + "count": 0.5, + "grade": 1, + "timeWindow": 30 + }, + { + "resource": "GET:http://service-provider", + "count": 0.5, + "grade": 1, + "timeWindow": 10 + }, + { + "resource": "GET:http://service-provider/sleep", + "count": 20.0, + "grade": 0, + "timeWindow": 30 + }, + { + "resource": "GET:http://service-provider/divide", + "count": 0.5, + "grade": 1, + "timeWindow": 30 + } +] \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/flowrule.json b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/flowrule.json new file mode 100644 index 00000000..5260bbe6 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-consumer-sclb-example/src/main/resources/flowrule.json @@ -0,0 +1,10 @@ +[ + { + "resource": "GET:http://service-provider/echo/{str}", + "controlBehavior": 0, + "count": 2, + "grade": 1, + "limitApp": "default", + "strategy": 0 + } +] diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java index c0bc7b01..94a84259 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import org.springframework.boot.SpringApplication; @@ -5,9 +21,8 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -25,17 +40,17 @@ public class ProviderApplication { @RestController class EchoController { - @RequestMapping(value = "/", method = RequestMethod.GET) + @GetMapping("/") public ResponseEntity index() { return new ResponseEntity("index error", HttpStatus.INTERNAL_SERVER_ERROR); } - @RequestMapping(value = "/test", method = RequestMethod.GET) + @GetMapping("/test") public ResponseEntity test() { return new ResponseEntity("error", HttpStatus.INTERNAL_SERVER_ERROR); } - @RequestMapping(value = "/sleep", method = RequestMethod.GET) + @GetMapping("/sleep") public String sleep() { try { Thread.sleep(1000L); @@ -46,14 +61,16 @@ public class ProviderApplication { return "ok"; } - @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET) + @GetMapping("/echo/{string}") public String echo(@PathVariable String string) { return "hello Nacos Discovery " + string; } - @RequestMapping(value = "/divide", method = RequestMethod.GET) + @GetMapping("/divide") public String divide(@RequestParam Integer a, @RequestParam Integer b) { return String.valueOf(a / b); } + } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/resources/application.properties index fad3190b..9732f8d5 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-provider-example/src/main/resources/application.properties @@ -1,6 +1,9 @@ server.port=18082 spring.application.name=service-provider spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos -management.endpoints.web.exposure.include=* \ No newline at end of file + +management.endpoints.web.exposure.include=* +management.endpoint.health.show-details=always diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/pom.xml similarity index 96% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/pom.xml rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/pom.xml index 54b044e4..14d9d4a0 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/pom.xml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/pom.xml @@ -10,7 +10,7 @@ 4.0.0 - nacos-discovery-spring-cloud-config-client + nacos-discovery-spring-cloud-config-client-example jar Example demonstrating how to use nacos discovery diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/GetConfigController.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/GetConfigController.java similarity index 78% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/GetConfigController.java rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/GetConfigController.java index f164e84a..32dfcff0 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/GetConfigController.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/GetConfigController.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,8 +17,7 @@ package com.alibaba.cloud.examples; import org.springframework.beans.factory.annotation.Value; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController @@ -27,9 +26,9 @@ public class GetConfigController { @Value("${config}") private String config; - @RequestMapping(value = "/config", method = RequestMethod.GET) + @GetMapping("/config") public String getConfig() { return config; } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java similarity index 94% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java index 4968266c..05bc6c5b 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigClientApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,4 +31,4 @@ public class SpringCloudConfigClientApplication { SpringApplication.run(SpringCloudConfigClientApplication.class, args); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/application.yml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/application.yml new file mode 100644 index 00000000..23cd46cd --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/application.yml @@ -0,0 +1 @@ +config: config-from-yml \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/bootstrap.yml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/bootstrap.yml similarity index 100% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/bootstrap.yml rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/bootstrap.yml index 9373ef50..9abeb329 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/bootstrap.yml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client-example/src/main/resources/bootstrap.yml @@ -3,10 +3,10 @@ spring: name: client cloud: nacos: - discovery: - server-addr: localhost:8848 username: nacos password: nacos + discovery: + server-addr: localhost:8848 config: discovery: enabled: true diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/application.yml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/application.yml deleted file mode 100644 index 8c1bb24e..00000000 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-client/src/main/resources/application.yml +++ /dev/null @@ -1,3 +0,0 @@ -config: config-from-yml -server: - port: 7777 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/pom.xml similarity index 95% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/pom.xml rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/pom.xml index 5495546d..ecff3bc6 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/pom.xml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/pom.xml @@ -10,7 +10,7 @@ 4.0.0 - nacos-discovery-with-spring-cloud-config-example + nacos-discovery-spring-cloud-config-server-example jar Example demonstrating how to use nacos discovery diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java similarity index 95% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java index 680ab2ec..a82bad8e 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/java/com/alibaba/cloud/examples/SpringCloudConfigServerApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -33,4 +33,4 @@ public class SpringCloudConfigServerApplication { SpringApplication.run(SpringCloudConfigServerApplication.class, args); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/resources/application.yml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/resources/application.yml similarity index 91% rename from spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/resources/application.yml rename to spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/resources/application.yml index 050cebec..cca1b446 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server/src/main/resources/application.yml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-discovery-spring-cloud-config-server-example/src/main/resources/application.yml @@ -6,12 +6,13 @@ spring: name: configserver cloud: nacos: - discovery: - server-addr: localhost:8848 username: nacos password: nacos + discovery: + server-addr: localhost:8848 config: server: git: uri: https://github.com/fangjian0423/blogimages - search-paths: / \ No newline at end of file + search-paths: / + diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/pom.xml new file mode 100644 index 00000000..9d7e8207 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/pom.xml @@ -0,0 +1,63 @@ + + + + + com.alibaba.cloud + nacos-discovery-example + 2.0.1.RELEASE + + 4.0.0 + + + nacos-reactivediscovery-consumer-example + jar + Example demonstrating how to use nacos discovery + + + + + org.springframework.boot + spring-boot-starter-webflux + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + + + + + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + true + + + + + + diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerReactiveApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerReactiveApplication.java new file mode 100644 index 00000000..b9e05737 --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerReactiveApplication.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples; + +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.context.annotation.Bean; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +/** + * @author Jim + */ +@SpringBootApplication +public class ConsumerReactiveApplication { + + @Bean + @LoadBalanced + public WebClient.Builder webClient() { + return WebClient.builder(); + } + + public static void main(String[] args) { + SpringApplication.run(ConsumerReactiveApplication.class, args); + } + + @RestController + class MyController { + + @Autowired + private ReactiveDiscoveryClient reactiveDiscoveryClient; + + @Autowired + private WebClient.Builder webClientBuilder; + + @GetMapping("/all-services") + public Flux allServices() { + return reactiveDiscoveryClient.getInstances("service-provider") + .map(serviceInstance -> serviceInstance.getHost() + ":" + + serviceInstance.getPort()); + } + + @GetMapping("/service-call/{name}") + public Mono serviceCall(@PathVariable("name") String name) { + return webClientBuilder.build().get() + .uri("http://service-provider/echo/" + name).retrieve() + .bodyToMono(String.class); + } + + } + +} diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/resources/application.properties new file mode 100644 index 00000000..4cdd63be --- /dev/null +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/nacos-reactivediscovery-consumer-example/src/main/resources/application.properties @@ -0,0 +1,9 @@ +spring.application.name=service-consumer-reactive +server.port=18083 +management.endpoints.web.exposure.include=* +spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + +spring.cloud.nacos.username=nacos +spring.cloud.nacos.password=nacos + +spring.cloud.loadbalancer.ribbon.enabled=false diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/pom.xml b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/pom.xml index 768d2d08..929f6a2b 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/pom.xml +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/pom.xml @@ -18,8 +18,10 @@ nacos-discovery-consumer-example + nacos-discovery-consumer-sclb-example + nacos-reactivediscovery-consumer-example nacos-discovery-provider-example - nacos-discovery-spring-cloud-config-client - nacos-discovery-spring-cloud-config-server + nacos-discovery-spring-cloud-config-server-example + nacos-discovery-spring-cloud-config-client-example diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/java/com/alibaba/cloud/examples/GatewayApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/java/com/alibaba/cloud/examples/GatewayApplication.java index a59a4168..6767357f 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/java/com/alibaba/cloud/examples/GatewayApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/java/com/alibaba/cloud/examples/GatewayApplication.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import org.springframework.boot.SpringApplication; diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/resources/application.properties index 69863aca..b2e3f9ef 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-discovery-example/src/main/resources/application.properties @@ -1,8 +1,10 @@ server.port=18085 spring.application.name=service-gateway spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos + management.endpoints.web.exposure.include=* # spring cloud route config @@ -10,4 +12,4 @@ spring.cloud.gateway.routes[0].id=nacos-route spring.cloud.gateway.routes[0].uri=lb://service-gateway-provider spring.cloud.gateway.routes[0].predicates[0].name=Path spring.cloud.gateway.routes[0].predicates[0].args[pattern]=/nacos/** -spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1 \ No newline at end of file +spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1 diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java index 718d06f7..a28fd943 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java @@ -1,11 +1,26 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @@ -22,14 +37,17 @@ public class ProviderApplication { @RestController class EchoController { - @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET) + + @GetMapping("/echo/{string}") public String echo(@PathVariable String string) { return "hello Nacos Discovery " + string; } - @RequestMapping(value = "/divide", method = RequestMethod.GET) + @GetMapping("/divide") public String divide(@RequestParam Integer a, @RequestParam Integer b) { return String.valueOf(a / b); } + } + } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/resources/application.properties index 482a1035..bda46189 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-gateway-example/nacos-gateway-provider-example/src/main/resources/application.properties @@ -1,6 +1,8 @@ server.port=18086 spring.application.name=service-gateway-provider spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 + spring.cloud.nacos.username=nacos spring.cloud.nacos.password=nacos -management.endpoints.web.exposure.include=* \ No newline at end of file + +management.endpoints.web.exposure.include=* diff --git a/spring-cloud-alibaba-examples/oss-example/readme-zh.md b/spring-cloud-alibaba-examples/oss-example/readme-zh.md deleted file mode 100644 index 4385636f..00000000 --- a/spring-cloud-alibaba-examples/oss-example/readme-zh.md +++ /dev/null @@ -1,156 +0,0 @@ -# OSS Example - -## 项目说明 - -如果您的应用是 Spring Cloud 应用,且需要使用阿里云的 OSS 服务进行云端的文件存储,例如电商业务中常见的商品图片存储,那么您可以使用 OSS starter 完成 Spring Cloud 应用的对象存储。 - -阿里云对象存储服务(Object Storage Service,简称 OSS),是阿里云提供的海量、安全、低成本、高可靠的云存储服务。您可以在任何应用、任何时间、任何地点存储和访问任意类型的数据。更多 OSS 相关的信息,请参考 [OSS官网](https://www.aliyun.com/product/oss)。 - -## 示例 - -### 接入 OSS -在启动示例进行演示之前,我们先了解一下如何接入 OSS。 - -**注意:本节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您只需修改 accessKey、secretKey、endpoint 即可。** - -1. 修改 pom.xml 文件,引入 alicloud-oss starter。 - - - com.alibaba.cloud - spring-cloud-starter-alicloud-oss - - -2. 在配置文件中配置 OSS 服务对应的 accessKey、secretKey 和 endpoint。 - - // application.properties - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - spring.cloud.alicloud.oss.endpoint=*** - - 以阿里云 accessKey、secretKey 为例,获取方式如下。 - - i. 在阿里云控制台界面,单击右上角头像,选择 accesskeys,或者直接登录[用户信息管理界面](https://usercenter.console.aliyun.com/): - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535371973274-3ebec90a-ebde-4eb7-96ed-5372f6b32fe0.png) - - ii. 获取 accessKey、secretKey: - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535372168883-b94a3d77-3f81-4938-b409-611945a9e21c.png) - - **注意:**如果您使用了阿里云 [STS服务](https://help.aliyun.com/document_detail/28756.html) 进行短期访问权限管理,则除了 accessKey、secretKey、endpoint 以外,还需配置 securityToken。 - -3. 注入 OSSClient 并进行文件上传下载等操作。 - - @Service - public class YourService { - @Autowired - private OSSClient ossClient; - - public void saveFile() { - // download file to local - ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("pathOfYourLocalFile")); - } - } - - **说明:**直接注入OSSClient 方式通常用于大量文件对象操作的场景。如果仅仅是需要读取文件对象内容,OSS Starter 也支持以 Resource 方式读取文件,详情请参考[下文](#1)。 - -### 启动应用 - - -1. 在应用的 /src/main/resources/application.properties 中添加基本配置信息和 OSS 配置。 - - spring.application.name=oss-example - server.port=18084 - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - spring.cloud.alicloud.oss.endpoint=*** - -2. 通过 IDE 直接启动或者编译打包后启动应用。 - - - IDE直接启动:找到主类 `OSSApplication`,执行 main 方法启动应用。 - - 打包编译后启动: - 1. 执行 `mvn clean package` 将工程编译打包; - 2. 执行 `java -jar oss-example.jar`启动应用。 - -应用启动后会自动在 OSS 上创建一个名为 `spring-cloud-alibaba-test` 的 Bucket。 - -### 上传或下载文件 - -#### 上传文件 -使用 curl 调用上传接口 upload。该接口会上传 classpath 下的的 oss-test.json 文件。文件内容是一段 json: - - curl http://localhost:18084/upload - -显示结果: - - // 如果配置正确,则输出 - upload success - // 如果上传的过程中发生异常,则会输出 upload fail: fail reason。比如accessKeyId配置错误的时候,fail reason内容如下 - upload fail: The OSS Access Key Id you provided does not exist in our records. [ErrorCode]: InvalidAccessKeyId [RequestId]: RequestId [HostId]: xxx.oss-cn-beijing.aliyuncs.com [ResponseError]: InvalidAccessKeyId The OSS Access Key Id you provided does not exist in our records. RequestId xxx.oss-cn-beijing.aliyuncs.com xxx-accessKeyId - -#### 下载文件 -使用 curl 调用下载接口 download。该接口会下载刚才用 upload 接口上传的 oss-test.json 文件,并打印文件内容到结果中: - - curl http://localhost:18084/download - -显示结果: - - // 如果配置正确,则输出 - download success, content: { "name": "oss-test" } - // 下载的过程中如果发生异常,则会输出download fail: fail reason。比如accessKeyId配置错误,则fail reason内容如下 - download fail: The OSS Access Key Id you provided does not exist in our records. [ErrorCode]: InvalidAccessKeyId [RequestId]: RequestId [HostId]: xxx.oss-cn-beijing.aliyuncs.com [ResponseError]: InvalidAccessKeyId The OSS Access Key Id you provided does not exist in our records. RequestId sxxx.oss-cn-beijing.aliyuncs.com xxx-accessKeyId - - - -### 在 OSS 上验证结果 - -完成文件上传或者下载操作后,可以登录 OSS 控制台进行验证。 - -1. 登陆[OSS控制台](https://oss.console.aliyun.com/),可以看到左侧 Bucket 列表新增一个名字为`spring-cloud-alibaba-test`的 Bucket。 - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535369224513-387afdf9-6078-4a42-9f18-d9fe9926a9cd.png) - -2. 单击`spring-cloud-alibaba-test` Bucket,选择 `文件管理` 页签,发现上传的 oss-test 文件。上传的 objectName 为`oss-test.json`。目录和文件以'/'符号分割。 - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535615378605-df1381e9-c5ff-4da1-b3b3-ce9acfef313f.png) - - -## 查看 Endpoint 信息 - -Spring Boot 应用支持通过 Endpoint 来暴露相关信息,OSS Starter 也支持这一点。 - -**前提条件:** - -在 maven 中添加 `spring-boot-starter-actuator`依赖,并在配置中允许 Endpoints 的访问。 - -- Spring Boot1.x 中添加配置 `management.security.enabled=false` -- Spring Boot2.x 中添加配置 `management.endpoints.web.exposure.include=*` - -Spring Boot1.x 可以通过访问 http://127.0.0.1:18084/oss 来查看 OSS Endpoint 的信息。 - -Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/actuator/oss 来访问。 - -Endpoint 内部会显示所有的 OSSClient 配置信息,以及该 OSSClient 对应的 Bucket 列表。 - -![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535373658171-20674565-6fe1-4e1e-a596-1dd6f4159ec3.png) - -

以 Resource 的形式读取文件

- -OSS Starter 支持以 Resource 的形式得到文件对象。如果只需读取少量文件,您可以使用这种方式。 - -**使用方法:** - -只需配置 OSS 协议对应的 Resource 即可: - - @Value("oss://spring-cloud-alibaba/oss-test") - private Resource file; - - // 文件内容的读取 - StreamUtils.copyToString(file.getInputStream(), Charset.forName(CharEncoding.UTF_8)) - -## 关闭 OSSClient 服务 -如果您不再需要 OSS 服务,您也无需手动关闭 OSSClient。在 ApplicationContext close 的时候,OSS Starter 会在 `OSSApplicationListener` 中调用所有 OSSClient 的 shutdown 方法。 - - -如果您对 Spring Cloud OSS Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/oss-example/readme.md b/spring-cloud-alibaba-examples/oss-example/readme.md deleted file mode 100644 index 76e7f899..00000000 --- a/spring-cloud-alibaba-examples/oss-example/readme.md +++ /dev/null @@ -1,150 +0,0 @@ -# OSS Example -## Introduction - -If your applications are Spring Cloud applications and you need to use Alibaba Cloud's OSS service for file storage (for example, storing commodity image for your e-commerce business), you can use OSS starter. This topic provides an example to illustrate how to use OSS starter to implement object storage for Spring Cloud applications. - -[Alibaba Cloud Object Storage Service (OSS)](https://www.alibabacloud.com/product/oss) is an encrypted, secure, cost-effective, and easy-to-use object storage service that enables you to store, back up, and archive large amounts of data in the cloud. - - -## Demo - -### Connect to OSS - -Before we start the demo, let's learn how to connect OSS to a Spring Cloud application. -**Note: This section is to show you how to connect to oss. The actual configurations have been completed in the following example, and you only need to specify your accessKey, secretKey and endpoint.** - -1. Add dependency spring-cloud-starter-alicloud-oss in the pom.xml file in your Spring Cloud project. - - - com.alibaba.cloud - spring-cloud-starter-alicloud-oss - - -2. Configure accessKeyId, secretAccessKey and region in application.properties. - - // application.properties - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - spring.cloud.alicloud.oss.endpoint=*** - - To get accessKey, secretKey, follow these steps: - - 1. On the Alibaba Cloud console, click your avatar on the upper-right corner and click accesskeys. Or visit [User Management](https://usercenter.console.aliyun.com/) page directly: - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535464041257-5c7ae997-daff-45b3-89d4-02d578da4ac7.png) - - 2. Get your accessKey、secretKey: - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535464098793-517491f6-156b-4a98-a5a4-6113cb3c01a4.png) - - **Note:** If you are using [STS](https://www.alibabacloud.com/help/doc-detail/28756.html), you should configure securityToken in addition to accessKey, secretKey, and endpoint. - -3. Inject OSSClient and use it to upload files to the OSS server and download a file from OSS server. - - @Service - public class YourService { - @Autowired - private OSSClient ossClient; - - public void saveFile() { - // download file to local - ossClient.getObject(new GetObjectRequest(bucketName, objectName), new File("pathOfYourLocalFile")); - } - } - -**Note:** Direct injection into the OSSClient mode is typically used for scenarios where you need to handle a large number of file objects. If you only need to read the contents of the file object, OSS Starter also supports reading the file in [Resource mode](#1). - -### Start Application - -1. Add necessary configurations to file `/src/main/resources/application.properties`. - - spring.application.name=oss-example - server.port=18084 - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - spring.cloud.alicloud.oss.endpoint=*** - -2. Start the application in IDE or by building a fatjar. - - - Start in IDE: Find main class `OSSApplication`, and execute the main method. - - Build a fatjar: - 1. Execute command `mvn clean package` to build a fatjar. - 2. Run command `java -jar oss-example.jar` to start the application. - -After startup, a bucket called 'spring-cloud-alibaba-test' is automatically created in OSS. - -### Upload or download files - -#### Upload files -Run `curl` command to upload files. It will upload file 'oss-test.json' in the `classpath` directory. The content of this file is JSON string: - - curl http://localhost:18084/upload - -Results: - - // If configurations are correct, the output will be as follows - upload success - // If an error occurs during uploading, the output will be 'upload fail: fail reason'. For example, if accessKeyId is wrong,the output will be - upload fail: The OSS Access Key Id you provided does not exist in our records. [ErrorCode]: InvalidAccessKeyId [RequestId]: RequestId [HostId]: xxx.oss-cn-beijing.aliyuncs.com [ResponseError]: InvalidAccessKeyId The OSS Access Key Id you provided does not exist in our records. RequestId xxx.oss-cn-beijing.aliyuncs.com xxx-accessKeyId - -#### Download files -Use `curl` command to download files. It will download the oss-test.json file that you uploaded just now and print in result: - - curl http://localhost:18084/download - -Results: - - // If configurations are correct, the output will be as follows - download success, content: { "name": "oss-tes" } - // If an error occurs during downloading, the output will be 'download fail: fail reason'. For example, if accessKeyId is wrong,fail reason will be as follows - download fail: The OSS Access Key Id you provided does not exist in our records. [ErrorCode]: InvalidAccessKeyId [RequestId]: RequestId [HostId]: xxx.oss-cn-beijing.aliyuncs.com [ResponseError]: InvalidAccessKeyId The OSS Access Key Id you provided does not exist in our records. RequestId sxxx.oss-cn-beijing.aliyuncs.com xxx-accessKeyId - - -### Verify results on OSS - -You can verify results on the OSS console when you finish uploading or downloading files. -1. Log on to the [OSS console](https://oss.console.aliyun.com/),and you will find a bucket named `spring-cloud-alibaba-test`. - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535464204462-ccebb9e0-7233-499c-8dec-8b8348231b2b.png) - -2. Click the `spring-cloud-alibaba-test` bucket, select the Files tab, and you will find the oss-test.json file. The objectName of the file is 'oss-test.json'. File directory and file is separated by '/'. - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535618026281-613a338c-f89c-4c7b-8b04-d404d1320699.png) - - -## Endpoint - -OSS starter also supports the implementation of Spring Boot actuator endpoints. - -**Prerequisite:** - -Add denpendency `spring-boot-starter-actuator` to your pom.xml file, and configure your endpoint security stategy. - -- Spring Boot1.x: Add configuration `management.security.enabled=false` -- Spring Boot2.x: Add configuration `management.endpoints.web.exposure.include=*` - -To view the endpoint information, visit the following URLs: - -Spring Boot1.x: OSS Endpoint URL is http://127.0.0.1:18084/oss. - -Spring Boot2.x: OSS Endpoint URL is http://127.0.0.1:18084/actuator/oss. - -Endpoint will show the configurations and the list of buckets of all OSSClients. - -![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535373658171-20674565-6fe1-4e1e-a596-1dd6f4159ec3.png) - -

Read file using resource mode

- -OSS Starter supports getting file objects by `Spring Resource`. Simply configure OSS protocol of the resource: - - @Value("oss://spring-cloud-alibaba/oss-test") - private Resource file; - - // read file content - StreamUtils.copyToString(file.getInputStream(), Charset.forName(CharEncoding.UTF_8)) - -## Stop OSSClient service -You do not need to manually shut down OSSClient. OSS Starter calls all OSSClient shutdown methods in the `OSSApplicationListener` during ApplicationContext close. - -If you have any feedback or suggestions for Spring Cloud OSS Starter, please don't hesitate to tell us by submitting github issues or via other community channels. - diff --git a/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssApplication.java b/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssApplication.java deleted file mode 100644 index 3c2205c7..00000000 --- a/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssApplication.java +++ /dev/null @@ -1,51 +0,0 @@ -package com.alibaba.cloud.examples; - -import java.net.URISyntaxException; - -import com.aliyun.oss.OSS; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.ApplicationArguments; -import org.springframework.boot.ApplicationRunner; -import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.context.annotation.Bean; - -/** - * OSS Application - * - * @author Jim - */ -@SpringBootApplication -public class OssApplication { - - public static final String BUCKET_NAME = "spring-cloud-alibaba"; - - public static void main(String[] args) throws URISyntaxException { - SpringApplication.run(OssApplication.class, args); - } - - @Bean - public AppRunner appRunner() { - return new AppRunner(); - } - - class AppRunner implements ApplicationRunner { - @Autowired - private OSS ossClient; - - @Override - public void run(ApplicationArguments args) throws Exception { - try { - if (!ossClient.doesBucketExist(BUCKET_NAME)) { - ossClient.createBucket(BUCKET_NAME); - } - } - catch (Exception e) { - System.err.println("oss handle bucket error: " + e.getMessage()); - System.exit(-1); - } - } - } - -} diff --git a/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssController.java b/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssController.java deleted file mode 100644 index 9628f950..00000000 --- a/spring-cloud-alibaba-examples/oss-example/src/main/java/com/alibaba/cloud/examples/OssController.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import java.io.InputStream; -import java.io.OutputStream; -import java.nio.charset.Charset; - -import com.aliyun.oss.OSS; -import com.aliyun.oss.common.utils.IOUtils; -import com.aliyun.oss.model.OSSObject; -import org.apache.commons.codec.CharEncoding; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.core.io.Resource; -import org.springframework.core.io.WritableResource; -import org.springframework.util.StreamUtils; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - -/** - * OSS Controller. - * - * @author Jim - */ -@RestController -public class OssController { - - @Autowired - private OSS ossClient; - - @Value("classpath:/oss-test.json") - private Resource localFile; - - @Value("oss://" + OssApplication.BUCKET_NAME + "/oss-test.json") - private Resource remoteFile; - - @GetMapping("/upload") - public String upload() { - try { - ossClient.putObject(OssApplication.BUCKET_NAME, "oss-test.json", this - .getClass().getClassLoader().getResourceAsStream("oss-test.json")); - } - catch (Exception e) { - e.printStackTrace(); - return "upload fail: " + e.getMessage(); - } - return "upload success"; - } - - @GetMapping("/file-resource") - public String fileResource() { - try { - return "get file resource success. content: " + StreamUtils.copyToString( - remoteFile.getInputStream(), Charset.forName(CharEncoding.UTF_8)); - } - catch (Exception e) { - e.printStackTrace(); - return "get resource fail: " + e.getMessage(); - } - } - - @GetMapping("/download") - public String download() { - try { - OSSObject ossObject = ossClient.getObject(OssApplication.BUCKET_NAME, - "oss-test.json"); - return "download success, content: " + IOUtils - .readStreamAsString(ossObject.getObjectContent(), CharEncoding.UTF_8); - } - catch (Exception e) { - e.printStackTrace(); - return "download fail: " + e.getMessage(); - } - } - - @GetMapping("/upload2") - public String uploadWithOutputStream() { - try { - try (OutputStream outputStream = ((WritableResource) this.remoteFile) - .getOutputStream(); - InputStream inputStream = localFile.getInputStream()) { - StreamUtils.copy(inputStream, outputStream); - } - } - catch (Exception ex) { - ex.printStackTrace(); - return "upload with outputStream failed"; - } - return "upload success"; - } - -} diff --git a/spring-cloud-alibaba-examples/oss-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/oss-example/src/main/resources/application.properties deleted file mode 100644 index 59c650d3..00000000 --- a/spring-cloud-alibaba-examples/oss-example/src/main/resources/application.properties +++ /dev/null @@ -1,6 +0,0 @@ -spring.application.name=oss-example -server.port=18084 -spring.cloud.alicloud.access-key=AK -spring.cloud.alicloud.secret-key=SK -spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com -management.endpoints.web.exposure.include=* diff --git a/spring-cloud-alibaba-examples/oss-example/src/main/resources/oss-test.json b/spring-cloud-alibaba-examples/oss-example/src/main/resources/oss-test.json deleted file mode 100644 index 68682f46..00000000 --- a/spring-cloud-alibaba-examples/oss-example/src/main/resources/oss-test.json +++ /dev/null @@ -1,3 +0,0 @@ -{ - "name": "oss-test" -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/pom.xml b/spring-cloud-alibaba-examples/pom.xml index f108f01c..427b7f72 100644 --- a/spring-cloud-alibaba-examples/pom.xml +++ b/spring-cloud-alibaba-examples/pom.xml @@ -8,8 +8,8 @@ 2.0.1.RELEASE ../pom.xml - 4.0.0 + 4.0.0 spring-cloud-alibaba-examples pom @@ -21,27 +21,24 @@ sentinel-example/sentinel-dubbo-example/sentinel-dubbo-provider-example sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example sentinel-example/sentinel-dubbo-example/sentinel-dubbo-api + sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example + sentinel-example/sentinel-feign-example/sentinel-feign-provider-example sentinel-example/sentinel-webflux-example - sentinel-example/sentinel-zuul-example sentinel-example/sentinel-spring-cloud-gateway-example + sentinel-example/sentinel-zuul-example nacos-example/nacos-discovery-example nacos-example/nacos-config-example nacos-example/nacos-gateway-example - oss-example - ans-example/ans-consumer-feign-example - ans-example/ans-consumer-ribbon-example - ans-example/ans-provider-example seata-example/business-service seata-example/order-service seata-example/storage-service seata-example/account-service - acm-example/acm-local-example rocketmq-example/rocketmq-consume-example rocketmq-example/rocketmq-produce-example - sms-example spring-cloud-bus-rocketmq-example - schedulerx-example/schedulerx-simple-task-example spring-cloud-alibaba-dubbo-examples + spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example + spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/Foo.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/Foo.java index 78dbf120..c4127e7b 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/Foo.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/Foo.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; /** @@ -6,6 +22,7 @@ package com.alibaba.cloud.examples; public class Foo { private int id; + private String bar; public Foo() { @@ -36,4 +53,5 @@ public class Foo { public String toString() { return "Foo{" + "id=" + id + ", bar='" + bar + '\'' + '}'; } + } diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/ReceiveService.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/ReceiveService.java index d178f8f2..0754c91b 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/ReceiveService.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/ReceiveService.java @@ -1,7 +1,22 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import org.springframework.cloud.stream.annotation.StreamListener; -import org.springframework.messaging.Message; import org.springframework.messaging.handler.annotation.Payload; import org.springframework.stereotype.Service; @@ -11,10 +26,10 @@ import org.springframework.stereotype.Service; @Service public class ReceiveService { - @StreamListener("input1") - public void receiveInput1(Message message) { - System.out.println("input1 receive: " + message.getPayload() + ", foo header: " + message.getHeaders().get("foo")); - } + @StreamListener("input1") + public void receiveInput1(String receiveMsg) { + System.out.println("input1 receive: " + receiveMsg); + } @StreamListener("input2") public void receiveInput2(String receiveMsg) { diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/RocketMQConsumerApplication.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/RocketMQConsumerApplication.java index caf9f357..2bd73880 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/RocketMQConsumerApplication.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/java/com/alibaba/cloud/examples/RocketMQConsumerApplication.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.cloud.examples.RocketMQConsumerApplication.MySink; @@ -20,6 +36,15 @@ import org.springframework.messaging.SubscribableChannel; @EnableBinding({ MySink.class }) public class RocketMQConsumerApplication { + public static void main(String[] args) { + SpringApplication.run(RocketMQConsumerApplication.class, args); + } + + @Bean + public ConsumerCustomRunner customRunner() { + return new ConsumerCustomRunner(); + } + public interface MySink { @Input("input1") @@ -36,15 +61,7 @@ public class RocketMQConsumerApplication { @Input("input5") PollableMessageSource input5(); - } - public static void main(String[] args) { - SpringApplication.run(RocketMQConsumerApplication.class, args); - } - - @Bean - public ConsumerCustomRunner customRunner() { - return new ConsumerCustomRunner(); } public static class ConsumerCustomRunner implements CommandLineRunner { @@ -63,6 +80,7 @@ public class RocketMQConsumerApplication { Thread.sleep(2_000); } } + } } diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/resources/application.properties index 1b84ed30..2779db52 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-consume-example/src/main/resources/application.properties @@ -4,7 +4,6 @@ spring.cloud.stream.bindings.input1.destination=test-topic spring.cloud.stream.bindings.input1.content-type=text/plain spring.cloud.stream.bindings.input1.group=test-group1 spring.cloud.stream.rocketmq.bindings.input1.consumer.orderly=true -spring.cloud.stream.rocketmq.bindings.input1.consumer.trustedPackages=com.alibaba.cloud spring.cloud.stream.bindings.input2.destination=test-topic spring.cloud.stream.bindings.input2.content-type=text/plain @@ -34,4 +33,4 @@ spring.application.name=rocketmq-consume-example server.port=28082 management.endpoints.web.exposure.include=* -management.endpoint.health.show-details=always \ No newline at end of file +management.endpoint.health.show-details=always diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/Foo.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/Foo.java index 78dbf120..c4127e7b 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/Foo.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/Foo.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; /** @@ -6,6 +22,7 @@ package com.alibaba.cloud.examples; public class Foo { private int id; + private String bar; public Foo() { @@ -36,4 +53,5 @@ public class Foo { public String toString() { return "Foo{" + "id=" + id + ", bar='" + bar + '\'' + '}'; } + } diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/RocketMQProduceApplication.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/RocketMQProduceApplication.java index 5eaa3b93..eaf4b47e 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/RocketMQProduceApplication.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/RocketMQProduceApplication.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; @@ -9,7 +25,6 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.stream.annotation.EnableBinding; import org.springframework.cloud.stream.annotation.Output; import org.springframework.context.annotation.Bean; -import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.support.MessageBuilder; @@ -20,20 +35,6 @@ import org.springframework.messaging.support.MessageBuilder; @EnableBinding({ MySource.class }) public class RocketMQProduceApplication { - public interface MySource { - @Output("output1") - MessageChannel output1(); - - @Output("output2") - MessageChannel output2(); - - @Output("output3") - MessageChannel output3(); - - @Output("output4") - MessageChannel output4(); - } - public static void main(String[] args) { SpringApplication.run(RocketMQProduceApplication.class, args); } @@ -48,16 +49,24 @@ public class RocketMQProduceApplication { return new CustomRunner("output3"); } - @Bean - public CustomRunner customRunner3() { - return new CustomRunner("output4"); - } - @Bean public CustomRunnerWithTransactional customRunnerWithTransactional() { return new CustomRunnerWithTransactional(); } + public interface MySource { + + @Output("output1") + MessageChannel output1(); + + @Output("output2") + MessageChannel output2(); + + @Output("output3") + MessageChannel output3(); + + } + public static class CustomRunner implements CommandLineRunner { private final String bindingName; @@ -97,20 +106,13 @@ public class RocketMQProduceApplication { .send(MessageBuilder.withPayload(msgContent).build()); } } - else if (this.bindingName.equals("output4")) { - int count = 5; - for (int index = 1; index <= count; index++) { - String msgContent = "partitionMsg-" + index; - Message message = MessageBuilder.withPayload(msgContent) - .setHeader("myPartitionKey", "myPartitionKey").build(); - mySource.output4().send(message); - } - } } + } public static class CustomRunnerWithTransactional implements CommandLineRunner { + @Autowired private SenderService senderService; @@ -125,6 +127,7 @@ public class RocketMQProduceApplication { // COMMIT_MESSAGE message senderService.sendTransactionalMsg("transactional-msg4", 4); } + } } diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/SenderService.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/SenderService.java index 645495b6..cd9e5093 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/SenderService.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/SenderService.java @@ -1,11 +1,25 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import java.util.stream.Collectors; import java.util.stream.Stream; import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; - -import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.spring.support.RocketMQHeaders; @@ -25,8 +39,6 @@ public class SenderService { @Autowired private MySource source; - private ObjectMapper objectMapper = new ObjectMapper(); - public void send(String msg) throws Exception { source.output1().send(MessageBuilder.withPayload(msg).build()); } @@ -41,7 +53,6 @@ public class SenderService { public void sendObject(T msg, String tag) throws Exception { Message message = MessageBuilder.withPayload(msg) .setHeader(MessageConst.PROPERTY_TAGS, tag) - .setHeader("foo", new Foo(1, "bar")) .setHeader(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON) .build(); source.output1().send(message); diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/TransactionListenerImpl.java b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/TransactionListenerImpl.java index 7894ac0f..e58beb22 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/TransactionListenerImpl.java +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/TransactionListenerImpl.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,8 +25,10 @@ import org.springframework.messaging.Message; /** * @author Jim */ -@RocketMQTransactionListener(txProducerGroup = "myTxProducerGroup", corePoolSize = 5, maximumPoolSize = 10) +@RocketMQTransactionListener(txProducerGroup = "myTxProducerGroup", corePoolSize = 5, + maximumPoolSize = 10) public class TransactionListenerImpl implements RocketMQLocalTransactionListener { + @Override public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) { @@ -52,4 +54,5 @@ public class TransactionListenerImpl implements RocketMQLocalTransactionListener System.out.println("check: " + new String((byte[]) msg.getPayload())); return RocketMQLocalTransactionState.COMMIT; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/resources/application.properties index 163ba7ae..772bf456 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/resources/application.properties @@ -6,7 +6,6 @@ spring.cloud.stream.bindings.output1.destination=test-topic spring.cloud.stream.bindings.output1.content-type=application/json spring.cloud.stream.rocketmq.bindings.output1.producer.group=binder-group spring.cloud.stream.rocketmq.bindings.output1.producer.sync=true -spring.cloud.stream.rocketmq.bindings.output1.producer.sendMessageTimeout=30000 spring.cloud.stream.bindings.output2.destination=TransactionTopic spring.cloud.stream.bindings.output2.content-type=application/json @@ -17,16 +16,9 @@ spring.cloud.stream.bindings.output3.destination=pull-topic spring.cloud.stream.bindings.output3.content-type=text/plain spring.cloud.stream.rocketmq.bindings.output3.producer.group=pull-binder-group -spring.cloud.stream.bindings.output4.destination=partition-topic -spring.cloud.stream.bindings.output4.content-type=text/plain -spring.cloud.stream.bindings.output4.producer.partition-key-expression=headers['myPartitionKey'] -spring.cloud.stream.bindings.output4.producer.partition-selector-class=com.alibaba.cloud.examples.MyPartitionSelectorStrategy -spring.cloud.stream.bindings.output4.producer.partition-count=8 -spring.cloud.stream.rocketmq.bindings.output4.producer.group=partition-binder-group - spring.application.name=rocketmq-produce-example server.port=28081 management.endpoints.web.exposure.include=* -management.endpoint.health.show-details=always \ No newline at end of file +management.endpoint.health.show-details=always diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/pom.xml b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/pom.xml deleted file mode 100644 index 5cbb0b86..00000000 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/pom.xml +++ /dev/null @@ -1,37 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-alibaba-examples - 2.0.1.RELEASE - ../../pom.xml - - 4.0.0 - schedulerx-simple-task-example - - - - com.alibaba.cloud - spring-cloud-starter-alicloud-schedulerx - - - org.springframework.boot - spring-boot-starter-web - - - org.springframework.boot - spring-boot-starter-actuator - - - - - - - org.springframework.boot - spring-boot-maven-plugin - - - - \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/readme-zh.md b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/readme-zh.md deleted file mode 100644 index 91b07a2e..00000000 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/readme-zh.md +++ /dev/null @@ -1,47 +0,0 @@ -# SchedulerX Simple Task Example - -## 项目说明 - -本项目展示了,在Spring Cloud体系中,如何快如接入SchedulerX,使用任务调度服务。 - -SchedulerX 是阿里中间件团队开发的一款分布式任务调度产品。它为您提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。同时提供分布式的任务执行模型,如网格任务。网格任务支持海量子任务均匀分配到所有 Worker(schedulerx-client)上执行。 - -## 示例 - -### 准备工作 - -1. 请先[注册阿里云账号](https://account.aliyun.com/register/register.htm?spm=5176.8142029.388261.26.e9396d3eEIv28g&oauth_callback=https%3A%2F%2Fwww.aliyun.com%2F) - -2. SchedulerX集成到了EDAS组件中心,因此需要[开通EDAS服务](https://common-buy.aliyun.com/?spm=5176.11451019.0.0.6f5965c0Uq5tue&commodityCode=edaspostpay#/buy) - -3. 到[EDAS组件中心](https://edas.console.aliyun.com/#/edasTools)开通SchedulerX组件,即分布式任务管理。 - -4. 进入[SchedulerX分组管理](https://edas.console.aliyun.com/#/schedulerXGroup?regionNo=cn-test)页面,选择上方"测试"区域,点击右上角"新建分组",创建一个分组。 - -5. 将"分组ID"的值填写到`application.properties`文件中`key`为`spring.cloud.alicloud.scx.group-id`对应的value值,即如下所示。 - - spring.cloud.alicloud.scx.group-id=111-1-1-1111 - -6. 进入[SchedulerX任务列表](https://edas.console.aliyun.com/#/edasSchedulerXJob?regionNo=cn-test)页面,选择上方"测试"区域,点击右上角"新建Job",创建一个Job,即如下所示。 - - Job分组:测试——111-1-1-1111 - Job处理接口:SimpleTask - 类型:简单Job单机版 - 定时表达式:默认选项——0 * * * * ? - Job描述:无 - 自定义参数:无 - -### 启动应用 - -直接运行main class,即`ScxApplication`。 - -### 查看效果 - -观察应用的控制台日志输出,可以看到每一分钟会打印一次如下日志。 - -``` - -----------Hello world--------------- -``` - -如果您对 Spring Cloud SchedulerX Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 - diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/SimpleTask.java b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/SimpleTask.java deleted file mode 100644 index 1f910e03..00000000 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/SimpleTask.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.examples; - -import com.alibaba.edas.schedulerx.ProcessResult; -import com.alibaba.edas.schedulerx.ScxSimpleJobContext; -import com.alibaba.edas.schedulerx.ScxSimpleJobProcessor; - -import org.springframework.beans.factory.annotation.Autowired; - -/** - * @author xiaolongzuo - */ -public class SimpleTask implements ScxSimpleJobProcessor { - - @Autowired - private TestService testService; - - @Override - public ProcessResult process(ScxSimpleJobContext context) { - testService.test(); - ProcessResult processResult = new ProcessResult(true); - return processResult; - } - -} diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/resources/application.properties deleted file mode 100644 index a995fa3f..00000000 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/resources/application.properties +++ /dev/null @@ -1,3 +0,0 @@ -server.port=18033 -spring.cloud.alicloud.scx.group-id=*** -spring.cloud.alicloud.edas.namespace=cn-test diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/pom.xml b/spring-cloud-alibaba-examples/seata-example/account-service/pom.xml index 8e738109..362d2d96 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/pom.xml +++ b/spring-cloud-alibaba-examples/seata-example/account-service/pom.xml @@ -16,6 +16,10 @@ com.alibaba.cloud spring-cloud-starter-alibaba-seata + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + org.springframework.boot spring-boot-starter-web @@ -29,9 +33,20 @@ spring-boot-starter-jdbc + + com.alibaba + druid-spring-boot-starter + 1.1.10 + mysql mysql-connector-java + 5.1.31 + + + log4j + log4j + 1.2.17 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountApplication.java b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountApplication.java index 7d52d74c..b573b549 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountApplication.java +++ b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountController.java b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountController.java index 00bad6db..903b52f6 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountController.java +++ b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/AccountController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples; import java.util.Random; @@ -34,9 +35,11 @@ public class AccountController { private static final Logger LOGGER = LoggerFactory.getLogger(AccountController.class); private static final String SUCCESS = "SUCCESS"; + private static final String FAIL = "FAIL"; private final JdbcTemplate jdbcTemplate; + private Random random; public AccountController(JdbcTemplate jdbcTemplate) { diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java index d30e9667..2bb2d004 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java +++ b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples; -import java.sql.SQLException; +import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; -import io.seata.rm.datasource.DataSourceProxy; - -import org.springframework.context.ApplicationContext; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; +import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; /** @@ -33,55 +32,16 @@ import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfiguration { - private final ApplicationContext applicationContext; - - public DatabaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean(initMethod = "init", destroyMethod = "close") - public DruidDataSource storageDataSource() throws SQLException { - - Environment environment = applicationContext.getEnvironment(); - - String ip = environment.getProperty("mysql.server.ip"); - String port = environment.getProperty("mysql.server.port"); - String dbName = environment.getProperty("mysql.db.name"); - - String userName = environment.getProperty("mysql.user.name"); - String password = environment.getProperty("mysql.user.password"); - - DruidDataSource druidDataSource = new DruidDataSource(); - druidDataSource.setUrl( - "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?serverTimezone=UTC"); - druidDataSource.setUsername(userName); - druidDataSource.setPassword(password); - druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); - druidDataSource.setInitialSize(0); - druidDataSource.setMaxActive(180); - druidDataSource.setMaxWait(60000); - druidDataSource.setMinIdle(0); - druidDataSource.setValidationQuery("Select 'x' from DUAL"); - druidDataSource.setTestOnBorrow(false); - druidDataSource.setTestOnReturn(false); - druidDataSource.setTestWhileIdle(true); - druidDataSource.setTimeBetweenEvictionRunsMillis(60000); - druidDataSource.setMinEvictableIdleTimeMillis(25200000); - druidDataSource.setRemoveAbandoned(true); - druidDataSource.setRemoveAbandonedTimeout(1800); - druidDataSource.setLogAbandoned(true); - druidDataSource.setFilters("mergeStat"); - return druidDataSource; + @Bean + @Primary + @ConfigurationProperties("spring.datasource") + public DataSource storageDataSource() { + return new DruidDataSource(); } @Bean - public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource) { - return new DataSourceProxy(druidDataSource); - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSourceProxy dataSourceProxy) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceProxy); + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update("delete from account_tbl where user_id = 'U100001'"); jdbcTemplate.update( diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/application.properties index 68b91d01..d5f73adf 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/application.properties @@ -1,9 +1,30 @@ spring.application.name=account-service server.port=18084 +spring.cloud.nacos.discovery.server-addr=localhost:8848 -mysql.server.ip=127.0.0.1 -mysql.server.port=3306 -mysql.db.name=demo +spring.datasource.name="accountDataSource" +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://xxx:3306/seata?useSSL=false&serverTimezone=UTC +spring.datasource.username=xxx +spring.datasource.password=xxx +spring.datasource.druid.max-active=20 +spring.datasource.druid.min-idle=2 +spring.datasource.druid.initial-size=2 + +seata.enabled=true +spring.cloud.alibaba.seata.tx-service-group=account-service +seata.service.vgroup-mapping.account-service=default +seata.service.grouplist.default=127.0.0.1:8091 +seata.service.disable-global-transaction=false + +## if use registry center +#seata.registry.type=nacos +#seata.registry.nacos.cluster=default +#seata.registry.nacos.server-addr=localhost +# +## if use config center +#seata.config.type=apollo +#seata.config.apollo.apollo-meta=http://192.168.1.204:8801 +#seata.config.apollo.app-id=seata-server -mysql.user.name=root -mysql.user.password=123456 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/file.conf b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/file.conf deleted file mode 100644 index 0777ae8a..00000000 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/file.conf +++ /dev/null @@ -1,67 +0,0 @@ -transport { - # tcp udt unix-domain-socket - type = "TCP" - #NIO NATIVE - server = "NIO" - #enable heartbeat - heartbeat = false - #thread factory for netty - thread-factory { - boss-thread-prefix = "NettyBoss" - worker-thread-prefix = "NettyServerNIOWorker" - server-executor-thread-prefix = "NettyServerBizHandler" - share-boss-worker = false - client-selector-thread-prefix = "NettyClientSelector" - client-selector-thread-size = 1 - client-worker-thread-prefix = "NettyClientWorkerThread" - # netty boss thread size,will not be used for UDT - boss-thread-size = 1 - #auto default pin or 8 - worker-thread-size = 8 - } - shutdown { - # when destroy server, wait seconds - wait = 3 - } - serialization = "seata" - compressor = "none" -} -service { - #vgroup->rgroup - vgroup_mapping.account-service-seata-service-group = "default" - #only support single node - default.grouplist = "127.0.0.1:8091" - #degrade current not support - enableDegrade = false - #disable - disable = false - #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent - max.commit.retry.timeout = "-1" - max.rollback.retry.timeout = "-1" -} -client { - async.commit.buffer.limit = 10000 - lock { - retry.internal = 10 - retry.times = 30 - } - report.retry.count = 5 - tm.commit.retry.count = 1 - tm.rollback.retry.count = 1 -} -transaction { - undo.data.validation = true - undo.log.serialization = "jackson" - undo.log.save.days = 7 - #schedule delete expired undo_log in milliseconds - undo.log.delete.period = 86400000 - undo.log.table = "undo_log" -} - -support { - ## spring - spring { - # auto proxy the DataSource bean - datasource.autoproxy = false - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/registry.conf b/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/registry.conf deleted file mode 100644 index b98f5704..00000000 --- a/spring-cloud-alibaba-examples/seata-example/account-service/src/main/resources/registry.conf +++ /dev/null @@ -1,73 +0,0 @@ -registry { - # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - cluster = "default" - } - eureka { - serviceUrl = "http://localhost:8761/eureka" - application = "default" - weight = "1" - } - redis { - serverAddr = "localhost:6379" - db = "0" - } - zk { - cluster = "default" - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - consul { - cluster = "default" - serverAddr = "127.0.0.1:8500" - } - etcd3 { - cluster = "default" - serverAddr = "http://localhost:2379" - } - sofa { - serverAddr = "127.0.0.1:9603" - application = "default" - region = "DEFAULT_ZONE" - datacenter = "DefaultDataCenter" - cluster = "default" - group = "SEATA_GROUP" - addressWaitTime = "3000" - } - file { - name = "file.conf" - } -} - -config { - # file、nacos 、apollo、zk、consul、etcd3 - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - } - consul { - serverAddr = "127.0.0.1:8500" - } - apollo { - app.id = "seata-server" - apollo.meta = "http://192.168.1.204:8801" - } - zk { - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - etcd3 { - serverAddr = "http://localhost:2379" - } - file { - name = "file.conf" - } -} diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/pom.xml b/spring-cloud-alibaba-examples/seata-example/business-service/pom.xml index 5804c602..ea55dd73 100644 --- a/spring-cloud-alibaba-examples/seata-example/business-service/pom.xml +++ b/spring-cloud-alibaba-examples/seata-example/business-service/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - com.alibaba.cloud spring-cloud-alibaba-examples + com.alibaba.cloud 2.0.1.RELEASE ../../pom.xml @@ -16,6 +16,10 @@ com.alibaba.cloud spring-cloud-starter-alibaba-seata + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + org.springframework.cloud spring-cloud-starter-openfeign @@ -24,6 +28,10 @@ org.springframework.cloud spring-cloud-starter-netflix-hystrix + + + + org.springframework.boot spring-boot-starter-web diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/BusinessApplication.java b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/BusinessApplication.java index 0b963bc8..e708c009 100644 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/BusinessApplication.java +++ b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/BusinessApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,11 +18,13 @@ package com.alibaba.cloud.examples; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.context.annotation.Bean; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; @@ -31,6 +33,7 @@ import org.springframework.web.client.RestTemplate; */ @SpringBootApplication @EnableFeignClients +@EnableDiscoveryClient(autoRegister = false) public class BusinessApplication { public static void main(String[] args) { @@ -42,22 +45,23 @@ public class BusinessApplication { return new RestTemplate(); } - @FeignClient(value = "storage", url = "http://127.0.0.1:18082") + @FeignClient("storage-service") public interface StorageService { - @RequestMapping(path = "/storage/{commodityCode}/{count}") - String storage(@RequestParam("commodityCode") String commodityCode, - @RequestParam("count") int count); + @GetMapping(path = "/storage/{commodityCode}/{count}") + String storage(@PathVariable("commodityCode") String commodityCode, + @PathVariable("count") int count); } - @FeignClient(value = "order", url = "http://127.0.0.1:18083") + @FeignClient("order-service") public interface OrderService { - @RequestMapping(path = "/order", method = RequestMethod.POST) + @PostMapping(path = "/order") String order(@RequestParam("userId") String userId, @RequestParam("commodityCode") String commodityCode, @RequestParam("orderCount") int orderCount); } + } diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/HomeController.java b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/HomeController.java index 96ca752f..ec93cd4d 100644 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/HomeController.java +++ b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/HomeController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +18,6 @@ package com.alibaba.cloud.examples; import com.alibaba.cloud.examples.BusinessApplication.OrderService; import com.alibaba.cloud.examples.BusinessApplication.StorageService; - import io.seata.spring.annotation.GlobalTransactional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,8 +28,7 @@ import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -43,13 +41,19 @@ public class HomeController { private static final Logger LOGGER = LoggerFactory.getLogger(HomeController.class); private static final String SUCCESS = "SUCCESS"; + private static final String FAIL = "FAIL"; + private static final String USER_ID = "U100001"; + private static final String COMMODITY_CODE = "C00321"; + private static final int ORDER_COUNT = 2; private final RestTemplate restTemplate; + private final OrderService orderService; + private final StorageService storageService; public HomeController(RestTemplate restTemplate, OrderService orderService, @@ -60,7 +64,7 @@ public class HomeController { } @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx") - @RequestMapping(value = "/seata/rest", method = RequestMethod.GET, produces = "application/json") + @GetMapping(value = "/seata/rest", produces = "application/json") public String rest() { String result = restTemplate.getForObject( @@ -83,11 +87,14 @@ public class HomeController { HttpEntity> request = new HttpEntity>( map, headers); - ResponseEntity response = restTemplate.postForEntity(url, request, - String.class); - + ResponseEntity response; + try { + response = restTemplate.postForEntity(url, request, String.class); + } + catch (Exception exx) { + throw new RuntimeException("mock error"); + } result = response.getBody(); - if (!SUCCESS.equals(result)) { throw new RuntimeException(); } @@ -96,7 +103,7 @@ public class HomeController { } @GlobalTransactional(timeoutMills = 300000, name = "spring-cloud-demo-tx") - @RequestMapping(value = "/seata/feign", method = RequestMethod.GET, produces = "application/json") + @GetMapping(value = "/seata/feign", produces = "application/json") public String feign() { String result = storageService.storage(COMMODITY_CODE, ORDER_COUNT); diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/Order.java b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/Order.java index 54ff8a0c..fbcb8391 100644 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/Order.java +++ b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/java/com/alibaba/cloud/examples/Order.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,10 +19,30 @@ package com.alibaba.cloud.examples; import java.io.Serializable; public class Order implements Serializable { + + /** + * order id. + */ public long id; + + /** + * user id. + */ public String userId; + + /** + * commodity code. + */ public String commodityCode; + + /** + * count. + */ public int count; + + /** + * money. + */ public int money; @Override @@ -30,4 +50,5 @@ public class Order implements Serializable { return "Order{" + "id=" + id + ", userId='" + userId + '\'' + ", commodityCode='" + commodityCode + '\'' + ", count=" + count + ", money=" + money + '}'; } + } diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/application.properties index 75ed9290..e1fc1c85 100644 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/application.properties @@ -1,8 +1,27 @@ server.port=18081 spring.application.name=business-service +spring.cloud.nacos.discovery.server-addr=localhost:8848 # The following configuration can be omitted. #feign.hystrix.enabled=true #feign.sentinel.enabled=true -logging.level.io.seata=debug \ No newline at end of file +logging.level.io.seata=debug + +seata.enabled=true +spring.cloud.alibaba.seata.tx-service-group=business-service +seata.service.vgroup-mapping.business-service=default +seata.service.grouplist.default=127.0.0.1:8091 +seata.service.disable-global-transaction=false + +spring.cloud.loadbalancer.ribbon.enabled=true + +## if use registry center +#seata.registry.type=nacos +#seata.registry.nacos.cluster=default +#seata.registry.nacos.server-addr=localhost +# +## if use config center +#seata.config.type=apollo +#seata.config.apollo.apollo-meta=http://192.168.1.204:8801 +#seata.config.apollo.app-id=seata-server diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/file.conf b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/file.conf deleted file mode 100644 index a6e431bc..00000000 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/file.conf +++ /dev/null @@ -1,67 +0,0 @@ -transport { - # tcp udt unix-domain-socket - type = "TCP" - #NIO NATIVE - server = "NIO" - #enable heartbeat - heartbeat = false - #thread factory for netty - thread-factory { - boss-thread-prefix = "NettyBoss" - worker-thread-prefix = "NettyServerNIOWorker" - server-executor-thread-prefix = "NettyServerBizHandler" - share-boss-worker = false - client-selector-thread-prefix = "NettyClientSelector" - client-selector-thread-size = 1 - client-worker-thread-prefix = "NettyClientWorkerThread" - # netty boss thread size,will not be used for UDT - boss-thread-size = 1 - #auto default pin or 8 - worker-thread-size = 8 - } - shutdown { - # when destroy server, wait seconds - wait = 3 - } - serialization = "seata" - compressor = "none" -} -service { - #vgroup->rgroup - vgroup_mapping.business-service-seata-service-group = "default" - #only support single node - default.grouplist = "127.0.0.1:8091" - #degrade current not support - enableDegrade = false - #disable - disable = false - #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent - max.commit.retry.timeout = "-1" - max.rollback.retry.timeout = "-1" -} -client { - async.commit.buffer.limit = 10000 - lock { - retry.internal = 10 - retry.times = 30 - } - report.retry.count = 5 - tm.commit.retry.count = 1 - tm.rollback.retry.count = 1 -} -transaction { - undo.data.validation = true - undo.log.serialization = "jackson" - undo.log.save.days = 7 - #schedule delete expired undo_log in milliseconds - undo.log.delete.period = 86400000 - undo.log.table = "undo_log" -} - -support { - ## spring - spring { - # auto proxy the DataSource bean - datasource.autoproxy = false - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/registry.conf b/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/registry.conf deleted file mode 100644 index b98f5704..00000000 --- a/spring-cloud-alibaba-examples/seata-example/business-service/src/main/resources/registry.conf +++ /dev/null @@ -1,73 +0,0 @@ -registry { - # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - cluster = "default" - } - eureka { - serviceUrl = "http://localhost:8761/eureka" - application = "default" - weight = "1" - } - redis { - serverAddr = "localhost:6379" - db = "0" - } - zk { - cluster = "default" - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - consul { - cluster = "default" - serverAddr = "127.0.0.1:8500" - } - etcd3 { - cluster = "default" - serverAddr = "http://localhost:2379" - } - sofa { - serverAddr = "127.0.0.1:9603" - application = "default" - region = "DEFAULT_ZONE" - datacenter = "DefaultDataCenter" - cluster = "default" - group = "SEATA_GROUP" - addressWaitTime = "3000" - } - file { - name = "file.conf" - } -} - -config { - # file、nacos 、apollo、zk、consul、etcd3 - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - } - consul { - serverAddr = "127.0.0.1:8500" - } - apollo { - app.id = "seata-server" - apollo.meta = "http://192.168.1.204:8801" - } - zk { - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - etcd3 { - serverAddr = "http://localhost:2379" - } - file { - name = "file.conf" - } -} diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/pom.xml b/spring-cloud-alibaba-examples/seata-example/order-service/pom.xml index 72595721..f656071a 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/pom.xml +++ b/spring-cloud-alibaba-examples/seata-example/order-service/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - com.alibaba.cloud spring-cloud-alibaba-examples + com.alibaba.cloud 2.0.1.RELEASE ../../pom.xml @@ -12,6 +12,10 @@ order-service + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + com.alibaba.cloud spring-cloud-starter-alibaba-seata @@ -29,9 +33,20 @@ spring-boot-starter-jdbc + + com.alibaba + druid-spring-boot-starter + 1.1.10 + mysql mysql-connector-java + 5.1.31 + + + log4j + log4j + 1.2.17 diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java index 9f517e1b..966f3b01 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java +++ b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples; -import java.sql.SQLException; +import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; -import io.seata.rm.datasource.DataSourceProxy; - -import org.springframework.context.ApplicationContext; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; +import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; /** @@ -33,55 +32,16 @@ import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfiguration { - private final ApplicationContext applicationContext; - - public DatabaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean(initMethod = "init", destroyMethod = "close") - public DruidDataSource storageDataSource() throws SQLException { - - Environment env = applicationContext.getEnvironment(); - - String ip = env.getProperty("mysql.server.ip"); - String port = env.getProperty("mysql.server.port"); - String dbName = env.getProperty("mysql.db.name"); - - String userName = env.getProperty("mysql.user.name"); - String password = env.getProperty("mysql.user.password"); - - DruidDataSource druidDataSource = new DruidDataSource(); - druidDataSource.setUrl( - "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?serverTimezone=UTC"); - druidDataSource.setUsername(userName); - druidDataSource.setPassword(password); - druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); - druidDataSource.setInitialSize(0); - druidDataSource.setMaxActive(180); - druidDataSource.setMaxWait(60000); - druidDataSource.setMinIdle(0); - druidDataSource.setValidationQuery("Select 'x' from DUAL"); - druidDataSource.setTestOnBorrow(false); - druidDataSource.setTestOnReturn(false); - druidDataSource.setTestWhileIdle(true); - druidDataSource.setTimeBetweenEvictionRunsMillis(60000); - druidDataSource.setMinEvictableIdleTimeMillis(25200000); - druidDataSource.setRemoveAbandoned(true); - druidDataSource.setRemoveAbandonedTimeout(1800); - druidDataSource.setLogAbandoned(true); - druidDataSource.setFilters("mergeStat"); - return druidDataSource; + @Bean + @Primary + @ConfigurationProperties("spring.datasource") + public DataSource storageDataSource() { + return new DruidDataSource(); } @Bean - public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource) { - return new DataSourceProxy(druidDataSource); - } - - @Bean - public JdbcTemplate jdbcTemplate(DataSourceProxy dataSourceProxy) { - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceProxy); + public JdbcTemplate jdbcTemplate(DataSource dataSource) { + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.execute("TRUNCATE TABLE order_tbl"); diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OderApplication.java b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OderApplication.java index 9bd64f51..b1233273 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OderApplication.java +++ b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OderApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/Order.java b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/Order.java index 54ff8a0c..6ad92cc5 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/Order.java +++ b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/Order.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,10 +19,30 @@ package com.alibaba.cloud.examples; import java.io.Serializable; public class Order implements Serializable { + + /** + * id. + */ public long id; + + /** + * user id. + */ public String userId; + + /** + * commodity code. + */ public String commodityCode; + + /** + * count. + */ public int count; + + /** + * money. + */ public int money; @Override @@ -30,4 +50,5 @@ public class Order implements Serializable { return "Order{" + "id=" + id + ", userId='" + userId + '\'' + ", commodityCode='" + commodityCode + '\'' + ", count=" + count + ", money=" + money + '}'; } + } diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OrderController.java b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OrderController.java index 66d3ea68..1aba194d 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OrderController.java +++ b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/java/com/alibaba/cloud/examples/OrderController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,8 +35,7 @@ import org.springframework.jdbc.support.GeneratedKeyHolder; import org.springframework.jdbc.support.KeyHolder; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -47,13 +46,19 @@ import org.springframework.web.client.RestTemplate; public class OrderController { private static final Logger LOGGER = LoggerFactory.getLogger(OrderController.class); + private static final String SUCCESS = "SUCCESS"; + private static final String FAIL = "FAIL"; + private static final String USER_ID = "U100001"; + private static final String COMMODITY_CODE = "C00321"; private final JdbcTemplate jdbcTemplate; + private final RestTemplate restTemplate; + private Random random; public OrderController(JdbcTemplate jdbcTemplate, RestTemplate restTemplate) { @@ -62,7 +67,7 @@ public class OrderController { this.random = new Random(); } - @RequestMapping(value = "/order", method = RequestMethod.POST, produces = "application/json") + @PostMapping(value = "/order", produces = "application/json") public String order(String userId, String commodityCode, int orderCount) { LOGGER.info("Order Service Begin ... xid: " + RootContext.getXID()); @@ -128,4 +133,5 @@ public class OrderController { ResponseEntity response = restTemplate.postForEntity(url, request, String.class); } + } diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/application.properties index c88342af..fb4a4b7c 100644 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/application.properties @@ -1,9 +1,29 @@ spring.application.name=order-service server.port=18083 +spring.cloud.nacos.discovery.server-addr=localhost:8848 -mysql.server.ip=127.0.0.1 -mysql.server.port=3306 -mysql.db.name=demo +spring.datasource.name="orderDataSource" +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://xxx:3306/seata?useSSL=false&serverTimezone=UTC +spring.datasource.username=xxx +spring.datasource.password=xxx +spring.datasource.druid.max-active=20 +spring.datasource.druid.min-idle=2 +spring.datasource.druid.initial-size=2 -mysql.user.name=root -mysql.user.password=123456 \ No newline at end of file +seata.enabled=true +spring.cloud.alibaba.seata.tx-service-group=business-service +seata.service.vgroup-mapping.business-service=default +seata.service.grouplist.default=127.0.0.1:8091 +seata.service.disable-global-transaction=false + +## if use registry center +#seata.registry.type=nacos +#seata.registry.nacos.cluster=default +#seata.registry.nacos.server-addr=localhost +# +## if use config center +#seata.config.type=apollo +#seata.config.apollo.apollo-meta=http://192.168.1.204:8801 +#seata.config.apollo.app-id=seata-server diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/file.conf b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/file.conf deleted file mode 100644 index 89f55344..00000000 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/file.conf +++ /dev/null @@ -1,67 +0,0 @@ -transport { - # tcp udt unix-domain-socket - type = "TCP" - #NIO NATIVE - server = "NIO" - #enable heartbeat - heartbeat = false - #thread factory for netty - thread-factory { - boss-thread-prefix = "NettyBoss" - worker-thread-prefix = "NettyServerNIOWorker" - server-executor-thread-prefix = "NettyServerBizHandler" - share-boss-worker = false - client-selector-thread-prefix = "NettyClientSelector" - client-selector-thread-size = 1 - client-worker-thread-prefix = "NettyClientWorkerThread" - # netty boss thread size,will not be used for UDT - boss-thread-size = 1 - #auto default pin or 8 - worker-thread-size = 8 - } - shutdown { - # when destroy server, wait seconds - wait = 3 - } - serialization = "seata" - compressor = "none" -} -service { - #vgroup->rgroup - vgroup_mapping.order-service-seata-service-group = "default" - #only support single node - default.grouplist = "127.0.0.1:8091" - #degrade current not support - enableDegrade = false - #disable - disable = false - #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent - max.commit.retry.timeout = "-1" - max.rollback.retry.timeout = "-1" -} -client { - async.commit.buffer.limit = 10000 - lock { - retry.internal = 10 - retry.times = 30 - } - report.retry.count = 5 - tm.commit.retry.count = 1 - tm.rollback.retry.count = 1 -} -transaction { - undo.data.validation = true - undo.log.serialization = "jackson" - undo.log.save.days = 7 - #schedule delete expired undo_log in milliseconds - undo.log.delete.period = 86400000 - undo.log.table = "undo_log" -} - -support { - ## spring - spring { - # auto proxy the DataSource bean - datasource.autoproxy = false - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/registry.conf b/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/registry.conf deleted file mode 100644 index b98f5704..00000000 --- a/spring-cloud-alibaba-examples/seata-example/order-service/src/main/resources/registry.conf +++ /dev/null @@ -1,73 +0,0 @@ -registry { - # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - cluster = "default" - } - eureka { - serviceUrl = "http://localhost:8761/eureka" - application = "default" - weight = "1" - } - redis { - serverAddr = "localhost:6379" - db = "0" - } - zk { - cluster = "default" - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - consul { - cluster = "default" - serverAddr = "127.0.0.1:8500" - } - etcd3 { - cluster = "default" - serverAddr = "http://localhost:2379" - } - sofa { - serverAddr = "127.0.0.1:9603" - application = "default" - region = "DEFAULT_ZONE" - datacenter = "DefaultDataCenter" - cluster = "default" - group = "SEATA_GROUP" - addressWaitTime = "3000" - } - file { - name = "file.conf" - } -} - -config { - # file、nacos 、apollo、zk、consul、etcd3 - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - } - consul { - serverAddr = "127.0.0.1:8500" - } - apollo { - app.id = "seata-server" - apollo.meta = "http://192.168.1.204:8801" - } - zk { - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - etcd3 { - serverAddr = "http://localhost:2379" - } - file { - name = "file.conf" - } -} diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/pom.xml b/spring-cloud-alibaba-examples/seata-example/storage-service/pom.xml index ce5a60f3..88a2cf37 100644 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/pom.xml +++ b/spring-cloud-alibaba-examples/seata-example/storage-service/pom.xml @@ -3,8 +3,8 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - com.alibaba.cloud spring-cloud-alibaba-examples + com.alibaba.cloud 2.0.1.RELEASE ../../pom.xml @@ -16,6 +16,10 @@ com.alibaba.cloud spring-cloud-starter-alibaba-seata + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + org.springframework.boot spring-boot-starter-web @@ -24,19 +28,24 @@ org.springframework.boot spring-boot-starter-actuator - - com.alibaba - druid - 1.1.10 - org.springframework.boot spring-boot-starter-jdbc - + + com.alibaba + druid-spring-boot-starter + 1.1.10 + mysql mysql-connector-java + 5.1.31 + + + log4j + log4j + 1.2.17 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java index 5799b2f9..b358cdc1 100644 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java +++ b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/DatabaseConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +16,14 @@ package com.alibaba.cloud.examples; -import java.sql.SQLException; +import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSource; -import io.seata.rm.datasource.DataSourceProxy; - -import org.springframework.context.ApplicationContext; +import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; +import org.springframework.context.annotation.Primary; import org.springframework.jdbc.core.JdbcTemplate; /** @@ -34,56 +32,17 @@ import org.springframework.jdbc.core.JdbcTemplate; @Configuration public class DatabaseConfiguration { - private final ApplicationContext applicationContext; - - public DatabaseConfiguration(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - @Bean(initMethod = "init", destroyMethod = "close") - public DruidDataSource storageDataSource() throws SQLException { - - Environment environment = applicationContext.getEnvironment(); - - String ip = environment.getProperty("mysql.server.ip"); - String port = environment.getProperty("mysql.server.port"); - String dbName = environment.getProperty("mysql.db.name"); - - String userName = environment.getProperty("mysql.user.name"); - String password = environment.getProperty("mysql.user.password"); - - DruidDataSource druidDataSource = new DruidDataSource(); - druidDataSource.setUrl( - "jdbc:mysql://" + ip + ":" + port + "/" + dbName + "?serverTimezone=UTC"); - druidDataSource.setUsername(userName); - druidDataSource.setPassword(password); - druidDataSource.setDriverClassName("com.mysql.jdbc.Driver"); - druidDataSource.setInitialSize(0); - druidDataSource.setMaxActive(180); - druidDataSource.setMaxWait(60000); - druidDataSource.setMinIdle(0); - druidDataSource.setValidationQuery("Select 'x' from DUAL"); - druidDataSource.setTestOnBorrow(false); - druidDataSource.setTestOnReturn(false); - druidDataSource.setTestWhileIdle(true); - druidDataSource.setTimeBetweenEvictionRunsMillis(60000); - druidDataSource.setMinEvictableIdleTimeMillis(25200000); - druidDataSource.setRemoveAbandoned(true); - druidDataSource.setRemoveAbandonedTimeout(1800); - druidDataSource.setLogAbandoned(true); - druidDataSource.setFilters("mergeStat"); - return druidDataSource; + @Bean + @Primary + @ConfigurationProperties("spring.datasource") + public DataSource storageDataSource() { + return new DruidDataSource(); } @Bean - public DataSourceProxy dataSourceProxy(DruidDataSource druidDataSource) { - return new DataSourceProxy(druidDataSource); - } + public JdbcTemplate jdbcTemplate(DataSource dataSource) { - @Bean - public JdbcTemplate jdbcTemplate(DataSourceProxy dataSourceProxy) { - - JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSourceProxy); + JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource); jdbcTemplate.update("delete from storage_tbl where commodity_code = 'C00321'"); jdbcTemplate.update( diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageApplication.java b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageApplication.java index 4e6185b2..91e6c46c 100644 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageApplication.java +++ b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageController.java b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageController.java index ea835168..31bf0607 100644 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageController.java +++ b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/java/com/alibaba/cloud/examples/StorageController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,9 +21,8 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; /** @@ -35,6 +34,7 @@ public class StorageController { private static final Logger LOGGER = LoggerFactory.getLogger(StorageController.class); private static final String SUCCESS = "SUCCESS"; + private static final String FAIL = "FAIL"; private final JdbcTemplate jdbcTemplate; @@ -43,7 +43,7 @@ public class StorageController { this.jdbcTemplate = jdbcTemplate; } - @RequestMapping(value = "/storage/{commodityCode}/{count}", method = RequestMethod.GET, produces = "application/json") + @GetMapping(value = "/storage/{commodityCode}/{count}", produces = "application/json") public String echo(@PathVariable String commodityCode, @PathVariable int count) { LOGGER.info("Storage Service Begin ... xid: " + RootContext.getXID()); int result = jdbcTemplate.update( @@ -55,4 +55,5 @@ public class StorageController { } return FAIL; } + } diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/application.properties b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/application.properties index b65047c8..a2bd463a 100644 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/application.properties @@ -1,9 +1,30 @@ spring.application.name=storage-service server.port=18082 +spring.cloud.nacos.discovery.server-addr=localhost:8848 -mysql.server.ip=127.0.0.1 -mysql.server.port=3306 -mysql.db.name=demo +spring.datasource.name="storageDataSource" +spring.datasource.type=com.alibaba.druid.pool.DruidDataSource +spring.datasource.driver-class-name=com.mysql.jdbc.Driver +spring.datasource.url=jdbc:mysql://xxx:3306/seata?useSSL=false&serverTimezone=UTC +spring.datasource.username=xxx +spring.datasource.password=xxx +spring.datasource.druid.max-active=20 +spring.datasource.druid.min-idle=2 +spring.datasource.druid.initial-size=2 -mysql.user.name=root -mysql.user.password=123456 \ No newline at end of file + +seata.enabled=true +spring.cloud.alibaba.seata.tx-service-group=business-service +seata.service.vgroup-mapping.business-service=default +seata.service.grouplist.default=127.0.0.1:8091 +seata.service.disable-global-transaction=false + +## if use registry center +#seata.registry.type=nacos +#seata.registry.nacos.cluster=default +#seata.registry.nacos.server-addr=localhost +# +## if use config center +#seata.config.type=apollo +#seata.config.apollo.apollo-meta=http://192.168.1.204:8801 +#seata.config.apollo.app-id=seata-server diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/file.conf b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/file.conf deleted file mode 100644 index 2915b99c..00000000 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/file.conf +++ /dev/null @@ -1,67 +0,0 @@ -transport { - # tcp udt unix-domain-socket - type = "TCP" - #NIO NATIVE - server = "NIO" - #enable heartbeat - heartbeat = false - #thread factory for netty - thread-factory { - boss-thread-prefix = "NettyBoss" - worker-thread-prefix = "NettyServerNIOWorker" - server-executor-thread-prefix = "NettyServerBizHandler" - share-boss-worker = false - client-selector-thread-prefix = "NettyClientSelector" - client-selector-thread-size = 1 - client-worker-thread-prefix = "NettyClientWorkerThread" - # netty boss thread size,will not be used for UDT - boss-thread-size = 1 - #auto default pin or 8 - worker-thread-size = 8 - } - shutdown { - # when destroy server, wait seconds - wait = 3 - } - serialization = "seata" - compressor = "none" -} -service { - #vgroup->rgroup - vgroup_mapping.storage-service-seata-service-group = "default" - #only support single node - default.grouplist = "127.0.0.1:8091" - #degrade current not support - enableDegrade = false - #disable - disable = false - #unit ms,s,m,h,d represents milliseconds, seconds, minutes, hours, days, default permanent - max.commit.retry.timeout = "-1" - max.rollback.retry.timeout = "-1" -} -client { - async.commit.buffer.limit = 10000 - lock { - retry.internal = 10 - retry.times = 30 - } - report.retry.count = 5 - tm.commit.retry.count = 1 - tm.rollback.retry.count = 1 -} -transaction { - undo.data.validation = true - undo.log.serialization = "jackson" - undo.log.save.days = 7 - #schedule delete expired undo_log in milliseconds - undo.log.delete.period = 86400000 - undo.log.table = "undo_log" -} - -support { - ## spring - spring { - # auto proxy the DataSource bean - datasource.autoproxy = false - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/registry.conf b/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/registry.conf deleted file mode 100644 index b98f5704..00000000 --- a/spring-cloud-alibaba-examples/seata-example/storage-service/src/main/resources/registry.conf +++ /dev/null @@ -1,73 +0,0 @@ -registry { - # file 、nacos 、eureka、redis、zk、consul、etcd3、sofa - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - cluster = "default" - } - eureka { - serviceUrl = "http://localhost:8761/eureka" - application = "default" - weight = "1" - } - redis { - serverAddr = "localhost:6379" - db = "0" - } - zk { - cluster = "default" - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - consul { - cluster = "default" - serverAddr = "127.0.0.1:8500" - } - etcd3 { - cluster = "default" - serverAddr = "http://localhost:2379" - } - sofa { - serverAddr = "127.0.0.1:9603" - application = "default" - region = "DEFAULT_ZONE" - datacenter = "DefaultDataCenter" - cluster = "default" - group = "SEATA_GROUP" - addressWaitTime = "3000" - } - file { - name = "file.conf" - } -} - -config { - # file、nacos 、apollo、zk、consul、etcd3 - type = "file" - - nacos { - serverAddr = "localhost" - namespace = "" - } - consul { - serverAddr = "127.0.0.1:8500" - } - apollo { - app.id = "seata-server" - apollo.meta = "http://192.168.1.204:8801" - } - zk { - serverAddr = "127.0.0.1:2181" - session.timeout = 6000 - connect.timeout = 2000 - } - etcd3 { - serverAddr = "http://localhost:2379" - } - file { - name = "file.conf" - } -} diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/pom.xml index 0d15cb23..24431bc5 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/pom.xml @@ -30,6 +30,10 @@ org.springframework.boot spring-boot-starter-actuator + + org.springframework.boot + spring-boot-starter-thymeleaf + diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md index 35b8dc21..c5a8111f 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md @@ -184,7 +184,7 @@ Spring Boot 应用支持通过 Endpoint 来暴露相关信息,Sentinel Starter * Spring Boot 1.x 中添加配置 `management.security.enabled=false` * Spring Boot 2.x 中添加配置 `management.endpoints.web.exposure.include=*` -Spring Boot 1.x 可以通过访问 http://127.0.0.1:18083/sentinel 来查看 Sentinel Endpoint 的信息。Spring Boot 2.x 可以通过访问 http://127.0.0.1:18083/acutator/sentinel 来访问。 +Spring Boot 1.x 可以通过访问 http://127.0.0.1:18083/sentinel 来查看 Sentinel Endpoint 的信息。Spring Boot 2.x 可以通过访问 http://127.0.0.1:18083/actuator/sentinel 来访问。

diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md index b6c56cd0..1856a4a0 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md @@ -193,15 +193,27 @@ Now ReadableDataSource type support 5 categories: `file`, `nacos`, `zk`, `apollo If you want to use `nacos`, `zk`, `apollo` or `redis` ReadableDataSource, you could add `sentinel-datasource-nacos`, `sentinel-datasource-zookeeper`,`sentinel-datasource-apollo` or `sentinel-datasource-redis` dependency. + + When ReadableDataSource load rule data successfully, console will print some logs: ``` [Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule [Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule ``` +## Warning +You should use `file` ReadableDataSource in a fatjar carefully or you may get error like this below + +``` +java.lang.RuntimeException: [Sentinel Starter] DataSource ds1 handle file [classpath: flowrule.json] error: class path resource [flowrule.json] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:xxx/xxx.jar!/BOOT-INF/classes!/flowrule.jso +``` + +You could use absolute path when you use File datasource & fat jar. +It is recommended to use Nacos/Apollo/Zookeeper/Redis datasource to store rules. + +https://github.com/alibaba/spring-cloud-alibaba/issues/428 ## More For more information about Sentinel, see [Sentinel Project](https://github.com/alibaba/Sentinel). If you have any ideas or suggestions for Spring Cloud Sentinel starter, please don't hesitate to tell us by submitting github issues. - diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ExceptionUtil.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ExceptionUtil.java index c5ad01e8..591756f8 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ExceptionUtil.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ExceptionUtil.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; @@ -9,7 +25,11 @@ import org.springframework.http.client.ClientHttpRequestExecution; /** * @author fangjian */ -public class ExceptionUtil { +public final class ExceptionUtil { + + private ExceptionUtil() { + + } public static SentinelClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) { diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/JsonFlowRuleListConverter.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/JsonFlowRuleListConverter.java index aee0fe99..fe90b718 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/JsonFlowRuleListConverter.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/JsonFlowRuleListConverter.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import java.util.List; @@ -11,9 +27,11 @@ import com.alibaba.fastjson.TypeReference; * @author fangjian */ public class JsonFlowRuleListConverter implements Converter> { + @Override public List convert(String source) { return JSON.parseObject(source, new TypeReference>() { }); } + } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ServiceApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ServiceApplication.java index fda03fe6..7345f74c 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ServiceApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/ServiceApplication.java @@ -1,10 +1,33 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; +import java.util.Collections; + +import com.alibaba.cloud.circuitbreaker.sentinel.SentinelCircuitBreakerFactory; +import com.alibaba.cloud.circuitbreaker.sentinel.SentinelConfigBuilder; import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; import com.alibaba.csp.sentinel.datasource.Converter; +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.circuitbreaker.Customizer; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; @@ -15,7 +38,8 @@ import org.springframework.web.client.RestTemplate; public class ServiceApplication { @Bean - @SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class) + @SentinelRestTemplate(blockHandler = "handleException", + blockHandlerClass = ExceptionUtil.class) public RestTemplate restTemplate() { return new RestTemplate(); } @@ -30,6 +54,18 @@ public class ServiceApplication { return new JsonFlowRuleListConverter(); } + @Bean + public Customizer defaultConfig() { + return factory -> { + factory.configureDefault( + id -> new SentinelConfigBuilder().resourceName(id) + .rules(Collections.singletonList(new DegradeRule(id) + .setGrade(RuleConstant.DEGRADE_GRADE_RT).setCount(100) + .setTimeWindow(10))) + .build()); + }; + } + public static void main(String[] args) { SpringApplication.run(ServiceApplication.class, args); } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/TestController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/TestController.java index 60191187..5ca27cd1 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/TestController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/TestController.java @@ -1,10 +1,26 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.examples; import com.alibaba.csp.sentinel.annotation.SentinelResource; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; @@ -17,26 +33,42 @@ public class TestController { @Autowired private RestTemplate restTemplate; - @RequestMapping(value = "/hello", method = RequestMethod.GET) + @Autowired + private CircuitBreakerFactory circuitBreakerFactory; + + @GetMapping("/hello") @SentinelResource("resource") public String hello() { return "Hello"; } - @RequestMapping(value = "/aa", method = RequestMethod.GET) + @GetMapping("/aa") @SentinelResource("aa") public String aa(int b, int a) { return "Hello test"; } - @RequestMapping(value = "/test", method = RequestMethod.GET) + @GetMapping("/test") public String test1() { return "Hello test"; } - @RequestMapping(value = "/template", method = RequestMethod.GET) + @GetMapping("/template") public String client() { return restTemplate.getForObject("http://www.taobao.com/test", String.class); } + @GetMapping("/slow") + public String slow() { + return circuitBreakerFactory.create("slow").run(() -> { + try { + Thread.sleep(500L); + } + catch (InterruptedException e) { + e.printStackTrace(); + } + return "slow"; + }, throwable -> "fallback"); + } + } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/WebMvcConfiguration.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/WebMvcConfiguration.java new file mode 100644 index 00000000..b4a562fb --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/java/com/alibaba/cloud/examples/WebMvcConfiguration.java @@ -0,0 +1,36 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples; + +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.config.annotation.EnableWebMvc; +import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @author yuhuangbin + */ +@Configuration +@EnableWebMvc +public class WebMvcConfiguration implements WebMvcConfigurer { + + @Override + public void addViewControllers(ViewControllerRegistry registry) { + registry.addViewController("/errorPage").setViewName("errorPage"); + } + +} diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/application.properties index cc772c49..16ee4a26 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/application.properties @@ -1,8 +1,17 @@ spring.application.name=sentinel-example server.port=18083 management.endpoints.web.exposure.include=* +management.endpoint.health.show-details=always + +# we can disable health check, default is enable +management.health.diskspace.enabled=false +# management.health.sentinel.enabled=false + spring.cloud.sentinel.transport.dashboard=localhost:8080 spring.cloud.sentinel.eager=true + +#spring.cloud.sentinel.block-page=/errorPage +#spring.cloud.sentinel.filter.enabled=false #spring.cloud.sentinel.http-method-specify=false spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json @@ -20,7 +29,4 @@ spring.cloud.sentinel.datasource.ds4.file.file=classpath: system.json spring.cloud.sentinel.datasource.ds4.file.rule-type=system spring.cloud.sentinel.datasource.ds5.file.file=classpath: param-flow.json -spring.cloud.sentinel.datasource.ds5.file.rule-type=param-flow - - -management.endpoint.health.show-details=always \ No newline at end of file +spring.cloud.sentinel.datasource.ds5.file.rule-type=param_flow diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/templates/errorPage.html b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/templates/errorPage.html new file mode 100644 index 00000000..04211d7e --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/src/main/resources/templates/errorPage.html @@ -0,0 +1,10 @@ + + + + + Title + + +This is error page. + + \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-api/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-api/pom.xml index 5cbf4255..d66a27b8 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-api/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-api/pom.xml @@ -10,7 +10,6 @@ 4.0.0 - sentinel-dubbo-api jar api for sentinel dubbo example diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/pom.xml index a522780b..80a48b10 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/pom.xml @@ -17,6 +17,12 @@ + + + org.springframework.boot + spring-boot-starter + + com.alibaba.cloud spring-cloud-starter-alibaba-sentinel diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-provider-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-provider-example/pom.xml index dcbfc806..dec11805 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-provider-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-provider-example/pom.xml @@ -17,6 +17,12 @@ + + + org.springframework.boot + spring-boot-starter + + com.alibaba.cloud spring-cloud-starter-alibaba-sentinel @@ -42,7 +48,6 @@ org.apache.dubbo dubbo - diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme-zh.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme-zh.md new file mode 100644 index 00000000..542d9ef7 --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme-zh.md @@ -0,0 +1,125 @@ +# Sentinel Feign Example + +## 项目说明 + +本项目演示如何使用 Sentinel starter 完成 Spring Cloud 应用调用。 + +[Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件,Sentinel 把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。 + +[OpenFeign](https://github.com/spring-cloud/spring-cloud-openfeign)是一款声明式、模板化的HTTP客户端, Feign可以帮助我们更快捷、优雅地调用HTTP API。 + +本项目专注于Sentinel与Feign的整合,关于Sentinel的更多特性可以查看[sentinel-core-example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example)。 + +## 示例 + +### 服务消费方 +在启动示例进行演示之前,我们先了解一下 Feign 如何接入 Sentinel。 +**注意 本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。** + +1. 首先,修改 pom.xml 文件,引入 Sentinel starter 和 Dubbo starter。 + +```xml + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + +``` +2. 其次, 使用nacos 注册中心 + +```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + +``` + +3. 定义FeignClient,及其降级配置 + +- 定义FeignClient +```java +@FeignClient(name = "service-provider", fallbackFactory = EchoServiceFallbackFactory.class) +public interface EchoService { + + /** + * 调用服务提供方的输出接口 + * + * @param str 用户输入 + * @return + */ + @GetMapping(value = "/echo/{str}") + String echo(@PathVariable("str") String str); +} +``` +- 定义fallback 工厂,获取异常 + +```java +@Component +public class EchoServiceFallbackFactory implements FallbackFactory { + @Override + public EchoServiceFallback create(Throwable throwable) { + return new EchoServiceFallback(throwable); + } +} +``` + +- 定义具体的fallback 实现 +```java +public class EchoServiceFallback implements EchoService { + private Throwable throwable; + + EchoServiceFallback(Throwable throwable) { + this.throwable = throwable; + } + + @Override + public String echo(String str) { + return "consumer-fallback-default-str" + throwable.getMessage(); + } +} +``` +### 服务提供方 + +1. 首先, 依赖nacos 注册中心 + +```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + +``` + +2. 定义服务提供方接口 + +```java +@RestController +public class EchoController { + + @GetMapping("/echo/{str}") + public String echo(@PathVariable String str) { + return "provider-" + str; + } + +} +``` +### 应用启动 + + +支持 IDE 直接启动和编译打包后启动。 + +- 启动nacos 注册中心 + +- 启动服务提供方: + +1. IDE直接启动:找到主类 `ProviderApplication`,执行 main 方法启动应用。 +2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-provider-example.jar`启动应用。 + +- 启动服务消费方: + +1. IDE直接启动:找到主类 `ConsumerApplication`,执行 main 方法启动应用。 +2. 打包编译后启动:首先执行 `mvn clean package` 将工程编译打包,然后执行 `java -jar sentinel-feign-consumer-example.jar`启动应用。 diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme.md new file mode 100644 index 00000000..875c019e --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/readme.md @@ -0,0 +1,126 @@ +# Sentinel Feign Example + +Project description + +This project demonstrates how to use Sentinel starter to complete the Spring Cloud application call. + +[Sentinel](https://github.com/alibaba/Sentinel) is alibaba open source distributed system flow defense components, Sentinel flow as the breakthrough point, from the flow control, fusing the drop, the stability of the system load multiple dimensions, such as protection services. + +[OpenFeign](https://github.com/spring-cloud/spring-cloud-openfeign) is a declarative, templated HTTP client, Feign can help us faster and gracefully HTTP API calls. + +By focusing on this project, the integration of Sentinel and Feign more characteristics about Sentinel can view [Sentinel - core - example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example). + +## sample + +Service consumer +Before launching the example, let's see how Feign can access Sentinel. +** note that this section is for your convenience only. The access has been completed in this sample code and you do not need to modify it. * * + +First, modify the pom.xml file to introduce Sentinel starter and Dubbo starter. + +```xml + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + +``` +2. Secondly, nacos registries are used + +```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + +``` + +3. Define the FeignClient and its degraded configuration + +```java +@FeignClient(name = "service-provider", fallbackFactory = EchoServiceFallbackFactory.class) +public interface EchoService { + + /** + * 调用服务提供方的输出接口 + * + * @param str 用户输入 + * @return + */ + @GetMapping(value = "/echo/{str}") + String echo(@PathVariable("str") String str); +} +``` +- define a fallback factory to get an exception + +```java +@Component +public class EchoServiceFallbackFactory implements FallbackFactory { + @Override + public EchoServiceFallback create(Throwable throwable) { + return new EchoServiceFallback(throwable); + } +} +``` + +- define a specific fallback implementation +```java +public class EchoServiceFallback implements EchoService { + private Throwable throwable; + + EchoServiceFallback(Throwable throwable) { + this.throwable = throwable; + } + + @Override + public String echo(String str) { + return "consumer-fallback-default-str" + throwable.getMessage(); + } +} +``` +Service provider + +1. First, rely on the nacos registry + +```xml + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + +``` + + +2. Define the service provider interface + +```java +@RestController +public class EchoController { + + @GetMapping("/echo/{str}") + public String echo(@PathVariable String str) { + return "provider-" + str; + } + +} +``` + +Application launch + + +Support for IDE startup directly and after compilation and packaging. + +- launch the nacos registry + +- starting service provider: + +1. IDE starts directly: find the main class `ProviderApplication` and execute the main method to start the application. +2. Start after packaging and compilation: first execute `mvn clean package` to compile and package the project, and then execute `java-jar sentinel-feign-provider-example.jar` to start the application. + +- starting service consumer: + +1. IDE launch directly: find the main class `ConsumerApplication` and execute the main method to launch the application. +2. Start after packaging and compilation: first execute `mvn clean package` to compile and package the project, and then execute `java-jar sentinel-feign-consumer-example.jar` to start the application. \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sms-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/pom.xml similarity index 71% rename from spring-cloud-alibaba-examples/sms-example/pom.xml rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/pom.xml index 1a0fffae..d1766e19 100644 --- a/spring-cloud-alibaba-examples/sms-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/pom.xml @@ -1,39 +1,46 @@ - 4.0.0 - - sms-example - jar - Example demonstrating how to use alicloud sms com.alibaba.cloud spring-cloud-alibaba-examples 2.0.1.RELEASE - ../pom.xml + ../../../pom.xml + 4.0.0 - - UTF-8 - UTF-8 - + + sentinel-feign-consumer-example + jar + Example demonstrating how to use sentinel with feign - - - org.springframework.boot - spring-boot-starter-actuator - org.springframework.boot spring-boot-starter-web com.alibaba.cloud - spring-cloud-starter-alicloud-sms + spring-cloud-starter-alibaba-nacos-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + + @@ -53,5 +60,4 @@ - diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java similarity index 73% rename from spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java index 4a22d36c..49b5b295 100644 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-feign-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,14 +17,14 @@ package com.alibaba.cloud.examples; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.cloud.client.SpringCloudApplication; import org.springframework.cloud.openfeign.EnableFeignClients; /** - * @author xiaolongzuo + * @author lengleng */ -@SpringBootApplication -@EnableFeignClients(basePackages = { "com.alibaba.cloud.examples" }) +@EnableFeignClients +@SpringCloudApplication public class ConsumerApplication { public static void main(String[] args) { diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/controller/TestController.java similarity index 52% rename from spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestController.java rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/controller/TestController.java index 3230e9b0..209439ab 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/TestController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/controller/TestController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,26 +14,27 @@ * limitations under the License. */ -package com.alibaba.cloud.examples; +package com.alibaba.cloud.examples.controller; -import java.util.concurrent.atomic.AtomicInteger; +import com.alibaba.cloud.examples.service.EchoService; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** - * @author xiaolongzuo + * @author lengleng */ @RestController public class TestController { - static AtomicInteger atomicInteger = new AtomicInteger(0); + @Autowired + private EchoService echoService; - @RequestMapping("/test") - @ResponseBody - public String test() { - return String.valueOf(atomicInteger.get()); + @GetMapping("/echo-feign/{str}") + public String feign(@PathVariable String str) { + return echoService.echo(str); } } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallback.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallback.java new file mode 100644 index 00000000..30a9de2b --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallback.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples.fallback; + +import com.alibaba.cloud.examples.service.EchoService; + +/** + * @author lengleng + * @date 2019-08-01 + *

+ * sentinel 降级处理 + */ +public class EchoServiceFallback implements EchoService { + + private Throwable throwable; + + EchoServiceFallback(Throwable throwable) { + this.throwable = throwable; + } + + /** + * 调用服务提供方的输出接口. + * @param str 用户输入 + * @return + */ + @Override + public String echo(String str) { + return "consumer-fallback-default-str" + throwable.getMessage(); + } + +} diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/MyPartitionSelectorStrategy.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallbackFactory.java similarity index 55% rename from spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/MyPartitionSelectorStrategy.java rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallbackFactory.java index fdf202e7..94366678 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/src/main/java/com/alibaba/cloud/examples/MyPartitionSelectorStrategy.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/fallback/EchoServiceFallbackFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -14,18 +14,22 @@ * limitations under the License. */ -package com.alibaba.cloud.examples; +package com.alibaba.cloud.examples.fallback; -import org.springframework.cloud.stream.binder.PartitionSelectorStrategy; +import feign.hystrix.FallbackFactory; + +import org.springframework.stereotype.Component; /** - * @author Jim + * @author lengleng + * @date 2019-08-01 */ -public class MyPartitionSelectorStrategy implements PartitionSelectorStrategy { +@Component +public class EchoServiceFallbackFactory implements FallbackFactory { + @Override - public int selectPartition(Object key, int partitionCount) { - System.out - .println("partition key: " + key + ", partitionCount: " + partitionCount); - return 0; + public EchoServiceFallback create(Throwable throwable) { + return new EchoServiceFallback(throwable); } + } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/service/EchoService.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/service/EchoService.java new file mode 100644 index 00000000..4e0da067 --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/java/com/alibaba/cloud/examples/service/EchoService.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.examples.service; + +import com.alibaba.cloud.examples.fallback.EchoServiceFallbackFactory; + +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; + +/** + * @author lengleng + * @date 2019-08-01 + *

+ * example feign client + */ +@FeignClient(name = "service-provider", + fallbackFactory = EchoServiceFallbackFactory.class) +public interface EchoService { + + /** + * 调用服务提供方的输出接口. + * @param str 用户输入 + * @return echo result + */ + @GetMapping("/echo/{str}") + String echo(@PathVariable("str") String str); + +} diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/resources/application.yml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/resources/application.yml new file mode 100644 index 00000000..219c38d0 --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-consumer-example/src/main/resources/application.yml @@ -0,0 +1,20 @@ +server: + port: 18087 + +spring: + application: + name: service-consumer + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 + +feign: + sentinel: + enabled: true + +management: + endpoints: + web: + exposure: + include: '*' diff --git a/spring-cloud-alibaba-examples/oss-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/pom.xml similarity index 84% rename from spring-cloud-alibaba-examples/oss-example/pom.xml rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/pom.xml index 97b73c7f..240fabc6 100644 --- a/spring-cloud-alibaba-examples/oss-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/pom.xml @@ -6,13 +6,14 @@ com.alibaba.cloud spring-cloud-alibaba-examples 2.0.1.RELEASE + ../../../pom.xml 4.0.0 - oss-example + sentinel-feign-provider-example jar - Example demonstrating how to use alicloud oss + Example demonstrating how to use sentinel with feign @@ -22,14 +23,13 @@ com.alibaba.cloud - spring-cloud-starter-alicloud-oss + spring-cloud-starter-alibaba-nacos-discovery org.springframework.boot spring-boot-starter-actuator - diff --git a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java similarity index 88% rename from spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java index 97c5592e..e3ac3f96 100644 --- a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/ProviderApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,10 +21,10 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** - * @author xiaolongzuo + * @author lengleng */ -@SpringBootApplication @EnableDiscoveryClient +@SpringBootApplication public class ProviderApplication { public static void main(String[] args) { diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/HelloController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/controller/EchoController.java similarity index 57% rename from spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/HelloController.java rename to spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/controller/EchoController.java index 56410502..c74f7b48 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/HelloController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/java/com/alibaba/cloud/examples/controller/EchoController.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,22 +14,22 @@ * limitations under the License. */ -package com.alibaba.cloud.examples; +package com.alibaba.cloud.examples.controller; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.ResponseBody; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; /** - * @author xiaolongzuo + * @author lengleng + * @date 2019-08-01 */ @RestController -public class HelloController { +public class EchoController { - @RequestMapping("/") - @ResponseBody - public String hello() { - return "OK"; + @GetMapping("/echo/{str}") + public String echo(@PathVariable String str) { + return "provider-" + str; } } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/resources/application.yml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/resources/application.yml new file mode 100644 index 00000000..f6098ec7 --- /dev/null +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-feign-example/sentinel-feign-provider-example/src/main/resources/application.yml @@ -0,0 +1,16 @@ +server: + port: 18088 + +spring: + application: + name: service-provider + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 + +management: + endpoints: + web: + exposure: + include: '*' diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/MySCGConfiguration.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/MySCGConfiguration.java index a5da97d5..89b0f532 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/MySCGConfiguration.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/MySCGConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,7 +17,6 @@ package com.alibaba.cloud.examples; import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; - import reactor.core.publisher.Mono; import org.springframework.context.annotation.Bean; @@ -40,8 +39,7 @@ public class MySCGConfiguration { @Override public Mono handleRequest(ServerWebExchange exchange, Throwable t) { - return ServerResponse.status(444) - .contentType(MediaType.APPLICATION_JSON_UTF8) + return ServerResponse.status(444).contentType(MediaType.APPLICATION_JSON) .body(fromObject("SCS Sentinel block")); } }; diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/RulesWebFluxController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/RulesWebFluxController.java index 8ff27269..cdf1c887 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/RulesWebFluxController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/RulesWebFluxController.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; - import reactor.core.publisher.Mono; import org.springframework.web.bind.annotation.GetMapping; diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/SentinelSpringCloudGatewayApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/SentinelSpringCloudGatewayApplication.java index 137c6e91..7e13e3f4 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/SentinelSpringCloudGatewayApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/java/com/alibaba/cloud/examples/SentinelSpringCloudGatewayApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/api.json b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/api.json index 72a62c47..6de3c4fb 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/api.json +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/api.json @@ -29,4 +29,4 @@ } ] } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/application.yaml index a64f0a02..37181d40 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/application.yaml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/application.yaml @@ -31,15 +31,13 @@ spring: ruleType: gw-api-group transport: dashboard: localhost:8080 -# filter: -# enabled: true + filter: + enabled: true scg.fallback: - mode: redirect - redirect: http://www.taobao.com + mode: response + response-status: 444 + response-body: 1234 scg: order: -100 -# response-status: 444 -# response-body: 1234 -# content-type: text/plain management.endpoints.web.exposure.include: "*" \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/gateway.json b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/gateway.json index d8cb8744..b08f71fc 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/gateway.json +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-spring-cloud-gateway-example/src/main/resources/gateway.json @@ -19,4 +19,4 @@ "fieldName": "name" } } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/MyConfiguration.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/MyConfiguration.java index b136f882..c1912ab4 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/MyConfiguration.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/MyConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,16 @@ package com.alibaba.cloud.examples; -import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; +import java.util.Collections; +import com.alibaba.cloud.circuitbreaker.sentinel.ReactiveSentinelCircuitBreakerFactory; +import com.alibaba.cloud.circuitbreaker.sentinel.SentinelConfigBuilder; +import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import reactor.core.publisher.Mono; +import org.springframework.cloud.client.circuitbreaker.Customizer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpStatus; @@ -42,10 +48,28 @@ public class MyConfiguration { public Mono handleRequest(ServerWebExchange exchange, Throwable t) { return ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS) - .contentType(MediaType.APPLICATION_JSON_UTF8) - .body(fromObject("block")); + .contentType(MediaType.APPLICATION_JSON).body(fromObject("block")); } }; } + @Bean + public Customizer slowCustomizer() { + return factory -> { + factory.configure(builder -> builder.rules(Collections.singletonList( + new DegradeRule("slow_mono").setGrade(RuleConstant.DEGRADE_GRADE_RT) + .setCount(100).setTimeWindow(5))), + "slow_mono"); + factory.configure(builder -> builder.rules(Collections.singletonList( + new DegradeRule("slow_flux").setGrade(RuleConstant.DEGRADE_GRADE_RT) + .setCount(100).setTimeWindow(5))), + "slow_flux"); + factory.configureDefault(id -> new SentinelConfigBuilder().resourceName(id) + .rules(Collections.singletonList(new DegradeRule(id) + .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) + .setCount(0.5).setTimeWindow(10))) + .build()); + }; + } + } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxApplication.java index 353b8ba0..b933d56a 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxController.java index 213a2ec3..d0b45891 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/java/com/alibaba/cloud/examples/SentinelWebFluxController.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -17,13 +17,14 @@ package com.alibaba.cloud.examples; import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer; -import com.alibaba.csp.sentinel.annotation.SentinelResource; - import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; /** * @author Jim @@ -31,6 +32,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController public class SentinelWebFluxController { + @Autowired + private ReactiveCircuitBreakerFactory circuitBreakerFactory; + @GetMapping("/mono") public Mono mono() { return Mono.just("simple string") @@ -38,6 +42,13 @@ public class SentinelWebFluxController { .transform(new SentinelReactorTransformer<>("mono")); } + @GetMapping("/test") + public Mono test() { + return Mono.just("simple string") + // transform the publisher here. + .transform(new SentinelReactorTransformer<>("test")); + } + @GetMapping("/flux") public Flux flux() { return Flux.fromArray(new String[] { "a", "b", "c" }) @@ -45,19 +56,26 @@ public class SentinelWebFluxController { .transform(new SentinelReactorTransformer<>("flux")); } - @GetMapping("/aaa") - @SentinelResource("abc") - public Flux aaa() { - return Flux.fromArray(new String[] { "a", "b", "c" }) - // transform the publisher here. - .transform(new SentinelReactorTransformer<>("aaa")); + @GetMapping("/cbSlow") + public Mono cbSlow() { + int delaySecs = 2; + return WebClient.builder().baseUrl("http://httpbin.org/").build().get() + .uri("/delay/" + delaySecs).retrieve().bodyToMono(String.class) + .transform(it -> circuitBreakerFactory.create("slow_mono").run(it, t -> { + t.printStackTrace(); + return Mono.just("fallback"); + })); } - @GetMapping("/test") - public Flux test() { - return Flux.fromArray(new String[] { "a", "b", "c" }) - // transform the publisher here. - .transform(new SentinelReactorTransformer<>("test")); + @GetMapping("/cbError") + public Mono cbError() { + String code = "500"; + return WebClient.builder().baseUrl("http://httpbin.org/").build().get() + .uri("/status/" + code).retrieve().bodyToMono(String.class) + .transform(it -> circuitBreakerFactory.create("cbError").run(it, t -> { + t.printStackTrace(); + return Mono.just("fallback"); + })); } } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/application.properties index 3bbd4f37..48bd8f43 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/application.properties +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/application.properties @@ -3,8 +3,6 @@ server.port=18084 management.endpoints.web.exposure.include=* spring.cloud.sentinel.transport.dashboard=localhost:8080 spring.cloud.sentinel.eager=true - - spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json spring.cloud.sentinel.datasource.ds1.file.data-type=json -spring.cloud.sentinel.datasource.ds1.file.rule-type=flow \ No newline at end of file +spring.cloud.sentinel.datasource.ds1.file.rule-type=flow diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/flowrule.json b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/flowrule.json index 422343cc..10e022b8 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/flowrule.json +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-webflux-example/src/main/resources/flowrule.json @@ -15,13 +15,4 @@ "limitApp": "default", "strategy": 0 } -, - { - "resource": "abc", - "controlBehavior": 0, - "count": 0, - "grade": 1, - "limitApp": "default", - "strategy": 0 - } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/pom.xml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/pom.xml index d7ded147..73712f48 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/pom.xml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/pom.xml @@ -60,7 +60,6 @@ - diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/RulesController.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/RulesController.java index 3af8104a..5475bcdd 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/RulesController.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/RulesController.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/SentinelZuulApplication.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/SentinelZuulApplication.java index 4c2243c6..476cbb05 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/SentinelZuulApplication.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/SentinelZuulApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/ZuulConfiguration.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/ZuulConfiguration.java index 96164f10..d3e1ffea 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/ZuulConfiguration.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/java/com/alibaba/cloud/examples/ZuulConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/api.json b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/api.json index 72a62c47..6de3c4fb 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/api.json +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/api.json @@ -29,4 +29,4 @@ } ] } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/application.yaml index 4d00e17f..0e9d9abf 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/application.yaml +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/application.yaml @@ -13,8 +13,8 @@ spring: ruleType: gw-api-group transport: dashboard: localhost:8080 -# filter: -# enabled: true + filter: + enabled: false management.endpoints.web.exposure.include: "*" diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/gateway.json b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/gateway.json index d55265ea..b3effe88 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/gateway.json +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-zuul-example/src/main/resources/gateway.json @@ -23,4 +23,4 @@ "fieldName": "name" } } -] \ No newline at end of file +] diff --git a/spring-cloud-alibaba-examples/sms-example/readme-zh.md b/spring-cloud-alibaba-examples/sms-example/readme-zh.md deleted file mode 100644 index 69076551..00000000 --- a/spring-cloud-alibaba-examples/sms-example/readme-zh.md +++ /dev/null @@ -1,314 +0,0 @@ -# SMS Example - -## 项目说明 - -如果您的应用是 Spring Cloud/Boot 应用,且需要使用阿里云的 SMS 服务来发送短信,例如登录验证码,那么您可以使用 SMS starter 完成 Spring Cloud/Boot 应用的短信发送。 - -短信服务(Short Message Service)是阿里云为用户提供的一种通信服务的能力。支持国内和国际快速发送验证码、短信通知和推广短信,服务范围覆盖全球200多个国家和地区。更多可参考 [官网文档](https://help.aliyun.com/document_detail/60704.html?spm=5176.8195934.1283918.6.18924183bHPct2) - -## 示例 - -### 接入 SMS - -在启动示例进行演示之前,我们先了解一下如何接入 SMS。 - -**注意:本节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您只需修改 accessKey、secretKey 即可。** - -1. 修改 pom.xml 文件,引入 alicloud-sms starter。 - - ```xml - - com.alibaba.cloud - spring-cloud-starter-alicloud-sms - - ``` - -1. 在配置文件中配置 SMS 服务对应的 accessKey、secretKey 。 - - ```properties - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - ``` - - 以阿里云 accessKey、secretKey 为例,获取方式如下。 - - i. 在阿里云控制台界面,单击右上角头像,选择 accesskeys,或者直接登录[用户信息管理界面](https://usercenter.console.aliyun.com/): - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535371973274-3ebec90a-ebde-4eb7-96ed-5372f6b32fe0.png) - - ii. 获取 accessKey、secretKey: - - ![undefined](https://cdn.nlark.com/lark/0/2018/png/64647/1535372168883-b94a3d77-3f81-4938-b409-611945a9e21c.png) - - **注意:**如果您使用了阿里云 [STS服务](https://help.aliyun.com/document_detail/28756.html) 进行短期访问权限管理,则除了 accessKey、secretKey 以外,还需配置 securityToken。 - -1. 注入 ISmsService 实例并进行短信发送等操作。 - - ```java - @RestController - public class SmsController { - @Autowired - private ISmsService smsService ; - - @RequestMapping("/send.do") - public SendSmsResponse sendMessage(String telphone,String code) { - // 组装请求对象-具体描述见控制台-文档部分内容 - SendSmsRequest request = new SendSmsRequest(); - // 必填:待发送手机号 - request.setPhoneNumbers(telphone); - // 必填:短信签名-可在短信控制台中找到 - request.setSignName("******"); - // 必填:短信模板-可在短信控制台中找到 - request.setTemplateCode("******"); - // 可选:模板中的变量替换JSON串,如模板内容为"【企业级分布式应用服务】,您的验证码为${code}"时,此处的值为 - request.setTemplateParam("{\"code\":\"" + code + "\"}"); - SendSmsResponse sendSmsResponse ; - try { - sendSmsResponse = smsService.sendSmsRequest(request); - } - catch (ClientException e) { - e.printStackTrace(); - sendSmsResponse = new SendSmsResponse(); - } - return sendSmsResponse ; - } - } - ``` - - **说明:** 直接注入 ISmsService 方式即可。 - -### 启动应用 - - -1. 在应用的 /src/main/resources/application.properties 中添加基本配置信息。 - - ```properties - spring.application.name=sms-example - server.port=18084 - spring.cloud.alicloud.access-key=your-ak - spring.cloud.alicloud.secret-key=your-sk - ``` - -2. 通过 IDE 直接启动或者编译打包后启动应用。 - - - IDE直接启动:找到主类 `SMSApplication`,执行 main 方法启动应用。 - - 打包编译后启动: - 1. 执行 `mvn clean package` 将工程编译打包; - 2. 执行 `java -jar sms-example.jar`启动应用。 - -应用启动后访问 http://localhost:18084/send.do?telphone=******&code=6580。 查看返回的 SendSmsResponse 的 json 串结果。 - - -### 批量短信发送 - -参考以下的 Example ,来快速开发一个具有批量短信发送的功能。在 Controller 中或者新建一个 Controler 新增如下代码: - - -```java -@RequestMapping("/batch-sms-send.do") -public SendBatchSmsResponse batchsendCheckCode( - @RequestParam(name = "code") String code) { - // 组装请求对象 - SendBatchSmsRequest request = new SendBatchSmsRequest(); - // 使用 GET 提交 - request.setMethod(MethodType.GET); - // 必填:待发送手机号。支持JSON格式的批量调用,批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 - request.setPhoneNumberJson("[\"177********\",\"130********\"]"); - // 必填:短信签名-支持不同的号码发送不同的短信签名 - request.setSignNameJson("[\"*******\",\"*******\"]"); - // 必填:短信模板-可在短信控制台中找到 - request.setTemplateCode("******"); - // 必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 - // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败 - request.setTemplateParamJson( - "[{\"code\":\"" + code + "\"},{\"code\":\"" + code + "\"}]"); - SendBatchSmsResponse sendSmsResponse ; - try { - sendSmsResponse = smsService - .sendSmsBatchRequest(request); - return sendSmsResponse; - } - catch (ClientException e) { - e.printStackTrace(); - sendSmsResponse = new SendBatchSmsResponse(); - } - return sendSmsResponse ; -} -``` - -### 短信查询 - -参考以下的 Example ,可以快速开发根据某个指定的号码查询短信历史发送状态。在 Controller 中或者新建一个 Controler 新增如下代码: - -```java -/** - * - * 短信查询 Example - * @param telephone - * @return - */ -@RequestMapping("/query.do") -public QuerySendDetailsResponse querySendDetailsResponse( - @RequestParam(name = "tel") String telephone) { - // 组装请求对象 - QuerySendDetailsRequest request = new QuerySendDetailsRequest(); - // 必填-号码 - request.setPhoneNumber(telephone); - // 必填-短信发送的日期 支持30天内记录查询(可查其中一天的发送数据),格式yyyyMMdd - request.setSendDate("20190103"); - // 必填-页大小 - request.setPageSize(10L); - // 必填-当前页码从1开始计数 - request.setCurrentPage(1L); - try { - QuerySendDetailsResponse response = smsService.querySendDetails(request); - return response; - } - catch (ClientException e) { - e.printStackTrace(); - } - - return new QuerySendDetailsResponse(); -} - -``` - -查询成功后的返回结果如下所示: - - ```plain - { - "requestId": "0030EE65-25B1-43EE-BA90-D8FDACC45DC7", - "code": "OK", - "message": "OK", - "totalCount": "3", - "smsSendDetailDTOs": [ - { - "phoneNum": "152********", - "sendStatus": 3, - "errCode": "DELIVRD", - "templateCode": "SMS_******", - "content": "【企业级分布式应用服务】验证码为:1080,您正在注册成为平台会员,感谢您的支持!", - "sendDate": "2019-01-03 22:09:09", - "receiveDate": "2019-01-03 22:09:21", - "outId": "edasTraceId" - }, - { - "phoneNum": "152********", - "sendStatus": 3, - "errCode": "DELIVRD", - "templateCode": "SMS_******", - "content": "【企业级分布式应用服务】验证码为:1865,您正在注册成为平台会员,感谢您的支持!", - "sendDate": "2019-01-03 21:13:30", - "receiveDate": "2019-01-03 21:13:37", - "outId": "edasTraceId" - }, - { - "phoneNum": "152********", - "sendStatus": 3, - "errCode": "DELIVRD", - "templateCode": "SMS_*******", - "content": "【企业级分布式应用服务】验证码为:9787,您正在注册成为平台会员,感谢您的支持!", - "sendDate": "2019-01-03 17:19:11", - "receiveDate": "2019-01-03 17:19:15", - "outId": "edasTraceId" - } - ] - } - ``` - -### 短信回执消息 - -通过订阅 SmsReport 短信状态报告,可以获知每条短信的发送情况,了解短信是否达到终端用户的状态与相关信息。这些工作已经都被 Spring Cloud AliCloud SMS 封装在内部了。你只需要完成以下两步即可。 - -1. 在 **application.properties** 配置文件中(也可以是 application.yaml)配置 SmsReport 的队列名称。 - - ```properties - spring.cloud.alicloud.sms.report-queue-name=Alicom-Queue-********-SmsReport - ``` - -2. 实现 SmsReportMessageListener 接口,并初始化一个 Spring Bean . - - ```java - /** - * 如果需要监听短信是否被对方成功接收,只需实现这个接口并初始化一个 Spring Bean 即可。 - */ - @Component - public class SmsReportMessageListener - implements SmsReportMessageListener { - - @Override - public boolean dealMessage(Message message) { - // 在这里添加你的处理逻辑 - - //do something - - System.err.println(this.getClass().getName() + "; " + message.toString()); - return true; - } - } - ``` - -发送状态的回执消息如下所示: - -```plain -SmsReportMessageListener; MessageID:9F3CFCE6BB3B2C8F-2-1682D84D9AD-20000000A,MessageMD5:C6AFEE0EE560BBC3380252337AC36985,RequestID:5C349CCEB8C115CCF344A3EB,MessageBody:"{"send_time":"2019-01-08 20:51:40","report_time":"2019-01-08 20:51:47","success":true,"err_msg":"用户接收成功","err_code":"DELIVERED","phone_number":"152********","sms_size":"1","biz_id":"667618746951900475^0","out_id":"edasTraceId"}",ReceiptHandle:"1-ODU4OTkzNDYwMi0xNTQ2OTUxOTM3LTItOA==",DequeueCount:"1",EnqueueTime:"Tue Jan 08 20:51:47 CST 2019",FirstDequeueTime:"Tue Jan 08 20:51:47 CST 2019",NextVisibleTime:"Tue Jan 08 20:52:17 CST 2019",Priority:"8" -``` - -### 上行短信消息 - - -通过订阅SmsUp上行短信消息,可以获知终端用户回复短信的内容。这些工作也已经被 Spring Cloud AliCloud SMS 封装好了。你只需要完成以下两步即可。 - -1. 在 **application.properties** 配置文件中(也可以是 application.yaml)配置 SmsReport 的队列名称。 - - ```properties - spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp - ``` - -1. 实现 SmsUpMessageListener 接口,并初始化一个 Spring Bean 。 - - ```java - /** - * 如果发送的短信需要接收对方回复的状态消息,只需实现该接口并初始化一个 Spring Bean 即可。 - */ - @Component - public class SmsUpMessageListener - implements SmsUpMessageListener { - - @Override - public boolean dealMessage(Message message) { - // 在这里添加你的处理逻辑 - - //do something - - System.err.println(this.getClass().getName() + "; " + message.toString()); - return true; - } - } - ``` - -短信成功恢复后,上行短信消息 SmsUpMessageListener 回调后的信息如下所示: - -```plain -SmsUpMessageListener; MessageID:BF030215BA85BB41-1-1682D85425F-400000003,MessageMD5:D1AF5C2D7410EF190532CBF8E17FE2B7,RequestID:5C349CEE36AF628D2A847D50,MessageBody:"{"dest_code":"2493559","send_time":"2019-01-08 20:52:14","sign_name":"【企业级分布式应用服务】","sequence_id":568585703,"phone_number":"152********","content":"5279"}",ReceiptHandle:"1-MTcxNzk4NjkxODctMTU0Njk1MTk2NC0xLTg=",DequeueCount:"1",EnqueueTime:"Tue Jan 08 20:52:14 CST 2019",FirstDequeueTime:"Tue Jan 08 20:52:14 CST 2019",NextVisibleTime:"Tue Jan 08 20:52:44 CST 2019",Priority:"8" -``` - -## 查看 Endpoint 信息 - -Spring Boot 应用支持通过 Endpoint 来暴露相关信息,SMS Starter 也支持这一点。 - -**前提条件:** - -在 maven 中添加 `spring-boot-starter-actuator`依赖,并在配置中允许 Endpoints 的访问。 - -- Spring Boot1.x 中添加配置 `management.security.enabled=false` -- Spring Boot2.x 中添加配置 `management.endpoints.web.exposure.include=*` - -Spring Boot1.x 可以通过访问 http://127.0.0.1:18084/sms-info 来查看 SMS Endpoint 的信息。 - -Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/actuator/sms-info 来访问。 - -Endpoint 内部会显示最近 20 条单个短信发送的记录和批量短信发送的记录,以及当前短信消息的配置信息(包括是**SmsReport** 还是 **SmsUp**,**队列名称**,以及对应的 **MessageListener** )。 - - -如果您对 Spring Cloud SMS Starter 有任何建议或想法,欢迎提交 issue 中或者通过其他社区渠道向我们反馈。 diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsController.java b/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsController.java deleted file mode 100644 index 56bfe1df..00000000 --- a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsController.java +++ /dev/null @@ -1,145 +0,0 @@ -package com.alibaba.cloud.examples; - -import java.util.List; - -import com.alibaba.alicloud.sms.ISmsService; - -import com.aliyun.mns.model.Message; -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; -import com.aliyuncs.exceptions.ClientException; -import com.aliyuncs.http.MethodType; - -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.RequestMapping; -import org.springframework.web.bind.annotation.RequestParam; -import org.springframework.web.bind.annotation.RestController; - -@RestController -public class SmsController { - - @Autowired - private Environment environment; - - @Autowired - private ISmsService smsService; - - @Autowired - private SmsReportMessageListener smsReportMessageListener; - - @GetMapping("/report-queue.do") - public String getSmsReportQueuename() { - - return environment.getProperty("spring.cloud.alicloud.sms.up-queue-name"); - } - - /** - * 短信发送 Example - * @param code - * @return - */ - @RequestMapping("/batch-sms-send.do") - public SendBatchSmsResponse batchsendCheckCode( - @RequestParam(name = "code") String code) { - // 组装请求对象 - SendBatchSmsRequest request = new SendBatchSmsRequest(); - // 使用post提交 - request.setMethod(MethodType.GET); - // 必填:待发送手机号。支持JSON格式的批量调用,批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 - request.setPhoneNumberJson("[\"177********\",\"130********\"]"); - // 必填:短信签名-支持不同的号码发送不同的短信签名 - request.setSignNameJson("[\"*******\",\"*******\"]"); - // 必填:短信模板-可在短信控制台中找到 - request.setTemplateCode("******"); - // 必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 - // 友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败 - request.setTemplateParamJson( - "[{\"code\":\"" + code + "\"},{\"code\":\"" + code + "\"}]"); - // 可选-上行短信扩展码(扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段) - // request.setSmsUpExtendCodeJson("[\"90997\",\"90998\"]"); - try { - SendBatchSmsResponse sendSmsResponse = smsService - .sendSmsBatchRequest(request); - return sendSmsResponse; - } - catch (ClientException e) { - e.printStackTrace(); - } - return new SendBatchSmsResponse(); - } - - /** - * 短信发送 Example - * @param code - * @return - */ - @RequestMapping("/sms-send.do") - public SendSmsResponse sendCheckCode(@RequestParam(name = "code") String code) { - // 组装请求对象-具体描述见控制台-文档部分内容 - SendSmsRequest request = new SendSmsRequest(); - // 必填:待发送手机号 - request.setPhoneNumbers("******"); - // 必填:短信签名-可在短信控制台中找到 - request.setSignName("******"); - // 必填:短信模板-可在短信控制台中找到 - request.setTemplateCode("******"); - // 可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为 - request.setTemplateParam("{\"code\":\"" + code + "\"}"); - - // 选填-上行短信扩展码(无特殊需求用户请忽略此字段) - // request.setSmsUpExtendCode("90997"); - - // 可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者 - request.setOutId("****TraceId"); - try { - SendSmsResponse sendSmsResponse = smsService.sendSmsRequest(request); - return sendSmsResponse; - } - catch (ClientException e) { - e.printStackTrace(); - } - return new SendSmsResponse(); - } - - /** - * - * 短信查询 Example - * @param telephone - * @return - */ - @RequestMapping("/query.do") - public QuerySendDetailsResponse querySendDetailsResponse( - @RequestParam(name = "tel") String telephone) { - // 组装请求对象 - QuerySendDetailsRequest request = new QuerySendDetailsRequest(); - // 必填-号码 - request.setPhoneNumber(telephone); - // 必填-短信发送的日期 支持30天内记录查询(可查其中一天的发送数据),格式yyyyMMdd - request.setSendDate("20190103"); - // 必填-页大小 - request.setPageSize(10L); - // 必填-当前页码从1开始计数 - request.setCurrentPage(1L); - try { - QuerySendDetailsResponse response = smsService.querySendDetails(request); - return response; - } - catch (ClientException e) { - e.printStackTrace(); - } - - return new QuerySendDetailsResponse(); - } - - @RequestMapping("/sms-report.do") - public List smsReport() { - - return smsReportMessageListener.getSmsReportMessageSet(); - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsReportMessageListener.java b/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsReportMessageListener.java deleted file mode 100644 index d77d4390..00000000 --- a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsReportMessageListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package com.alibaba.cloud.examples; - -import java.util.LinkedList; -import java.util.List; - -import com.aliyun.mns.model.Message; - -import org.springframework.stereotype.Component; - -/** - * @author 如果需要监听短信是否被对方成功接收,只需实现这个接口并初始化一个 Spring Bean 即可。 - */ -@Component -public class SmsReportMessageListener - implements com.alibaba.alicloud.sms.SmsReportMessageListener { - private List smsReportMessageSet = new LinkedList<>(); - - @Override - public boolean dealMessage(Message message) { - smsReportMessageSet.add(message); - System.err.println(this.getClass().getName() + "; " + message.toString()); - return true; - } - - public List getSmsReportMessageSet() { - - return smsReportMessageSet; - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsUpMessageListener.java b/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsUpMessageListener.java deleted file mode 100644 index dbd9d693..00000000 --- a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsUpMessageListener.java +++ /dev/null @@ -1,19 +0,0 @@ -package com.alibaba.cloud.examples; - -import com.aliyun.mns.model.Message; - -import org.springframework.stereotype.Component; - -/** - * @author 如果发送的短信需要接收对方回复的状态消息,只需实现该接口并初始化一个 Spring Bean 即可。 - */ -@Component -public class SmsUpMessageListener - implements com.alibaba.alicloud.sms.SmsUpMessageListener { - - @Override - public boolean dealMessage(Message message) { - System.err.println(this.getClass().getName() + "; " + message.toString()); - return true; - } -} \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties b/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties deleted file mode 100644 index 4464cfe9..00000000 --- a/spring-cloud-alibaba-examples/sms-example/src/main/resources/application.properties +++ /dev/null @@ -1,9 +0,0 @@ -spring.application.name=sca-sms-example -server.port=9051 -# config sms -spring.cloud.alicloud.access-key=***** -spring.cloud.alicloud.secret-key=****** -spring.cloud.alicloud.sms.report-queue-name=***** -spring.cloud.alicloud.sms.up-queue-name=***** -#config endpoint -management.endpoints.web.exposure.include=* \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/README_CN.md b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/README_CN.md new file mode 100644 index 00000000..28e2428d --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/README_CN.md @@ -0,0 +1,348 @@ +# Dubbo Spring Cloud 示例工程 + + +## 快速开始 + +### 定义 Dubbo 服务接口 + +Dubbo 服务接口是服务提供方与消费方的远程通讯契约,通常由普通的 Java 接口(interface)来声明,如 `EchoService` 接口: + +```java +public interface EchoService { + + String echo(String message); +} +``` + +为了确保契约的一致性,推荐的做法是将 Dubbo 服务接口打包在第二方或者第三方的 artifact(jar)中,如以上接口就存放在 + artifact [spring-cloud-dubbo-sample-api](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api) 之中。 +对于服务提供方而言,不仅通过依赖 artifact 的形式引入 Dubbo 服务接口,而且需要将其实现。对应的服务消费端,同样地需要依赖该 artifact, +并以接口调用的方式执行远程方法。接下来进一步讨论怎样实现 Dubbo 服务提供方和消费方。 + + +### 实现 Dubbo 服务提供方 + + + +#### 初始化 `spring-cloud-dubbo-server-sample` Maven 工程 + +首先,创建 `artifactId` 名为 `spring-cloud-dubbo-server-sample` 的 Maven 工程,并在其 `pom.xml` 文件中增添 +Dubbo Spring Cloud 必要的依赖: + +```xml + + + + org.springframework.cloud + spring-cloud-dubbo-sample-api + ${project.version} + + + + + org.springframework.boot + spring-boot-actuator + + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + +``` + +以上依赖 artifact 说明如下: + +- `spring-cloud-dubbo-sample-api` : 提供 `EchoService` 接口的 artifact +- `spring-boot-actuator` : Spring Boot Production-Ready artifact,间接引入 `spring-boot` artifact +- `spring-cloud-starter-dubbo` : Dubbo Spring Cloud Starter `artifact`,间接引入 `dubbo-spring-boot-starter` 等 artifact +- `spring-cloud-starter-alibaba-nacos-discovery` : Nacos Spring Cloud 服务注册与发现 `artifact` + + +值得注意的是,以上 artifact 未指定版本(version),因此,还需显示地声明 `` : + +```xml + + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.9.0.RELEASE + pom + import + + + +``` + +> 以上完整的 Maven 依赖配置,请参考 `spring-cloud-dubbo-server-sample` [`pom.xml`](spring-cloud-dubbo-server-sample/pom.xml) 文件 + +完成以上步骤之后,下一步则是实现 Dubbo 服务 + + +#### 实现 Dubbo 服务 + +`EchoService` 作为暴露的 Dubbo 服务接口,服务提供方 `spring-cloud-dubbo-server-sample` 需要将其实现: + +```java +@org.apache.dubbo.config.annotation.Service +class EchoServiceImpl implements EchoService { + + @Override + public String echo(String message) { + return "[echo] Hello, " + message; + } +} +``` + +其中,`@org.apache.dubbo.config.annotation.Service` 是 Dubbo 服务注解,仅声明该 Java 服务(本地)实现为 Dubbo 服务。 +因此,下一步需要将其配置 Dubbo 服务(远程)。 + + + +#### 配置 Dubbo 服务提供方 + +在暴露 Dubbo 服务方面,推荐开发人员外部化配置的方式,即指定 Java 服务实现类的扫描基准包。 +> Dubbo Spring Cloud 继承了 Dubbo Spring Boot 的外部化配置特性,也可以通过标注 `@DubboComponentScan` 来实现基准包扫描。 + +同时,Dubbo 远程服务需要暴露网络端口,并设定通讯协议,完整的 YAML 配置如下所示: + +```yaml +dubbo: + scan: + # dubbo 服务扫描基准包 + base-packages: com.alibaba.cloud.dubbo.bootstrap + protocol: + # dubbo 协议 + name: dubbo + # dubbo 协议端口( -1 表示自增端口,从 20880 开始) + port: -1 + registry: + # 挂载到 Spring Cloud 注册中心 + address: spring-cloud://localhost + +spring: + application: + # Dubbo 应用名称 + name: spring-cloud-alibaba-dubbo-server + main: + # Spring Boot 2.1 需要设定 + allow-bean-definition-overriding: true + cloud: + nacos: + # Nacos 服务发现与注册配置 + discovery: + server-addr: 127.0.0.1:8848 +``` + +以上 YAML 内容,上半部分为 Dubbo 的配置: + +- `dubbo.scan.base-packages` : 指定 Dubbo 服务实现类的扫描基准包 +- `dubbo.protocol` : Dubbo 服务暴露的协议配置,其中子属性 `name` 为协议名称,`port` 为协议端口( -1 表示自增端口,从 20880 开始) +- `dubbo.registry` : Dubbo 服务注册中心配置,其中子属性 `address` 的值 "spring-cloud://localhost",说明挂载到 Spring Cloud 注册中心 +> 当前 Dubbo Spring Cloud 实现必须配置 `dubbo.registry.address = spring-cloud://localhost`,下一个版本将其配置变为可选 +(参考 [issue #592](https://github.com/alibaba/spring-cloud-alibaba/issues/592)), +> 并且支持传统 Dubbo 协议的支持(参考 [issue #588](https://github.com/alibaba/spring-cloud-alibaba/issues/588)) + +下半部分则是 Spring Cloud 相关配置: + +- `spring.application.name` : Spring 应用名称,用于 Spring Cloud 服务注册和发现。 +> 该值在 Dubbo Spring Cloud 加持下被视作 `dubbo.application.name`,因此,无需再显示地配置 `dubbo.application.name` +- `spring.main.allow-bean-definition-overriding` : 在 Spring Boot 2.1 以及更高的版本增加该设定, +因为 Spring Boot 默认调整了 Bean 定义覆盖行为。(推荐一个好的 Dubbo 讨论 [issue #3193](https://github.com/apache/dubbo/issues/3193#issuecomment-474340165)) +- `spring.cloud.nacos.discovery` : Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口 + +> 以上完整的 YAML 配置文件,请参考 `spring-cloud-dubbo-server-sample` [`bootstrap.yaml`](spring-cloud-dubbo-server-sample/src/main/resources/bootstrap.yaml) 文件 + + +完成以上步骤后,还需编写一个 Dubbo Spring Cloud 引导类。 + + +#### 引导 Dubbo Spring Cloud 服务提供方应用 + +Dubbo Spring Cloud 引导类与普通 Spring Cloud 应用并无差别,如下所示: +```java +@EnableDiscoveryClient +@EnableAutoConfiguration +public class DubboSpringCloudServerBootstrap { + + public static void main(String[] args) { + SpringApplication.run(DubboSpringCloudServerBootstrap.class); + } +} +``` + +在引导 `DubboSpringCloudServerBootstrap` 之前,请提前启动 Nacos 服务器。 +当 `DubboSpringCloudServerBootstrap` 启动后,将应用 `spring-cloud-dubbo-server-sample` 将出现在 Nacos 控制台界面。 + + +当 Dubbo 服务提供方启动后,下一步实现一个 Dubbo 服务消费方。 + + + +### 实现 Dubbo 服务消费方 + +由于 Java 服务就 `EchoService`、服务提供方应用 `spring-cloud-dubbo-server-sample` 以及 Nacos 服务器均已准备完毕。Dubbo 服务消费方 +只需初始化服务消费方 Maven 工程 `spring-cloud-dubbo-client-sample` 以及消费 Dubbo 服务。 + + + +#### 初始化 `spring-cloud-dubbo-client-sample` Maven 工程 + +与服务提供方 Maven 工程类,需添加相关 Maven 依赖: + +```xml + + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.9.0.RELEASE + pom + import + + + + + + + + org.springframework.cloud + spring-cloud-dubbo-sample-api + ${project.version} + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-actuator + + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + +``` + +与应用 `spring-cloud-dubbo-server-sample` 不同的是,当前应用依赖 `spring-boot-starter-web`,表明它属于 Web Servlet 应用。 + +> 以上完整的 Maven 依赖配置,请参考 `spring-cloud-dubbo-client-sample` [`pom.xml`](spring-cloud-dubbo-client-sample/pom.xml) 文件 + + +#### 配置 Dubbo 服务消费方 + +Dubbo 服务消费方配置与服务提供方类似,当前应用 `spring-cloud-dubbo-client-sample` 属于纯服务消费方,因此,所需的外部化配置更精简: + +```yaml +dubbo: + registry: + # 挂载到 Spring Cloud 注册中心 + address: spring-cloud://localhost + cloud: + subscribed-services: spring-cloud-alibaba-dubbo-server + +spring: + application: + # Dubbo 应用名称 + name: spring-cloud-alibaba-dubbo-client + main: + # Spring Boot 2.1 需要设定 + allow-bean-definition-overriding: true + cloud: + nacos: + # Nacos 服务发现与注册配置 + discovery: + server-addr: 127.0.0.1:8848 +``` + +对比应用 `spring-cloud-dubbo-server-sample`,除应用名称 `spring.application.name` 存在差异外,`spring-cloud-dubbo-client-sample` +新增了属性 `dubbo.cloud.subscribed-services` 的设置。并且该值为服务提供方应用 "spring-cloud-dubbo-server-sample"。 + +- `dubbo.cloud.subscribed-services` : 用于服务消费方订阅服务提供方的应用名称的列表,若需订阅多应用,使用 "," 分割。 +不推荐使用默认值为 "*",它将订阅所有应用。 +> 当应用使用属性 `dubbo.cloud.subscribed-services` 默认值时,日志中将会输出一行警告: +> > Current application will subscribe all services(size:x) in registry, a lot of memory and CPU cycles may be used, +> > thus it's strongly recommend you using the externalized property 'dubbo.cloud.subscribed-services' to specify the services + +由于当前应用属于 Web 应用,它会默认地使用 8080 作为 Web 服务端口,如果需要自定义,可通过属性 `server.port` 调整。 + +> 以上完整的 YAML 配置文件,请参考 `spring-cloud-dubbo-client-sample` [`bootstrap.yaml`](spring-cloud-dubbo-client-sample/src/main/resources/bootstrap.yaml) 文件 + + + +#### 引导 Dubbo Spring Cloud 服务消费方应用 + +为了减少实现步骤,以下引导类将 Dubbo 服务消费以及引导功能合二为一: + +```java +@EnableDiscoveryClient +@EnableAutoConfiguration +@RestController +public class DubboSpringCloudClientBootstrap { + + @Reference + private EchoService echoService; + + @GetMapping("/echo") + public String echo(String message) { + return echoService.echo(message); + } + + public static void main(String[] args) { + SpringApplication.run(DubboSpringCloudClientBootstrap.class); + } +} +``` + +不仅如此,`DubboSpringCloudClientBootstrap` 也作为 REST Endpoint,通过暴露 `/echo` Web 服务,消费 Dubbo `EchoService` 服务。因此, +可通过 `curl` 命令执行 HTTP GET 方法: + +``` +$ curl http://127.0.0.1:8080/echo?message=%E5%B0%8F%E9%A9%AC%E5%93%A5%EF%BC%88mercyblitz%EF%BC%89 +``` + +HTTP 响应为: + +``` +[echo] Hello, 小马哥(mercyblitz) +``` + +以上结果说明应用 `spring-cloud-dubbo-client-sample` 通过消费 Dubbo 服务,返回服务提供方 `spring-cloud-dubbo-server-sample` +运算后的内容。 + +以上操作就一套完整的 Dubbo 服务提供方和消费方的运用,更多的详情请直接参考模块: +- [`spring-cloud-dubbo-server-sample` ](spring-cloud-dubbo-server-sample) +- [`spring-cloud-dubbo-client-sample`](spring-cloud-dubbo-client-sample) + + + + +## 模块说明 + +- [spring-cloud-dubbo-sample-api](spring-cloud-dubbo-sample-api):API 模块,存放 Dubbo 服务接口和模型定义 +- [spring-cloud-dubbo-provider-web-sample](spring-cloud-dubbo-provider-web-sample):Dubbo Spring Cloud 服务提供方示例(Web 应用) +- [spring-cloud-dubbo-provider-sample](spring-cloud-dubbo-provider-sample):Dubbo Spring Cloud 服务提供方示例(非 Web 应用) +- [spring-cloud-dubbo-consumer-sample](spring-cloud-dubbo-consumer-sample):Dubbo Spring Cloud 服务消费方示例 +- [spring-cloud-dubbo-servlet-gateway](spring-cloud-dubbo-servlet-gateway-sample):Dubbo Spring Cloud Servlet 网关简易实现示例 diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml index 91fcf022..63fcd270 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/pom.xml @@ -10,15 +10,20 @@ 4.0.0 + com.alibaba.cloud spring-cloud-alibaba-dubbo-examples + 2.0.1.RELEASE Spring Cloud Alibaba Dubbo Examples pom spring-cloud-dubbo-sample-api + spring-cloud-dubbo-server-sample + spring-cloud-dubbo-client-sample spring-cloud-dubbo-provider-sample spring-cloud-dubbo-consumer-sample spring-cloud-dubbo-provider-web-sample + spring-cloud-dubbo-servlet-gateway-sample \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/pom.xml new file mode 100644 index 00000000..0c7ac519 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/pom.xml @@ -0,0 +1,58 @@ + + + + com.alibaba.cloud + spring-cloud-alibaba-dubbo-examples + 2.0.1.RELEASE + ../pom.xml + + 4.0.0 + + com.alibaba.cloud + spring-cloud-dubbo-client-sample + Spring Cloud Dubbo Client Sample + 2.0.1.RELEASE + + + + + com.alibaba.cloud + spring-cloud-dubbo-sample-api + ${project.version} + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-actuator + + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudClientBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudClientBootstrap.java new file mode 100644 index 00000000..5171d48f --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudClientBootstrap.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.dubbo.bootstrap; + +import com.alibaba.cloud.dubbo.service.EchoService; +import org.apache.dubbo.config.annotation.Reference; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * Dubbo Spring Cloud Client Bootstrap. + */ +@EnableDiscoveryClient +@EnableAutoConfiguration +@RestController +public class DubboSpringCloudClientBootstrap { + + @Reference + private EchoService echoService; + + @GetMapping("/echo") + public String echo(String message) { + return echoService.echo(message); + } + + public static void main(String[] args) { + SpringApplication.run(DubboSpringCloudClientBootstrap.class); + } + +} diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..42e49bcb --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-client-sample/src/main/resources/bootstrap.yaml @@ -0,0 +1,15 @@ +dubbo: + registry: + address: spring-cloud://localhost + cloud: + subscribed-services: spring-cloud-alibaba-dubbo-server + +spring: + application: + name: spring-cloud-alibaba-dubbo-client + main: + allow-bean-definition-overriding: true + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java index 4f571375..000859ca 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudConsumerBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.bootstrap; import java.util.HashMap; @@ -22,7 +23,6 @@ import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.service.RestService; import com.alibaba.cloud.dubbo.service.User; import com.alibaba.cloud.dubbo.service.UserService; - import org.apache.dubbo.config.annotation.Reference; import org.springframework.beans.factory.annotation.Autowired; @@ -48,9 +48,10 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; +import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; /** - * Dubbo Spring Cloud Consumer Bootstrap + * Dubbo Spring Cloud Consumer Bootstrap. */ @EnableDiscoveryClient @EnableAutoConfiguration @@ -80,51 +81,6 @@ public class DubboSpringCloudConsumerBootstrap { @LoadBalanced private RestTemplate restTemplate; - @FeignClient("${provider.application.name}") - public interface FeignRestService { - - @GetMapping(value = "/param") - String param(@RequestParam("param") String param); - - @PostMapping("/params") - public String params(@RequestParam("b") String b, @RequestParam("a") int a); - - @PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_UTF8_VALUE) - User requestBody(@RequestParam("param") String param, - @RequestBody Map data); - - @GetMapping("/headers") - public String headers(@RequestHeader("h2") String header2, - @RequestHeader("h") String header, @RequestParam("v") Integer value); - - @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables(@PathVariable("p2") String path2, - @PathVariable("p1") String path1, @RequestParam("v") String param); - } - - @FeignClient("${provider.application.name}") - @DubboTransported(protocol = "dubbo") - public interface DubboFeignRestService { - - @GetMapping(value = "/param") - String param(@RequestParam("param") String param); - - @PostMapping("/params") - String params(@RequestParam("b") String paramB, @RequestParam("a") int paramA); - - @PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_UTF8_VALUE) - User requestBody(@RequestParam("param") String param, - @RequestBody Map data); - - @GetMapping("/headers") - public String headers(@RequestHeader("h2") String header2, - @RequestParam("v") Integer value, @RequestHeader("h") String header); - - @GetMapping("/path-variables/{p1}/{p2}") - public String pathVariables(@RequestParam("v") String param, - @PathVariable("p2") String path2, @PathVariable("p1") String path1); - } - @Bean public ApplicationRunner userServiceRunner() { return arguments -> { @@ -255,4 +211,52 @@ public class DubboSpringCloudConsumerBootstrap { new SpringApplicationBuilder(DubboSpringCloudConsumerBootstrap.class) .properties("spring.profiles.active=nacos").run(args); } + + @FeignClient("${provider.application.name}") + public interface FeignRestService { + + @GetMapping("/param") + String param(@RequestParam("param") String param); + + @PostMapping("/params") + String params(@RequestParam("b") String b, @RequestParam("a") int a); + + @PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_VALUE) + User requestBody(@RequestParam("param") String param, + @RequestBody Map data); + + @GetMapping("/headers") + String headers(@RequestHeader("h2") String header2, + @RequestHeader("h") String header, @RequestParam("v") Integer value); + + @GetMapping("/path-variables/{p1}/{p2}") + String pathVariables(@PathVariable("p2") String path2, + @PathVariable("p1") String path1, @RequestParam("v") String param); + + } + + @FeignClient("${provider.application.name}") + @DubboTransported(protocol = "dubbo") + public interface DubboFeignRestService { + + @GetMapping("/param") + String param(@RequestParam("param") String param); + + @PostMapping("/params") + String params(@RequestParam("b") String paramB, @RequestParam("a") int paramA); + + @PostMapping(value = "/request/body/map", produces = APPLICATION_JSON_UTF8_VALUE) + User requestBody(@RequestParam("param") String param, + @RequestBody Map data); + + @GetMapping("/headers") + String headers(@RequestHeader("h2") String header2, + @RequestParam("v") Integer value, @RequestHeader("h") String header); + + @GetMapping("/path-variables/{p1}/{p2}") + String pathVariables(@RequestParam("v") String param, + @PathVariable("p2") String path2, @PathVariable("p1") String path1); + + } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml index 7244e451..c46f7a87 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-consumer-sample/src/main/resources/application.yaml @@ -10,6 +10,9 @@ dubbo: # The subscribed services in consumer side subscribed-services: ${provider.application.name} + consumer: + check: false + server: port: 0 diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml index 4b38958d..987800e5 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/pom.xml @@ -99,35 +99,35 @@ netty-all - - org.jboss.resteasy - resteasy-jaxrs - - - - org.jboss.resteasy - resteasy-client - - - - org.jboss.resteasy - resteasy-netty4 - - javax.validation validation-api - - org.jboss.resteasy - resteasy-jackson-provider - + + + + - - org.jboss.resteasy - resteasy-jaxb-provider - + + + + + + + + + + + + + + + + + + + org.hibernate.validator @@ -136,18 +136,6 @@ - - - - org.apache.dubbo - dubbo-bom - ${dubbo.version} - pom - import - - - - diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java index 1424019c..286e2d2b 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudProviderBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.bootstrap; import org.springframework.boot.WebApplicationType; @@ -21,7 +22,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** - * Dubbo Spring Cloud Provider Bootstrap + * Dubbo Spring Cloud Provider Bootstrap. */ @EnableDiscoveryClient @EnableAutoConfiguration @@ -32,4 +33,5 @@ public class DubboSpringCloudProviderBootstrap { .properties("spring.profiles.active=nacos").web(WebApplicationType.NONE) .run(args); } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java index 2a9c30de..bd11c413 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Collection; @@ -22,7 +23,7 @@ import java.util.Map; import org.apache.dubbo.config.annotation.Service; /** - * In-Memory {@link UserService} implementation + * In-Memory {@link UserService} implementation. */ @Service(protocol = "dubbo") public class InMemoryUserService implements UserService { @@ -43,4 +44,5 @@ public class InMemoryUserService implements UserService { public Collection findAll() { return usersRepository.values(); } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/StandardRestService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/StandardRestService.java index 87292db0..a71cc193 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/StandardRestService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-sample/src/main/java/com/alibaba/cloud/dubbo/service/StandardRestService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.HashMap; @@ -37,7 +38,7 @@ import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE; /** - * Default {@link RestService} + * Default {@link RestService}. * * @author Mercy */ @@ -118,4 +119,5 @@ public class StandardRestService implements RestService { map.put("age", user.getAge()); return map; } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java index 55c40c4d..ab456ccc 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudWebProviderBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.bootstrap; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -20,7 +21,7 @@ import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; /** - * Dubbo Spring Cloud Provider Bootstrap + * Dubbo Spring Cloud Provider Bootstrap. */ @EnableDiscoveryClient @EnableAutoConfiguration @@ -30,4 +31,5 @@ public class DubboSpringCloudWebProviderBootstrap { new SpringApplicationBuilder(DubboSpringCloudWebProviderBootstrap.class) .properties("spring.profiles.active=nacos").run(args); } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java index 2a9c30de..bd11c413 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/InMemoryUserService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Collection; @@ -22,7 +23,7 @@ import java.util.Map; import org.apache.dubbo.config.annotation.Service; /** - * In-Memory {@link UserService} implementation + * In-Memory {@link UserService} implementation. */ @Service(protocol = "dubbo") public class InMemoryUserService implements UserService { @@ -43,4 +44,5 @@ public class InMemoryUserService implements UserService { public Collection findAll() { return usersRepository.values(); } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/SpringRestService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/SpringRestService.java index 708c0921..0c867538 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/SpringRestService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/java/com/alibaba/cloud/dubbo/service/SpringRestService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.HashMap; @@ -34,7 +35,7 @@ import org.springframework.web.bind.annotation.RestController; import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; /** - * Spring MVC {@link RestService} + * Spring MVC {@link RestService}. * * @author Mercy */ @@ -45,7 +46,7 @@ public class SpringRestService implements RestService { private Logger logger = LoggerFactory.getLogger(getClass()); @Override - @GetMapping(value = "/param") + @GetMapping("/param") public String param(@RequestParam String param) { log("/param", param); return param; @@ -83,7 +84,8 @@ public class SpringRestService implements RestService { } @Override - @PostMapping(value = "/request/body/map", produces = MediaType.APPLICATION_JSON_UTF8_VALUE) + @PostMapping(value = "/request/body/map", + produces = MediaType.APPLICATION_JSON_UTF8_VALUE) public User requestBodyMap(@RequestBody Map data, @RequestParam("param") String param) { User user = new User(); @@ -94,7 +96,8 @@ public class SpringRestService implements RestService { return user; } - @PostMapping(value = "/request/body/user", consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) + @PostMapping(value = "/request/body/user", + consumes = MediaType.APPLICATION_JSON_UTF8_VALUE) @Override public Map requestBodyUser(@RequestBody User user) { Map map = new HashMap<>(); diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml index 76692fe1..b6858c74 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-provider-web-sample/src/main/resources/application.yaml @@ -5,18 +5,21 @@ dubbo: dubbo: name: dubbo port: -1 - registry: + registries: + new: + address: spring-cloud://localhost +# registry: # The Spring Cloud Dubbo's registry extension - address: spring-cloud://localhost +# address: spring-cloud://localhost # The traditional Dubbo's registry -# address: zookeeper://127.0.0.1:2181 +# address: nacos://127.0.0.1:8848 feign: hystrix: enabled: true server: - port: 8888 + port: 8080 management: endpoints: diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/EchoService.java similarity index 69% rename from spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java rename to spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/EchoService.java index 94946f00..068c72c8 100644 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/EchoService.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,10 +14,13 @@ * limitations under the License. */ -package com.alibaba.alicloud.ans; +package com.alibaba.cloud.dubbo.service; /** - * @author xiaolongzuo + * Echo Service. */ -public class AnsAutoConfiguration { +public interface EchoService { + + String echo(String message); + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/RestService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/RestService.java index d916e473..175b7cb7 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/RestService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/RestService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Map; /** - * Rest Service + * Rest Service. * * @author Mercy */ @@ -37,4 +38,5 @@ public interface RestService { User requestBodyMap(Map data, String param); Map requestBodyUser(User user); + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/User.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/User.java index 5349356c..edbe3f01 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/User.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/User.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.io.Serializable; /** - * User Entity + * User Entity. * * @author Mercy */ @@ -58,4 +59,5 @@ public class User implements Serializable { public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/UserService.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/UserService.java index 1798f5f2..acd875b0 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/UserService.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/service/UserService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Collection; /** - * {@link User} Service + * {@link User} Service. * * @author Mercy */ @@ -29,4 +30,5 @@ public interface UserService { boolean remove(Long userId); Collection findAll(); + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/util/LoggerUtils.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/util/LoggerUtils.java index b09577fc..6e73e634 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/util/LoggerUtils.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-sample-api/src/main/java/com/alibaba/cloud/dubbo/util/LoggerUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.util; import org.apache.dubbo.rpc.RpcContext; @@ -20,7 +21,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * Logger Utilities + * Logger Utilities. */ public abstract class LoggerUtils { @@ -37,4 +38,5 @@ public abstract class LoggerUtils { logger.info(message); } } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/pom.xml new file mode 100644 index 00000000..f3317933 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/pom.xml @@ -0,0 +1,55 @@ + + + + com.alibaba.cloud + spring-cloud-alibaba-dubbo-examples + 2.0.1.RELEASE + ../pom.xml + + + 4.0.0 + + com.alibaba.cloud + spring-cloud-dubbo-server-sample + Spring Cloud Dubbo Server Sample + 2.0.1.RELEASE + + + + + + com.alibaba.cloud + spring-cloud-dubbo-sample-api + ${project.version} + + + + + org.springframework.boot + spring-boot-actuator + + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServerBootstrap.java similarity index 52% rename from spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java rename to spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServerBootstrap.java index 1d674cbe..bd7e1784 100644 --- a/spring-cloud-alibaba-examples/ans-example/ans-consumer-ribbon-example/src/main/java/com/alibaba/cloud/examples/ConsumerApplication.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServerBootstrap.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,30 +14,34 @@ * limitations under the License. */ -package com.alibaba.cloud.examples; +package com.alibaba.cloud.dubbo.bootstrap; + +import com.alibaba.cloud.dubbo.service.EchoService; +import org.apache.dubbo.config.annotation.Service; import org.springframework.boot.SpringApplication; -import org.springframework.boot.autoconfigure.SpringBootApplication; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.context.annotation.Bean; -import org.springframework.web.client.RestTemplate; /** - * @author xiaolongzuo + * Dubbo Spring Cloud Server Bootstrap. */ -@SpringBootApplication @EnableDiscoveryClient -public class ConsumerApplication { - - @Bean - @LoadBalanced - public RestTemplate restTemplate() { - return new RestTemplate(); - } +@EnableAutoConfiguration +public class DubboSpringCloudServerBootstrap { public static void main(String[] args) { - SpringApplication.run(ConsumerApplication.class, args); + SpringApplication.run(DubboSpringCloudServerBootstrap.class); + } + +} + +@Service +class EchoServiceImpl implements EchoService { + + @Override + public String echo(String message) { + return "[echo] Hello, " + message; } } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..394df7ec --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-server-sample/src/main/resources/bootstrap.yaml @@ -0,0 +1,18 @@ +dubbo: + scan: + base-packages: com.alibaba.cloud.dubbo.bootstrap + protocol: + name: dubbo + port: -1 + registry: + address: spring-cloud://localhost + +spring: + application: + name: spring-cloud-alibaba-dubbo-server + main: + allow-bean-definition-overriding: true + cloud: + nacos: + discovery: + server-addr: 127.0.0.1:8848 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/pom.xml similarity index 50% rename from spring-cloud-alibaba-examples/ans-example/ans-provider-example/pom.xml rename to spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/pom.xml index 59cc0196..683f7acc 100644 --- a/spring-cloud-alibaba-examples/ans-example/ans-provider-example/pom.xml +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/pom.xml @@ -1,29 +1,55 @@ + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> com.alibaba.cloud - spring-cloud-alibaba-examples + spring-cloud-alibaba-dubbo-examples 2.0.1.RELEASE - ../../pom.xml + ../pom.xml 4.0.0 - ans-provider-example + + spring-cloud-dubbo-servlet-gateway-sample + Spring Cloud Dubbo Servlet Gateway Sample - - com.alibaba.cloud - spring-cloud-starter-alicloud-ans - + org.springframework.boot spring-boot-starter-web + org.springframework.boot spring-boot-starter-actuator + + + + com.alibaba.cloud + spring-cloud-dubbo-sample-api + ${project.version} + + + + + com.alibaba.cloud + spring-cloud-starter-dubbo + + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + javax.servlet + javax.servlet-api + provided + + @@ -34,4 +60,4 @@ - \ No newline at end of file + diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServletGatewayBootstrap.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServletGatewayBootstrap.java new file mode 100644 index 00000000..face2b41 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/bootstrap/DubboSpringCloudServletGatewayBootstrap.java @@ -0,0 +1,39 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.dubbo.bootstrap; + +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.builder.SpringApplicationBuilder; +import org.springframework.boot.web.servlet.ServletComponentScan; +import org.springframework.cloud.client.discovery.EnableDiscoveryClient; +import org.springframework.cloud.openfeign.EnableFeignClients; + +/** + * Dubbo Spring Cloud Servlet Gateway Bootstrap. + */ +@EnableDiscoveryClient +@EnableAutoConfiguration +@EnableFeignClients +@ServletComponentScan(basePackages = "com.alibaba.cloud.dubbo.gateway") +public class DubboSpringCloudServletGatewayBootstrap { + + public static void main(String[] args) { + new SpringApplicationBuilder(DubboSpringCloudServletGatewayBootstrap.class) + .properties("spring.profiles.active=nacos").run(args); + } + +} diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/gateway/DubboGatewayServlet.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/gateway/DubboGatewayServlet.java new file mode 100644 index 00000000..8fe7f25d --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/java/com/alibaba/cloud/dubbo/gateway/DubboGatewayServlet.java @@ -0,0 +1,212 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.dubbo.gateway; + +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.ServletInputStream; +import javax.servlet.annotation.WebServlet; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import com.alibaba.cloud.dubbo.http.MutableHttpServerRequest; +import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; +import com.alibaba.cloud.dubbo.metadata.RequestMetadata; +import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContext; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import org.apache.dubbo.rpc.service.GenericException; +import org.apache.dubbo.rpc.service.GenericService; + +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpRequest; +import org.springframework.util.AntPathMatcher; +import org.springframework.util.PathMatcher; +import org.springframework.util.StreamUtils; +import org.springframework.web.servlet.HttpServletBean; +import org.springframework.web.util.UriComponents; + +import static org.apache.commons.lang3.StringUtils.substringAfter; +import static org.apache.commons.lang3.StringUtils.substringBetween; +import static org.springframework.web.util.UriComponentsBuilder.fromUriString; + +@WebServlet(urlPatterns = "/dsc/*") +public class DubboGatewayServlet extends HttpServletBean { + + private final DubboServiceMetadataRepository repository; + + private final DubboGenericServiceFactory serviceFactory; + + private final DubboGenericServiceExecutionContextFactory contextFactory; + + private final PathMatcher pathMatcher = new AntPathMatcher(); + + private final Map dubboTranslatedAttributes = new HashMap<>(); + + public DubboGatewayServlet(DubboServiceMetadataRepository repository, + DubboGenericServiceFactory serviceFactory, + DubboGenericServiceExecutionContextFactory contextFactory) { + this.repository = repository; + this.serviceFactory = serviceFactory; + this.contextFactory = contextFactory; + dubboTranslatedAttributes.put("protocol", "dubbo"); + dubboTranslatedAttributes.put("cluster", "failover"); + } + + private String resolveServiceName(HttpServletRequest request) { + + // /g/{app-name}/{rest-path} + String requestURI = request.getRequestURI(); + // /g/ + String servletPath = request.getServletPath(); + + String part = substringAfter(requestURI, servletPath); + + String serviceName = substringBetween(part, "/", "/"); + + return serviceName; + } + + @Override + public void service(HttpServletRequest request, HttpServletResponse response) + throws IOException, ServletException { + + String serviceName = resolveServiceName(request); + + String restPath = substringAfter(request.getRequestURI(), serviceName); + + // 初始化 serviceName 的 REST 请求元数据 + repository.initializeMetadata(serviceName); + // 将 HttpServletRequest 转化为 RequestMetadata + RequestMetadata clientMetadata = buildRequestMetadata(request, restPath); + + DubboRestServiceMetadata dubboRestServiceMetadata = repository.get(serviceName, + clientMetadata); + + if (dubboRestServiceMetadata == null) { + // if DubboServiceMetadata is not found, executes next + throw new ServletException("DubboServiceMetadata can't be found!"); + } + + RestMethodMetadata dubboRestMethodMetadata = dubboRestServiceMetadata + .getRestMethodMetadata(); + + GenericService genericService = serviceFactory.create(dubboRestServiceMetadata, + dubboTranslatedAttributes); + + // TODO: Get the Request Body from HttpServletRequest + byte[] body = getRequestBody(request); + + MutableHttpServerRequest httpServerRequest = new MutableHttpServerRequest( + new HttpRequestAdapter(request), body); + + DubboGenericServiceExecutionContext context = contextFactory + .create(dubboRestMethodMetadata, httpServerRequest); + + Object result = null; + GenericException exception = null; + + try { + result = genericService.$invoke(context.getMethodName(), + context.getParameterTypes(), context.getParameters()); + } + catch (GenericException e) { + exception = e; + } + response.getWriter().println(result); + } + + private byte[] getRequestBody(HttpServletRequest request) throws IOException { + ServletInputStream inputStream = request.getInputStream(); + return StreamUtils.copyToByteArray(inputStream); + } + + private RequestMetadata buildRequestMetadata(HttpServletRequest request, + String restPath) { + UriComponents uriComponents = fromUriString(request.getRequestURI()).build(true); + RequestMetadata requestMetadata = new RequestMetadata(); + requestMetadata.setPath(restPath); + requestMetadata.setMethod(request.getMethod()); + requestMetadata.setParams(getParams(request)); + requestMetadata.setHeaders(getHeaders(request)); + return requestMetadata; + } + + private Map> getHeaders(HttpServletRequest request) { + Map> map = new LinkedHashMap<>(); + Enumeration headerNames = request.getHeaderNames(); + while (headerNames.hasMoreElements()) { + String headerName = headerNames.nextElement(); + Enumeration headerValues = request.getHeaders(headerName); + map.put(headerName, Collections.list(headerValues)); + } + return map; + } + + private Map> getParams(HttpServletRequest request) { + Map> map = new LinkedHashMap<>(); + for (Map.Entry entry : request.getParameterMap().entrySet()) { + map.put(entry.getKey(), Arrays.asList(entry.getValue())); + } + return map; + } + + private final static class HttpRequestAdapter implements HttpRequest { + + private final HttpServletRequest request; + + private HttpRequestAdapter(HttpServletRequest request) { + this.request = request; + } + + @Override + public String getMethodValue() { + return request.getMethod(); + } + + @Override + public URI getURI() { + try { + return new URI(request.getRequestURL().toString() + "?" + + request.getQueryString()); + } + catch (URISyntaxException e) { + e.printStackTrace(); + } + throw new RuntimeException(); + } + + @Override + public HttpHeaders getHeaders() { + return new HttpHeaders(); + } + + } + +} diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/application.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/application.yaml new file mode 100644 index 00000000..263a5699 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/application.yaml @@ -0,0 +1,12 @@ +dubbo: + registry: + # The Spring Cloud Dubbo's registry extension + address: spring-cloud://localhost +# The traditional Dubbo's registry +# address: zookeeper://127.0.0.1:2181 +server: + port: 0 + +provider: + application: + name: spring-cloud-alibaba-dubbo-web-provider \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/bootstrap.yaml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/bootstrap.yaml new file mode 100644 index 00000000..a86acd15 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/spring-cloud-dubbo-servlet-gateway-sample/src/main/resources/bootstrap.yaml @@ -0,0 +1,70 @@ +spring: + application: + name: spring-cloud-alibaba-dubbo-servlet-gateway + main: + allow-bean-definition-overriding: true + + + # default disable all + cloud: + nacos: + discovery: + enabled: false + register-enabled: false + zookeeper: + enabled: false + consul: + enabled: false + +eureka: + client: + enabled: false + +ribbon: + nacos: + enabled: false + +--- +spring: + profiles: nacos + + cloud: + nacos: + discovery: + enabled: true + register-enabled: true + server-addr: 127.0.0.1:8848 + +ribbon: + nacos: + enabled: true + +--- +spring: + profiles: eureka + +eureka: + client: + enabled: true + service-url: + defaultZone: http://127.0.0.1:8761/eureka/ + + +--- +spring: + profiles: zookeeper + cloud: + zookeeper: + enabled: true + connect-string: 127.0.0.1:2181 + + +--- +spring: + profiles: consul + + cloud: + consul: + enabled: true + host: 127.0.0.1 + port: 8500 \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/node-service.js b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/node-service.js new file mode 100644 index 00000000..61e07ab6 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/node-service.js @@ -0,0 +1,26 @@ +var http = require('http'); +var url = require("url"); +var path = require('path'); + +// 创建server +var server = http.createServer(function(req, res) { + // 获得请求的路径 + var pathname = url.parse(req.url).pathname; + res.writeHead(200, { 'Content-Type' : 'application/json; charset=utf-8' }); + // 访问http://localhost:8060/,将会返回{"index":"欢迎来到首页"} + if (pathname === '/') { + res.end(JSON.stringify({ "index" : "欢迎来到首页" })); + } + // 访问http://localhost:8060/health,将会返回{"status":"UP"} + else if (pathname === '/health.json') { + res.end(JSON.stringify({ "status" : "UP" })); + } + // 其他情况返回404 + else { + res.end("404"); + } +}); +// 创建监听,并打印日志 +server.listen(8060, function() { + console.log('listening on localhost:8060'); +}); \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/pom.xml new file mode 100644 index 00000000..640b5458 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/pom.xml @@ -0,0 +1,63 @@ + + + + com.alibaba.cloud + spring-cloud-alibaba-examples + 2.0.1.RELEASE + ../../pom.xml + + 4.0.0 + + spring-cloud-alibaba-sidecar-consul-example + Example demonstrating how to use Spring Cloud Alibaba Sidecar with consul + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sidecar + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + + org.springframework.cloud + spring-cloud-starter-consul-discovery + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + true + + + + + diff --git a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/ScxApplication.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java similarity index 73% rename from spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/ScxApplication.java rename to spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java index fe3d4357..f61c6013 100644 --- a/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/src/main/java/com/alibaba/cloud/examples/ScxApplication.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,19 +14,16 @@ * limitations under the License. */ -package com.alibaba.cloud.examples; +package com.alibaba.cloud.sidecar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * @author xiaolongzuo - */ @SpringBootApplication -public class ScxApplication { +public class DemoApplication { public static void main(String[] args) { - SpringApplication.run(ScxApplication.class, args); + SpringApplication.run(DemoApplication.class, args); } } diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/resources/application.yml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/resources/application.yml new file mode 100644 index 00000000..325fb38a --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-consul-example/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 8070 +spring: + cloud: + gateway: + discovery: + locator: + enabled: true + consul: + host: localhost + port: 8500 + application: + name: node-service +sidecar: + # 异构微服务的IP + ip: 127.0.0.1 + # 异构微服务的端口 + port: 8060 + # 异构微服务的健康检查URL + health-check-url: http://localhost:8060/health.json +management: + endpoint: + health: + show-details: always \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/pom.xml new file mode 100644 index 00000000..21dfffff --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/pom.xml @@ -0,0 +1,62 @@ + + + + com.alibaba.cloud + spring-cloud-alibaba-examples + 2.0.1.RELEASE + ../../pom.xml + + 4.0.0 + + spring-cloud-alibaba-sidecar-nacos-example + Example demonstrating how to use Spring Cloud Alibaba Sidecar with nacos + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter-web + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sidecar + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + io.projectreactor + reactor-core + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + org.apache.maven.plugins + maven-deploy-plugin + ${maven-deploy-plugin.version} + + true + + + + + diff --git a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsApplication.java b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java similarity index 69% rename from spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsApplication.java rename to spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java index e96ffe55..f61c6013 100644 --- a/spring-cloud-alibaba-examples/sms-example/src/main/java/com/alibaba/cloud/examples/SmsApplication.java +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/java/com/alibaba/cloud/sidecar/DemoApplication.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,18 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.cloud.examples; + +package com.alibaba.cloud.sidecar; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; -/** - * - */ @SpringBootApplication -public class SmsApplication { +public class DemoApplication { - public static void main(String[] args) throws Exception { - SpringApplication.run(SmsApplication.class, args); + public static void main(String[] args) { + SpringApplication.run(DemoApplication.class, args); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/resources/application.yml b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/resources/application.yml new file mode 100644 index 00000000..7f059ef3 --- /dev/null +++ b/spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example/src/main/resources/application.yml @@ -0,0 +1,24 @@ +server: + port: 8070 +spring: + cloud: + nacos: + discovery: + server-addr: localhost:8848 + gateway: + discovery: + locator: + enabled: true + application: + name: node-service +sidecar: + # 异构微服务的IP + ip: 127.0.0.1 + # 异构微服务的端口 + port: 8060 + # 异构微服务的健康检查URL + health-check-url: http://localhost:8060/health.json +management: + endpoint: + health: + show-details: always \ No newline at end of file diff --git a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/pom.xml b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/pom.xml index efd3ed57..358eebbb 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/pom.xml +++ b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/pom.xml @@ -3,14 +3,13 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> - com.alibaba.cloud spring-cloud-alibaba-examples + com.alibaba.cloud 2.0.1.RELEASE ../pom.xml 4.0.0 - org.springframework.cloud spring-cloud-bus-rocketmq-example Spring Cloud Bus RocketMQ Example diff --git a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/RocketMQBusApplication.java b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/RocketMQBusApplication.java index 2626481b..91a3ffb3 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/RocketMQBusApplication.java +++ b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/RocketMQBusApplication.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples.rocketmq; import com.fasterxml.jackson.core.JsonProcessingException; @@ -31,7 +32,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * RocketMQ Bus Spring Application + * RocketMQ Bus Spring Application. * * @author Mercy * @since 0.2.1 @@ -64,8 +65,7 @@ public class RocketMQBusApplication { private ObjectMapper objectMapper; /** - * Publish the {@link UserRemoteApplicationEvent} - * + * Publish the {@link UserRemoteApplicationEvent}. * @param name the user name * @param destination the destination * @return If published @@ -82,8 +82,7 @@ public class RocketMQBusApplication { } /** - * Listener on the {@link UserRemoteApplicationEvent} - * + * Listener on the {@link UserRemoteApplicationEvent}. * @param event {@link UserRemoteApplicationEvent} */ @EventListener @@ -98,4 +97,5 @@ public class RocketMQBusApplication { System.out.printf("Server [port : %d] listeners on %s\n", localServerPort, objectMapper.writeValueAsString(event)); } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/User.java b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/User.java index 3805094e..40b3e7d7 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/User.java +++ b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/User.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,10 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples.rocketmq; /** - * User Domain + * User Domain. * * @author Mercy * @since 0.2.1 @@ -47,4 +48,5 @@ public class User { public String toString() { return "User{" + "id=" + id + ", name='" + name + '\'' + '}'; } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/UserRemoteApplicationEvent.java b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/UserRemoteApplicationEvent.java index d5fb804d..e7d56ffc 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/UserRemoteApplicationEvent.java +++ b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/java/com/alibaba/cloud/examples/rocketmq/UserRemoteApplicationEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.examples.rocketmq; import org.springframework.cloud.bus.event.RemoteApplicationEvent; /** - * {@link User} {@link RemoteApplicationEvent} + * {@link User} {@link RemoteApplicationEvent}. * * @author Mercy * @since 0.2.1 @@ -43,4 +44,5 @@ public class UserRemoteApplicationEvent extends RemoteApplicationEvent { public User getUser() { return user; } + } diff --git a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/resources/bootstrap.properties b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/resources/bootstrap.properties index 9e36d301..d2265b76 100644 --- a/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/resources/bootstrap.properties +++ b/spring-cloud-alibaba-examples/spring-cloud-bus-rocketmq-example/src/main/resources/bootstrap.properties @@ -1,4 +1,4 @@ spring.application.name=spring-cloud-bus-rocketmq-example spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876 server.port=8080 -spring.cloud.bus.id=${spring.application.name}:${server.port} \ No newline at end of file +spring.cloud.bus.id=${spring.application.name}:${server.port} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java deleted file mode 100644 index f7937336..00000000 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos; - -import java.util.List; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.cloud.nacos.client.NacosPropertySource; -import com.google.common.collect.Lists; - -/** - * @author xiaojing - * @author pbting - */ -public class NacosPropertySourceRepository { - - private final static ConcurrentHashMap NACOS_PROPERTY_SOURCE_REPOSITORY = new ConcurrentHashMap<>(); - - /** - * @return all nacos properties from application context - */ - public static List getAll() { - return Lists.newArrayList(NACOS_PROPERTY_SOURCE_REPOSITORY.values()); - } - - public static void collectNacosPropertySources( - NacosPropertySource nacosPropertySource) { - NACOS_PROPERTY_SOURCE_REPOSITORY.putIfAbsent(nacosPropertySource.getDataId(), - nacosPropertySource); - } - - public static NacosPropertySource getNacosPropertySource(String dataId) { - - return NACOS_PROPERTY_SOURCE_REPOSITORY.get(dataId); - } -} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java deleted file mode 100644 index c29369d0..00000000 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos.parser; - -import java.io.IOException; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; -import java.util.Properties; - -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; - -import org.springframework.util.StringUtils; - -/** - * @author zkz - */ -public class NacosDataJsonParser extends AbstractNacosDataParser { - protected NacosDataJsonParser() { - super("json"); - } - - @Override - protected Properties doParse(String data) throws IOException { - if (StringUtils.isEmpty(data)) { - return null; - } - Map map = parseJSON2Map(data); - return this.generateProperties(this.reloadMap(map)); - } - - /** - * JSON to Map. - * @param json json data - * @return the map convert by json string - * @throws IOException thrown if there is a problem parsing config. - */ - public static Map parseJSON2Map(String json) throws IOException { - Map map = new HashMap<>(32); - ObjectMapper mapper = new ObjectMapper(); - JsonNode jsonNode = mapper.readTree(json); - if (null == jsonNode) { - return map; - } - parseJsonNode(map, jsonNode, ""); - return map; - } - - private static void parseJsonNode(Map jsonMap, JsonNode jsonNode, - String parentKey) { - Iterator fieldNames = jsonNode.fieldNames(); - while (fieldNames.hasNext()) { - String name = fieldNames.next(); - String fullKey = StringUtils.isEmpty(parentKey) ? name - : parentKey + DOT + name; - JsonNode resultValue = jsonNode.findValue(name); - if (null == resultValue) { - continue; - } - if (resultValue.isArray()) { - Iterator iterator = resultValue.elements(); - while (iterator != null && iterator.hasNext()) { - JsonNode next = iterator.next(); - if (null == next) { - continue; - } - parseJsonNode(jsonMap, next, fullKey); - } - continue; - } - if (resultValue.isObject()) { - parseJsonNode(jsonMap, resultValue, fullKey); - continue; - } - jsonMap.put(fullKey, resultValue.asText()); - } - } - -} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java deleted file mode 100644 index f0599bd2..00000000 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos.parser; - -import java.io.IOException; -import java.io.StringReader; -import java.util.Properties; - -/** - * @author zkz - */ -public class NacosDataPropertiesParser extends AbstractNacosDataParser { - - public NacosDataPropertiesParser() { - super("properties"); - } - - @Override - protected Properties doParse(String data) throws IOException { - Properties properties = new Properties(); - properties.load(new StringReader(data)); - return properties; - } -} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java deleted file mode 100644 index ad50b614..00000000 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos.refresh; - -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.Executor; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; - -import com.alibaba.cloud.nacos.NacosPropertySourceRepository; -import com.alibaba.cloud.nacos.client.NacosPropertySource; -import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.config.listener.Listener; -import com.alibaba.nacos.api.exception.NacosException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.cloud.endpoint.event.RefreshEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ApplicationListener; -import org.springframework.util.StringUtils; - -/** - * On application start up, NacosContextRefresher add nacos listeners to all application - * level dataIds, when there is a change in the data, listeners will refresh - * configurations. - * - * @author juven.xuxb - * @author pbting - */ -public class NacosContextRefresher - implements ApplicationListener, ApplicationContextAware { - - private final static Logger log = LoggerFactory - .getLogger(NacosContextRefresher.class); - - private static final AtomicLong REFRESH_COUNT = new AtomicLong(0); - - private final NacosRefreshProperties refreshProperties; - - private final NacosRefreshHistory refreshHistory; - - private final ConfigService configService; - - private ApplicationContext applicationContext; - - private AtomicBoolean ready = new AtomicBoolean(false); - - private Map listenerMap = new ConcurrentHashMap<>(16); - - public NacosContextRefresher(NacosRefreshProperties refreshProperties, - NacosRefreshHistory refreshHistory, ConfigService configService) { - this.refreshProperties = refreshProperties; - this.refreshHistory = refreshHistory; - this.configService = configService; - } - - @Override - public void onApplicationEvent(ApplicationReadyEvent event) { - // many Spring context - if (this.ready.compareAndSet(false, true)) { - this.registerNacosListenersForApplications(); - } - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - private void registerNacosListenersForApplications() { - if (refreshProperties.isEnabled()) { - for (NacosPropertySource nacosPropertySource : NacosPropertySourceRepository - .getAll()) { - - if (!nacosPropertySource.isRefreshable()) { - continue; - } - - String dataId = nacosPropertySource.getDataId(); - registerNacosListener(nacosPropertySource.getGroup(), dataId); - } - } - } - - private void registerNacosListener(final String group, final String dataId) { - - Listener listener = listenerMap.computeIfAbsent(dataId, i -> new Listener() { - @Override - public void receiveConfigInfo(String configInfo) { - refreshCountIncrement(); - String md5 = ""; - if (!StringUtils.isEmpty(configInfo)) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - md5 = new BigInteger(1, md.digest(configInfo.getBytes("UTF-8"))) - .toString(16); - } - catch (NoSuchAlgorithmException | UnsupportedEncodingException e) { - log.warn("[Nacos] unable to get md5 for dataId: " + dataId, e); - } - } - refreshHistory.add(dataId, md5); - applicationContext.publishEvent( - new RefreshEvent(this, null, "Refresh Nacos config")); - if (log.isDebugEnabled()) { - log.debug("Refresh Nacos config group " + group + ",dataId" + dataId); - } - } - - @Override - public Executor getExecutor() { - return null; - } - }); - - try { - configService.addListener(dataId, group, listener); - } - catch (NacosException e) { - e.printStackTrace(); - } - } - - public static long getRefreshCount() { - return REFRESH_COUNT.get(); - } - - public static void refreshCountIncrement() { - REFRESH_COUNT.incrementAndGet(); - } -} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java deleted file mode 100644 index 0778fb34..00000000 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos.refresh; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; - -public class NacosRefreshHistory { - - private static final int MAX_SIZE = 20; - - private LinkedList records = new LinkedList<>(); - - private ThreadLocal dateFormat = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; - - public void add(String dataId, String md5) { - records.addFirst(new Record(dateFormat.get().format(new Date()), dataId, md5)); - if (records.size() > MAX_SIZE) { - records.removeLast(); - } - } - - public LinkedList getRecords() { - return records; - } -} - -class Record { - - private final String timestamp; - - private final String dataId; - - private final String md5; - - public Record(String timestamp, String dataId, String md5) { - this.timestamp = timestamp; - this.dataId = dataId; - this.md5 = md5; - } - - public String getTimestamp() { - return timestamp; - } - - public String getDataId() { - return dataId; - } - - public String getMd5() { - return md5; - } -} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosNamingManager.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosNamingManager.java deleted file mode 100644 index 8acaf0c7..00000000 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosNamingManager.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos; - -import java.util.Objects; - -import com.alibaba.nacos.api.naming.NamingMaintainService; -import com.alibaba.nacos.api.naming.NamingService; - -import org.springframework.beans.factory.annotation.Autowired; - -/** - * @author liaochuntao - */ -public class NacosNamingManager { - - private static NamingService namingService = null; - - private static NamingMaintainService namingMaintainService = null; - - @Autowired - private NacosDiscoveryProperties discoveryProperties; - - public NamingService getNamingService() { - if (Objects.isNull(namingService)) { - namingService = discoveryProperties.namingServiceInstance(); - } - return namingService; - } - - public NamingMaintainService getNamingMaintainService() { - if (Objects.isNull(namingMaintainService)) { - namingMaintainService = discoveryProperties.namingMaintainServiceInstance(); - } - return namingMaintainService; - } -} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java deleted file mode 100644 index daa50ea7..00000000 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java +++ /dev/null @@ -1,44 +0,0 @@ -package com.alibaba.cloud.nacos; - -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author lyuzb - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressBothLevelTests.TestConfig.class, properties = { - "spring.cloud.nacos.discovery.server-addr=321.321.321.321:8848", - "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT) -public class NacosDiscoveryPropertiesServerAddressBothLevelTests { - - @Autowired - private NacosDiscoveryProperties properties; - - @Test - public void testGetServerAddr() { - assertEquals("NacosDiscoveryProperties server address was wrong", - "321.321.321.321:8848", properties.getServerAddr()); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java deleted file mode 100644 index b77c28d7..00000000 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.alibaba.cloud.nacos; - -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * - * @author lyuzb - * - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosDiscoveryPropertiesServerAddressTopLevelTests.TestConfig.class, properties = { - "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT) - -public class NacosDiscoveryPropertiesServerAddressTopLevelTests { - - @Autowired - private NacosDiscoveryProperties properties; - - @Test - public void testGetServerAddr() { - assertEquals("NacosDiscoveryProperties server address was wrong", - "123.123.123.123:8848", properties.getServerAddr()); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java deleted file mode 100644 index d99a64ed..00000000 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos.registry; - -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", "management.server.port=8888", - "management.server.servlet.context-path=/test-context-path", - "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT) -public class NacosAutoServiceRegistrationManagementPortTests { - - @Autowired - private NacosRegistration registration; - - @Autowired - private NacosAutoServiceRegistration nacosAutoServiceRegistration; - - @Autowired - private NacosDiscoveryProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("NacosRegistration was not created", registration); - assertNotNull("NacosDiscoveryProperties was not created", properties); - assertNotNull("NacosAutoServiceRegistration was not created", - nacosAutoServiceRegistration); - - checkoutNacosDiscoveryManagementData(); - - } - - private void checkoutNacosDiscoveryManagementData() { - assertEquals("NacosDiscoveryProperties management port was wrong", "8888", - properties.getMetadata().get(NacosRegistration.MANAGEMENT_PORT)); - - assertEquals("NacosDiscoveryProperties management context path was wrong", - "/test-context-path", - properties.getMetadata().get(NacosRegistration.MANAGEMENT_CONTEXT_PATH)); - - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/GlobalTransactionAutoConfiguration.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/GlobalTransactionAutoConfiguration.java deleted file mode 100644 index e115f3e0..00000000 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/GlobalTransactionAutoConfiguration.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.seata; - -import io.seata.spring.annotation.GlobalTransactionScanner; - -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.StringUtils; - -/** - * @author xiaojing - */ - -@Configuration -@EnableConfigurationProperties(SeataProperties.class) -public class GlobalTransactionAutoConfiguration { - - private final ApplicationContext applicationContext; - - private final SeataProperties seataProperties; - - public GlobalTransactionAutoConfiguration(ApplicationContext applicationContext, - SeataProperties seataProperties) { - this.applicationContext = applicationContext; - this.seataProperties = seataProperties; - } - - @Bean - public GlobalTransactionScanner globalTransactionScanner() { - - String applicationName = applicationContext.getEnvironment() - .getProperty("spring.application.name"); - - String txServiceGroup = seataProperties.getTxServiceGroup(); - - if (StringUtils.isEmpty(txServiceGroup)) { - txServiceGroup = applicationName + "-seata-service-group"; - seataProperties.setTxServiceGroup(txServiceGroup); - } - - return new GlobalTransactionScanner(applicationName, txServiceGroup); - } -} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/SeataProperties.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/SeataProperties.java deleted file mode 100644 index c9531434..00000000 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/SeataProperties.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.seata; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author xiaojing - */ -@ConfigurationProperties("spring.cloud.alibaba.seata") -public class SeataProperties { - - // todo support config Seata server information - - /** - * Seata tx service group.default is ${spring.application.name}-seata-service-group. - */ - private String txServiceGroup; - - public String getTxServiceGroup() { - return txServiceGroup; - } - - public void setTxServiceGroup(String txServiceGroup) { - this.txServiceGroup = txServiceGroup; - } - -} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java deleted file mode 100644 index 672759c9..00000000 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.seata.feign; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import feign.Client; -import feign.Request; -import feign.Response; -import io.seata.core.context.RootContext; - -import org.springframework.beans.factory.BeanFactory; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; -import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; -import org.springframework.util.StringUtils; - -/** - * @author xiaojing - */ -public class SeataLoadBalancerFeignClient extends LoadBalancerFeignClient { - - private static final int MAP_SIZE = 16; - - private final BeanFactory beanFactory; - - SeataLoadBalancerFeignClient(Client delegate, - CachingSpringLoadBalancerFactory lbClientFactory, - SpringClientFactory clientFactory, BeanFactory beanFactory) { - super(wrap(delegate, beanFactory), lbClientFactory, clientFactory); - this.beanFactory = beanFactory; - } - - @Override - public Response execute(Request request, Request.Options options) throws IOException { - Request modifiedRequest = getModifyRequest(request); - return super.execute(modifiedRequest, options); - } - - private static Client wrap(Client delegate, BeanFactory beanFactory) { - return (Client) new SeataFeignObjectWrapper(beanFactory).wrap(delegate); - } - - private Request getModifyRequest(Request request) { - - String xid = RootContext.getXID(); - - if (StringUtils.isEmpty(xid)) { - return request; - } - - Map> headers = new HashMap<>(MAP_SIZE); - headers.putAll(request.headers()); - - List seataXid = new ArrayList<>(); - seataXid.add(xid); - headers.put(RootContext.KEY_XID, seataXid); - - return Request.create(request.method(), request.url(), headers, request.body(), - request.charset()); - } -} diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesConfigurationTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesConfigurationTests.java deleted file mode 100644 index 903bb377..00000000 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesConfigurationTests.java +++ /dev/null @@ -1,250 +0,0 @@ -/// * -// * Copyright (C) 2018 the original author or authors. -// * -// * Licensed under the Apache License, Version 2.0 (the "License"); -// * you may not use this file except in compliance with the License. -// * You may obtain a copy of the License at -// * -// * http://www.apache.org/licenses/LICENSE-2.0 -// * -// * Unless required by applicable law or agreed to in writing, software -// * distributed under the License is distributed on an "AS IS" BASIS, -// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -// * See the License for the specific language governing permissions and -// * limitations under the License. -// */ -// -// package com.alibaba.cloud.sentinel.datasource; -// -// import static org.junit.Assert.assertEquals; -// import static org.junit.Assert.assertNotNull; -// import static org.junit.Assert.assertNull; -// -// import org.junit.Test; -// import ApolloDataSourceProperties; -// import DataSourcePropertiesConfiguration; -// import FileDataSourceProperties; -// import NacosDataSourceProperties; -// import ZookeeperDataSourceProperties; -// -/// ** -// * @author Jim -// */ -// public class DataSourcePropertiesConfigurationTests { -// -// @Test -// public void testFileAttr() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration(); -// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0, -// dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull("DataSourcePropertiesConfiguration valid properties was not null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// -// FileDataSourceProperties fileDataSourceProperties = buildFileProperties(); -// -// dataSourcePropertiesConfiguration.setFile(fileDataSourceProperties); -// -// assertEquals( -// "DataSourcePropertiesConfiguration valid field size was wrong after set file -/// attribute", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration file properties was null after set file attribute", -// dataSourcePropertiesConfiguration.getFile()); -// assertNotNull( -// "DataSourcePropertiesConfiguration valid properties was null after set file attribute", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testNacosAttr() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration(); -// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0, -// dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull("DataSourcePropertiesConfiguration valid properties was not null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// -// NacosDataSourceProperties nacosDataSourceProperties = buildNacosProperties(); -// -// dataSourcePropertiesConfiguration.setNacos(nacosDataSourceProperties); -// -// assertEquals( -// "DataSourcePropertiesConfiguration valid field size was wrong after set nacos -/// attribute", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration nacos properties was null after set nacos -/// attribute", -// dataSourcePropertiesConfiguration.getNacos()); -// assertNotNull( -// "DataSourcePropertiesConfiguration valid properties was null after set nacos -/// attribute", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testZKAttr() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration(); -// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0, -// dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull("DataSourcePropertiesConfiguration valid properties was not null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// -// ZookeeperDataSourceProperties zookeeperDataSourceProperties = buildZKProperties(); -// -// dataSourcePropertiesConfiguration.setZk(zookeeperDataSourceProperties); -// -// assertEquals( -// "DataSourcePropertiesConfiguration valid field size was wrong after set zk attribute", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration zk properties was null after set zk attribute", -// dataSourcePropertiesConfiguration.getZk()); -// assertNotNull( -// "DataSourcePropertiesConfiguration valid properties was null after set zk attribute", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testApolloAttr() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration(); -// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0, -// dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull("DataSourcePropertiesConfiguration valid properties was not null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// -// ApolloDataSourceProperties apolloDataSourceProperties = buildApolloProperties(); -// -// dataSourcePropertiesConfiguration.setApollo(apolloDataSourceProperties); -// -// assertEquals( -// "DataSourcePropertiesConfiguration valid field size was wrong after set apollo -/// attribute", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration apollo properties was null after set apollo -/// attribute", -// dataSourcePropertiesConfiguration.getApollo()); -// assertNotNull( -// "DataSourcePropertiesConfiguration valid properties was null after set apollo -/// attribute", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testMultiAttr() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration(); -// assertEquals("DataSourcePropertiesConfiguration valid field size was wrong", 0, -// dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull("DataSourcePropertiesConfiguration valid properties was not null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// -// FileDataSourceProperties fileDataSourceProperties = buildFileProperties(); -// NacosDataSourceProperties nacosDataSourceProperties = buildNacosProperties(); -// -// dataSourcePropertiesConfiguration.setFile(fileDataSourceProperties); -// dataSourcePropertiesConfiguration.setNacos(nacosDataSourceProperties); -// -// assertEquals( -// "DataSourcePropertiesConfiguration valid field size was wrong after set file and nacos -/// attribute", -// 2, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNull( -// "DataSourcePropertiesConfiguration valid properties was not null after set file and -/// nacos attribute", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testFileConstructor() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration( -// buildFileProperties()); -// assertEquals( -// "DataSourcePropertiesConfiguration file constructor valid field size was wrong", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration file constructor valid properties was null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testNacosConstructor() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration( -// buildNacosProperties()); -// assertEquals( -// "DataSourcePropertiesConfiguration nacos constructor valid field size was wrong", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration nacos constructor valid properties was null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testApolloConstructor() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration( -// buildApolloProperties()); -// assertEquals( -// "DataSourcePropertiesConfiguration apollo constructor valid field size was wrong", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration apollo constructor valid properties was null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// @Test -// public void testZKConstructor() { -// DataSourcePropertiesConfiguration dataSourcePropertiesConfiguration = new -/// DataSourcePropertiesConfiguration( -// buildZKProperties()); -// assertEquals( -// "DataSourcePropertiesConfiguration zk constructor valid field size was wrong", -// 1, dataSourcePropertiesConfiguration.getValidField().size()); -// assertNotNull( -// "DataSourcePropertiesConfiguration zk constructor valid properties was null", -// dataSourcePropertiesConfiguration.getValidDataSourceProperties()); -// } -// -// private FileDataSourceProperties buildFileProperties() { -// FileDataSourceProperties fileDataSourceProperties = new FileDataSourceProperties(); -// -// fileDataSourceProperties.setFile("/tmp/test.json"); -// fileDataSourceProperties.setBufSize(1024); -// fileDataSourceProperties.setRecommendRefreshMs(2000); -// return fileDataSourceProperties; -// } -// -// private NacosDataSourceProperties buildNacosProperties() { -// NacosDataSourceProperties nacosDataSourceProperties = new NacosDataSourceProperties(); -// nacosDataSourceProperties.setServerAddr("127.0.0.1:8848"); -// nacosDataSourceProperties.setDataId("sentinel"); -// nacosDataSourceProperties.setGroupId("custom-group"); -// return nacosDataSourceProperties; -// } -// -// private ApolloDataSourceProperties buildApolloProperties() { -// ApolloDataSourceProperties apolloDataSourceProperties = new -/// ApolloDataSourceProperties(); -// apolloDataSourceProperties.setFlowRulesKey("test-key"); -// apolloDataSourceProperties.setDefaultFlowRuleValue("dft-val"); -// apolloDataSourceProperties.setNamespaceName("namespace"); -// return apolloDataSourceProperties; -// } -// -// private ZookeeperDataSourceProperties buildZKProperties() { -// ZookeeperDataSourceProperties zookeeperDataSourceProperties = new -/// ZookeeperDataSourceProperties(); -// -// zookeeperDataSourceProperties.setServerAddr("localhost:2181"); -// zookeeperDataSourceProperties.setPath("/path"); -// return zookeeperDataSourceProperties; -// } -// -// } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java deleted file mode 100644 index f973fe5b..00000000 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.sentinel.datasource; - -import com.alibaba.csp.sentinel.slots.block.AbstractRule; -import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; -import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; -import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; -import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; -import com.alibaba.csp.sentinel.slots.system.SystemRule; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -/** - * @author Jim - */ -public class RuleTypeTests { - - @Test - public void testGetByName() { - assertFalse("empty str rule name was not null", - RuleType.getByName("").isPresent()); - assertFalse("test rule name was not null", - RuleType.getByName("test").isPresent()); - assertFalse("param_flow rule name was not null", - RuleType.getByName("param_flow").isPresent()); - assertFalse("param rule name was not null", - RuleType.getByName("param").isPresent()); - assertFalse("FLOW rule name was not null", - RuleType.getByName("FLOW").isPresent()); - assertTrue("flow rule name was null", RuleType.getByName("flow").isPresent()); - assertTrue("degrade rule name was null", - RuleType.getByName("degrade").isPresent()); - assertTrue("param-flow rule name was null", - RuleType.getByName("param-flow").isPresent()); - assertTrue("system rule name was null", RuleType.getByName("system").isPresent()); - assertTrue("authority rule name was null", - RuleType.getByName("authority").isPresent()); - assertEquals("flow rule name was not equals RuleType.FLOW", RuleType.FLOW, - RuleType.getByName("flow").get()); - assertEquals("flow rule name was not equals RuleType.DEGRADE", RuleType.DEGRADE, - RuleType.getByName("degrade").get()); - assertEquals("flow rule name was not equals RuleType.PARAM_FLOW", - RuleType.PARAM_FLOW, RuleType.getByName("param-flow").get()); - assertEquals("flow rule name was not equals RuleType.SYSTEM", RuleType.SYSTEM, - RuleType.getByName("system").get()); - assertEquals("flow rule name was not equals RuleType.AUTHORITY", - RuleType.AUTHORITY, RuleType.getByName("authority").get()); - } - - @Test - public void testGetByClass() { - assertFalse("Object.class type type was not null", - RuleType.getByClass(Object.class).isPresent()); - assertFalse("AbstractRule.class rule type was not null", - RuleType.getByClass(AbstractRule.class).isPresent()); - assertTrue("FlowRule.class rule type was null", - RuleType.getByClass(FlowRule.class).isPresent()); - assertTrue("DegradeRule.class rule type was null", - RuleType.getByClass(DegradeRule.class).isPresent()); - assertTrue("ParamFlowRule.class rule type was null", - RuleType.getByClass(ParamFlowRule.class).isPresent()); - assertTrue("SystemRule.class rule type was null", - RuleType.getByClass(SystemRule.class).isPresent()); - assertTrue("AuthorityRule.class rule type was null", - RuleType.getByClass(AuthorityRule.class).isPresent()); - } - -} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java deleted file mode 100644 index f06ad272..00000000 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.sentinel.gateway; - -/** - * @author Jim - */ -public interface ConfigConstants { - - String APP_TYPE_ZUUL_GATEWAY = "12"; - String APP_TYPE_SCG_GATEWAY = "11"; - - String ZUUl_PREFIX = "spring.cloud.sentinel.zuul"; - - String GATEWAY_PREFIX = "spring.cloud.sentinel.scg"; - - String FALLBACK_MSG_RESPONSE = "response"; - String FALLBACK_REDIRECT = "redirect"; - -} \ No newline at end of file diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java deleted file mode 100644 index 7501ee49..00000000 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.sentinel; - -/** - * @author fangjian - */ -public interface SentinelConstants { - - String PROPERTY_PREFIX = "spring.cloud.sentinel"; - - String BLOCK_TYPE = "block"; - String FALLBACK_TYPE = "fallback"; - String URLCLEANER_TYPE = "urlCleaner"; - - // commercialization - - String FLOW_DATASOURCE_NAME = "edas-flow"; - String DEGRADE_DATASOURCE_NAME = "edas-degrade"; - -} diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java deleted file mode 100644 index 0e792fb1..00000000 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.sentinel; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; - -import javax.annotation.PostConstruct; -import javax.servlet.Filter; - -import com.alibaba.csp.sentinel.adapter.servlet.CommonFilter; -import com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser; -import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; -import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlCleaner; -import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.boot.web.servlet.FilterRegistrationBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaojing - */ -@Configuration -@ConditionalOnWebApplication(type = Type.SERVLET) -@ConditionalOnClass(CommonFilter.class) -@ConditionalOnProperty(name = "spring.cloud.sentinel.enabled", matchIfMissing = true) -@EnableConfigurationProperties(SentinelProperties.class) -public class SentinelWebAutoConfiguration { - - private static final Logger log = LoggerFactory - .getLogger(SentinelWebAutoConfiguration.class); - - @Autowired - private SentinelProperties properties; - - @Autowired - private Optional urlCleanerOptional; - - @Autowired - private Optional urlBlockHandlerOptional; - - @Autowired - private Optional requestOriginParserOptional; - - @PostConstruct - public void init() { - urlBlockHandlerOptional.ifPresent(WebCallbackManager::setUrlBlockHandler); - urlCleanerOptional.ifPresent(WebCallbackManager::setUrlCleaner); - requestOriginParserOptional.ifPresent(WebCallbackManager::setRequestOriginParser); - } - - @Bean - @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true) - public FilterRegistrationBean sentinelFilter() { - FilterRegistrationBean registration = new FilterRegistrationBean<>(); - - SentinelProperties.Filter filterConfig = properties.getFilter(); - - if (filterConfig.getUrlPatterns() == null - || filterConfig.getUrlPatterns().isEmpty()) { - List defaultPatterns = new ArrayList<>(); - defaultPatterns.add("/*"); - filterConfig.setUrlPatterns(defaultPatterns); - } - - registration.addUrlPatterns(filterConfig.getUrlPatterns().toArray(new String[0])); - Filter filter = new CommonFilter(); - registration.setFilter(filter); - registration.setOrder(filterConfig.getOrder()); - registration.addInitParameter("HTTP_METHOD_SPECIFY", - String.valueOf(properties.getHttpMethodSpecify())); - log.info( - "[Sentinel Starter] register Sentinel CommonFilter with urlPatterns: {}.", - filterConfig.getUrlPatterns()); - return registration; - - } - -} \ No newline at end of file diff --git a/spring-cloud-starter-alibaba/pom.xml b/spring-cloud-alibaba-starters/pom.xml similarity index 50% rename from spring-cloud-starter-alibaba/pom.xml rename to spring-cloud-alibaba-starters/pom.xml index f5f015f9..85d7f028 100644 --- a/spring-cloud-starter-alibaba/pom.xml +++ b/spring-cloud-alibaba-starters/pom.xml @@ -1,24 +1,56 @@ 4.0.0 + com.alibaba.cloud spring-cloud-alibaba 2.0.1.RELEASE ../pom.xml - spring-cloud-starter-alibaba + + spring-cloud-alibaba-starters pom Spring Cloud Alibaba Starters Spring Cloud Alibaba Starters + spring-cloud-starter-alibaba-nacos-config spring-cloud-starter-alibaba-nacos-config-server spring-cloud-starter-alibaba-nacos-discovery - spring-cloud-starter-alibaba-sentinel spring-cloud-starter-alibaba-seata spring-cloud-starter-stream-rocketmq spring-cloud-starter-bus-rocketmq spring-cloud-starter-dubbo + spring-cloud-starter-alibaba-sidecar + spring-cloud-circuitbreaker-sentinel + spring-cloud-starter-alibaba-sentinel + spring-cloud-alibaba-sentinel-datasource + spring-cloud-alibaba-sentinel-gateway + + + + + org.jacoco + jacoco-maven-plugin + ${jacoco.version} + + + jacoco-initialize + + prepare-agent + + + + jacoco-site + test + + report + + + + + + \ No newline at end of file diff --git a/spring-cloud-alibaba-sentinel-datasource/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/pom.xml similarity index 76% rename from spring-cloud-alibaba-sentinel-datasource/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/pom.xml index 6bd19c59..5c2d6c0d 100644 --- a/spring-cloud-alibaba-sentinel-datasource/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/pom.xml @@ -4,9 +4,11 @@ com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml + 4.0.0 spring-cloud-alibaba-sentinel-datasource @@ -14,6 +16,31 @@ + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + org.hibernate.validator + hibernate-validator + true + + com.alibaba.csp sentinel-datasource-extension @@ -35,41 +62,37 @@ com.alibaba.csp sentinel-datasource-nacos - provided true com.alibaba.csp sentinel-datasource-zookeeper - provided true com.alibaba.csp sentinel-datasource-apollo - provided true com.alibaba.csp sentinel-datasource-redis - provided true com.fasterxml.jackson.core jackson-databind - provided + true com.fasterxml.jackson.dataformat jackson-dataformat-xml - provided + true @@ -77,28 +100,24 @@ org.springframework.boot spring-boot-configuration-processor - provided true org.springframework.boot spring-boot - provided true org.springframework.boot spring-boot-autoconfigure - provided true org.hibernate.validator hibernate-validator - provided true diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java similarity index 94% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java index 59f74fe9..12229a4e 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,7 +31,7 @@ import org.springframework.util.StringUtils; /** * Enum for {@link AbstractRule} class, using in - * {@link AbstractDataSourceProperties#ruleType} + * {@link AbstractDataSourceProperties#ruleType}. * * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java similarity index 96% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java index fb8d1d38..a3f16fe0 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -28,13 +28,12 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRuleManager; import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; - import com.fasterxml.jackson.annotation.JsonIgnore; import org.springframework.core.env.Environment; /** - * Abstract class Using by {@link DataSourcePropertiesConfiguration} + * Abstract class Using by {@link DataSourcePropertiesConfiguration}. * * @author Jim */ @@ -125,4 +124,5 @@ public class AbstractDataSourceProperties { break; } } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java similarity index 91% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java index 6c392258..7f1f9078 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,7 @@ import com.alibaba.cloud.sentinel.datasource.factorybean.ApolloDataSourceFactory /** * Apollo Properties class Using by {@link DataSourcePropertiesConfiguration} and - * {@link ApolloDataSourceFactoryBean} + * {@link ApolloDataSourceFactoryBean}. * * @author Jim */ @@ -63,4 +63,5 @@ public class ApolloDataSourceProperties extends AbstractDataSourceProperties { public void setDefaultFlowRuleValue(String defaultFlowRuleValue) { this.defaultFlowRuleValue = defaultFlowRuleValue; } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java similarity index 97% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java index 6212af13..2c4f1d7b 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java similarity index 93% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java index 347da650..318523fd 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,7 @@ import org.springframework.util.StringUtils; /** * File Properties class Using by {@link DataSourcePropertiesConfiguration} and - * {@link FileRefreshableDataSourceFactoryBean} + * {@link FileRefreshableDataSourceFactoryBean}. * * @author Jim */ @@ -93,4 +93,5 @@ public class FileDataSourceProperties extends AbstractDataSourceProperties { } } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java similarity index 87% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java index a0a23c7a..e0aa9e74 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,7 @@ import org.springframework.util.StringUtils; /** * Nacos Properties class Using by {@link DataSourcePropertiesConfiguration} and - * {@link NacosDataSourceFactoryBean} + * {@link NacosDataSourceFactoryBean}. * * @author Jim */ @@ -54,11 +54,8 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties { public void preCheck(String dataSourceName) { if (StringUtils.isEmpty(serverAddr)) { serverAddr = this.getEnv().getProperty( - "spring.cloud.sentinel.datasource.nacos.server-addr", ""); - if (StringUtils.isEmpty(serverAddr)) { - throw new IllegalArgumentException( - "NacosDataSource server-addr is empty"); - } + "spring.cloud.sentinel.datasource.nacos.server-addr", + "localhost:8848"); } } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java similarity index 95% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java index 08f3bc20..984b6e2c 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +25,7 @@ import org.springframework.util.StringUtils; /** * Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and - * {@link RedisDataSourceFactoryBean} + * {@link RedisDataSourceFactoryBean}. * * @author lengleng */ @@ -170,4 +170,5 @@ public class RedisDataSourceProperties extends AbstractDataSourceProperties { public void setMasterId(String masterId) { this.masterId = masterId; } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java similarity index 93% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java index ae24a0e6..d0d7b8b8 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,7 @@ import org.springframework.util.StringUtils; /** * Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and - * {@link ZookeeperDataSourceFactoryBean} + * {@link ZookeeperDataSourceFactoryBean}. * * @author Jim */ @@ -83,4 +83,5 @@ public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties public void setDataId(String dataId) { this.dataId = dataId; } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java similarity index 92% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java index 7ffd4ef7..298ce492 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/JsonConverter.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,11 +21,10 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import com.alibaba.csp.sentinel.slots.system.SystemRule; - import com.fasterxml.jackson.databind.ObjectMapper; /** - * Convert sentinel rules for json array Using strict mode to parse json + * Convert sentinel rules for json array Using strict mode to parse json. * * @author Jim * @see FlowRule diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java similarity index 96% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java index d082f792..306dd1a0 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,7 +30,6 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import com.alibaba.csp.sentinel.slots.system.SystemRule; - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.slf4j.Logger; @@ -39,7 +38,7 @@ import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; /** - * Convert sentinel rules for json or xml array Using strict mode to parse json or xml + * Convert sentinel rules for json or xml array Using strict mode to parse json or xml. * * @author Jim * @see FlowRule diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java similarity index 92% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java index 770413c1..91ec1560 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/XmlConverter.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,12 +21,11 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import com.alibaba.csp.sentinel.slots.system.SystemRule; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; /** - * Convert sentinel rules for xml array Using strict mode to parse xml + * Convert sentinel rules for xml array Using strict mode to parse xml. * * @author Jim * @see FlowRule diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java similarity index 94% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java index 758c61b3..4272db5c 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -79,4 +79,5 @@ public class ApolloDataSourceFactoryBean implements FactoryBean public void setSecretKey(String secretKey) { this.secretKey = secretKey; } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java similarity index 97% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java index 4e36e17d..98967fa1 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -186,4 +186,5 @@ public class RedisDataSourceFactoryBean implements FactoryBean public void setMasterId(String masterId) { this.masterId = masterId; } + } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java similarity index 95% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java index 19a6ab1f..d9b51403 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +18,6 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource; - import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.FactoryBean; @@ -97,4 +96,5 @@ public class ZookeeperDataSourceFactoryBean implements FactoryBeanJim @@ -52,21 +50,16 @@ public class DataSourcePropertiesTests { apolloDataSourceProperties.setDefaultFlowRuleValue("dft-val"); apolloDataSourceProperties.setNamespaceName("namespace"); apolloDataSourceProperties.setRuleType(RuleType.DEGRADE); - assertEquals("Apollo flow rule key was wrong", "test-key", - apolloDataSourceProperties.getFlowRulesKey()); - assertEquals("Apollo namespace was wrong", "namespace", - apolloDataSourceProperties.getNamespaceName()); - assertEquals("Apollo default data type was wrong", "json", - apolloDataSourceProperties.getDataType()); - assertEquals("Apollo rule type was wrong", RuleType.DEGRADE, - apolloDataSourceProperties.getRuleType()); - assertEquals("Apollo default flow value was wrong", "dft-val", - apolloDataSourceProperties.getDefaultFlowRuleValue()); - assertEquals("Apollo factory bean was wrong", - ApolloDataSourceFactoryBean.class.getName(), - apolloDataSourceProperties.getFactoryBeanName()); - assertNull("Apollo converterClass was not null", - apolloDataSourceProperties.getConverterClass()); + + assertThat(apolloDataSourceProperties.getFlowRulesKey()).isEqualTo("test-key"); + assertThat(apolloDataSourceProperties.getNamespaceName()).isEqualTo("namespace"); + assertThat(apolloDataSourceProperties.getDataType()).isEqualTo("json"); + assertThat(apolloDataSourceProperties.getRuleType()).isEqualTo(RuleType.DEGRADE); + assertThat(apolloDataSourceProperties.getDefaultFlowRuleValue()) + .isEqualTo("dft-val"); + assertThat(apolloDataSourceProperties.getFactoryBeanName()) + .isEqualTo(ApolloDataSourceFactoryBean.class.getName()); + assertThat(apolloDataSourceProperties.getConverterClass()).isNull(); } @Test @@ -80,21 +73,17 @@ public class DataSourcePropertiesTests { zookeeperDataSourceProperties.setConverterClass("test.ConverterClass"); zookeeperDataSourceProperties.setRuleType(RuleType.AUTHORITY); - assertEquals("ZK serverAddr was wrong", "localhost:2181", - zookeeperDataSourceProperties.getServerAddr()); - assertEquals("ZK groupId was wrong", "groupId", - zookeeperDataSourceProperties.getGroupId()); - assertEquals("ZK dataId was wrong", "dataId", - zookeeperDataSourceProperties.getDataId()); - assertEquals("ZK path was wrong", "/path", - zookeeperDataSourceProperties.getPath()); - assertEquals("ZK factory bean was wrong", - ZookeeperDataSourceFactoryBean.class.getName(), - zookeeperDataSourceProperties.getFactoryBeanName()); - assertEquals("ZK custom converter class was wrong", "test.ConverterClass", - zookeeperDataSourceProperties.getConverterClass()); - assertEquals("ZK rule type was wrong", RuleType.AUTHORITY, - zookeeperDataSourceProperties.getRuleType()); + assertThat(zookeeperDataSourceProperties.getServerAddr()) + .isEqualTo("localhost:2181"); + assertThat(zookeeperDataSourceProperties.getGroupId()).isEqualTo("groupId"); + assertThat(zookeeperDataSourceProperties.getDataId()).isEqualTo("dataId"); + assertThat(zookeeperDataSourceProperties.getPath()).isEqualTo("/path"); + assertThat(zookeeperDataSourceProperties.getFactoryBeanName()) + .isEqualTo(ZookeeperDataSourceFactoryBean.class.getName()); + assertThat(zookeeperDataSourceProperties.getConverterClass()) + .isEqualTo("test.ConverterClass"); + assertThat(zookeeperDataSourceProperties.getRuleType()) + .isEqualTo(RuleType.AUTHORITY); } @Test @@ -104,19 +93,13 @@ public class DataSourcePropertiesTests { fileDataSourceProperties.setFile("/tmp/test.json"); fileDataSourceProperties.setRuleType(RuleType.PARAM_FLOW); - assertEquals("File path was wrong", "/tmp/test.json", - fileDataSourceProperties.getFile()); - assertEquals("File charset was wrong", "utf-8", - fileDataSourceProperties.getCharset()); - assertEquals("File refresh time was wrong", 3000L, - fileDataSourceProperties.getRecommendRefreshMs()); - assertEquals("File buf size was wrong", 1024 * 1024, - fileDataSourceProperties.getBufSize()); - assertEquals("File factory bean was wrong", - FileRefreshableDataSourceFactoryBean.class.getName(), - fileDataSourceProperties.getFactoryBeanName()); - assertEquals("File rule type was wrong", RuleType.PARAM_FLOW, - fileDataSourceProperties.getRuleType()); + assertThat(fileDataSourceProperties.getFile()).isEqualTo("/tmp/test.json"); + assertThat(fileDataSourceProperties.getCharset()).isEqualTo("utf-8"); + assertThat(fileDataSourceProperties.getRecommendRefreshMs()).isEqualTo(3000L); + assertThat(fileDataSourceProperties.getBufSize()).isEqualTo(1024 * 1024); + assertThat(fileDataSourceProperties.getFactoryBeanName()) + .isEqualTo(FileRefreshableDataSourceFactoryBean.class.getName()); + assertThat(fileDataSourceProperties.getRuleType()).isEqualTo(RuleType.PARAM_FLOW); } @Test @@ -128,14 +111,10 @@ public class DataSourcePropertiesTests { fileDataSourceProperties.setRecommendRefreshMs(2000); fileDataSourceProperties.setCharset("ISO8859-1"); - assertEquals("File path was wrong", "/tmp/test.json", - fileDataSourceProperties.getFile()); - assertEquals("File charset was wrong", "ISO8859-1", - fileDataSourceProperties.getCharset()); - assertEquals("File refresh time was wrong", 2000L, - fileDataSourceProperties.getRecommendRefreshMs()); - assertEquals("File buf size was wrong", 1024, - fileDataSourceProperties.getBufSize()); + assertThat(fileDataSourceProperties.getFile()).isEqualTo("/tmp/test.json"); + assertThat(fileDataSourceProperties.getCharset()).isEqualTo("ISO8859-1"); + assertThat(fileDataSourceProperties.getRecommendRefreshMs()).isEqualTo(2000L); + assertThat(fileDataSourceProperties.getBufSize()).isEqualTo(1024); } @Test(expected = RuntimeException.class) @@ -174,8 +153,8 @@ public class DataSourcePropertiesTests { } }); fileDataSourceProperties.postRegister(fileRefreshableDataSource); - assertEquals("DataSourceProperties postRegister error", - fileRefreshableDataSource.loadConfig(), FlowRuleManager.getRules()); + assertThat(FlowRuleManager.getRules()) + .isEqualTo(fileRefreshableDataSource.loadConfig()); } } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java similarity index 73% rename from spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java index 6bb79f75..25bad044 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,6 @@ import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSour import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; @@ -34,8 +33,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.util.ResourceUtils; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim @@ -46,24 +44,18 @@ public class FileRefreshableDataSourceFactoryBeanTests { public void testFile() throws Exception { AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext( TestConfig.class); - assertNotNull("FileRefreshableDataSourceFactoryBean was not created", - annotationConfigApplicationContext.getBean("fileBean")); + assertThat(annotationConfigApplicationContext.getBean("fileBean")).isNotNull(); FileRefreshableDataSource fileRefreshableDataSource = annotationConfigApplicationContext .getBean("fileBean", FileRefreshableDataSource.class); - assertEquals("FileRefreshableDataSourceFactoryBean flow rule size was wrong", 1, - ((List) fileRefreshableDataSource.loadConfig()).size()); + assertThat(((List) fileRefreshableDataSource.loadConfig()).size()) + .isEqualTo(1); FileRefreshableDataSourceFactoryBean factoryBean = annotationConfigApplicationContext .getBean("&fileBean", FileRefreshableDataSourceFactoryBean.class); - assertEquals("FileRefreshableDataSourceFactoryBean buf size was wrong", 1024, - factoryBean.getBufSize()); - assertEquals("FileRefreshableDataSourceFactoryBean charset was wrong", "utf-8", - factoryBean.getCharset()); - assertEquals("FileRefreshableDataSourceFactoryBean recommendRefreshMs was wrong", - 2000, factoryBean.getRecommendRefreshMs()); - assertNotNull("FileRefreshableDataSourceFactoryBean file was null", - factoryBean.getFile()); - assertNotNull("FileRefreshableDataSourceFactoryBean converter was null", - factoryBean.getConverter()); + assertThat(factoryBean.getBufSize()).isEqualTo(1024); + assertThat(factoryBean.getCharset()).isEqualTo("utf-8"); + assertThat(factoryBean.getRecommendRefreshMs()).isEqualTo(2000); + assertThat(factoryBean.getFile()).isNotNull(); + assertThat(factoryBean.getConverter()).isNotNull(); } @Configuration diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java similarity index 60% rename from spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java index abbc2ad1..ca364f30 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,10 +20,9 @@ import com.alibaba.cloud.sentinel.datasource.converter.SentinelConverter; import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource; - import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -35,11 +34,17 @@ import static org.mockito.Mockito.when; public class NacosDataSourceFactoryBeanTests { private String dataId = "sentinel"; + private String groupId = "DEFAULT_GROUP"; + private String serverAddr = "localhost:8848"; + private String accessKey = "ak"; + private String secretKey = "sk"; + private String endpoint = "endpoint"; + private String namespace = "namespace"; @Test @@ -58,18 +63,12 @@ public class NacosDataSourceFactoryBeanTests { doReturn(nacosDataSource).when(factoryBean).getObject(); when(nacosDataSource.readSource()).thenReturn("{}"); - assertEquals("NacosDataSourceFactoryBean getObject was wrong", nacosDataSource, - factoryBean.getObject()); - assertEquals("NacosDataSource read source value was wrong", "{}", - factoryBean.getObject().readSource()); - assertEquals("NacosDataSource converter was wrong", converter, - factoryBean.getConverter()); - assertEquals("NacosDataSourceFactoryBean dataId was wrong", dataId, - factoryBean.getDataId()); - assertEquals("NacosDataSourceFactoryBean groupId was wrong", groupId, - factoryBean.getGroupId()); - assertEquals("NacosDataSourceFactoryBean serverAddr was wrong", serverAddr, - factoryBean.getServerAddr()); + assertThat(factoryBean.getObject()).isEqualTo(nacosDataSource); + assertThat(factoryBean.getObject().readSource()).isEqualTo("{}"); + assertThat(factoryBean.getConverter()).isEqualTo(converter); + assertThat(factoryBean.getDataId()).isEqualTo(dataId); + assertThat(factoryBean.getGroupId()).isEqualTo(groupId); + assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr); } @Test @@ -91,25 +90,15 @@ public class NacosDataSourceFactoryBeanTests { doReturn(nacosDataSource).when(factoryBean).getObject(); when(nacosDataSource.readSource()).thenReturn("{}"); - assertEquals("NacosDataSourceFactoryBean getObject was wrong", nacosDataSource, - factoryBean.getObject()); - assertEquals("NacosDataSource read source value was wrong", "{}", - factoryBean.getObject().readSource()); - assertEquals("NacosDataSource converter was wrong", converter, - factoryBean.getConverter()); - assertEquals("NacosDataSourceFactoryBean dataId was wrong", dataId, - factoryBean.getDataId()); - assertEquals("NacosDataSourceFactoryBean groupId was wrong", groupId, - factoryBean.getGroupId()); - assertEquals("NacosDataSourceFactoryBean namespace was wrong", namespace, - factoryBean.getNamespace()); - assertEquals("NacosDataSourceFactoryBean endpoint was wrong", endpoint, - factoryBean.getEndpoint()); - assertEquals("NacosDataSourceFactoryBean ak was wrong", accessKey, - factoryBean.getAccessKey()); - assertEquals("NacosDataSourceFactoryBean sk was wrong", secretKey, - factoryBean.getSecretKey()); - + assertThat(factoryBean.getObject()).isEqualTo(nacosDataSource); + assertThat(factoryBean.getObject().readSource()).isEqualTo("{}"); + assertThat(factoryBean.getConverter()).isEqualTo(converter); + assertThat(factoryBean.getDataId()).isEqualTo(dataId); + assertThat(factoryBean.getGroupId()).isEqualTo(groupId); + assertThat(factoryBean.getNamespace()).isEqualTo(namespace); + assertThat(factoryBean.getEndpoint()).isEqualTo(endpoint); + assertThat(factoryBean.getAccessKey()).isEqualTo(accessKey); + assertThat(factoryBean.getSecretKey()).isEqualTo(secretKey); } } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java similarity index 58% rename from spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java index 0388c34a..f897d6ed 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,10 +18,9 @@ package com.alibaba.cloud.sentinel.datasource; import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties; import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; - import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim @@ -37,17 +36,12 @@ public class NacosDataSourcePropertiesTests { nacosDataSourceProperties.setGroupId("custom-group"); nacosDataSourceProperties.setDataType("xml"); - assertEquals("Nacos groupId was wrong", "custom-group", - nacosDataSourceProperties.getGroupId()); - assertEquals("Nacos dataId was wrong", "sentinel", - nacosDataSourceProperties.getDataId()); - assertEquals("Nacos default data type was wrong", "xml", - nacosDataSourceProperties.getDataType()); - assertEquals("Nacos rule type was wrong", RuleType.FLOW, - nacosDataSourceProperties.getRuleType()); - assertEquals("Nacos default factory bean was wrong", - NacosDataSourceFactoryBean.class.getName(), - nacosDataSourceProperties.getFactoryBeanName()); + assertThat(nacosDataSourceProperties.getGroupId()).isEqualTo("custom-group"); + assertThat(nacosDataSourceProperties.getDataId()).isEqualTo("sentinel"); + assertThat(nacosDataSourceProperties.getDataType()).isEqualTo("xml"); + assertThat(nacosDataSourceProperties.getRuleType()).isEqualTo(RuleType.FLOW); + assertThat(nacosDataSourceProperties.getFactoryBeanName()) + .isEqualTo(NacosDataSourceFactoryBean.class.getName()); } @Test @@ -59,16 +53,11 @@ public class NacosDataSourcePropertiesTests { nacosDataSourceProperties.setNamespace("namespace"); nacosDataSourceProperties.setRuleType(RuleType.SYSTEM); - assertEquals("Nacos ak was wrong", "ak", - nacosDataSourceProperties.getAccessKey()); - assertEquals("Nacos sk was wrong", "sk", - nacosDataSourceProperties.getSecretKey()); - assertEquals("Nacos endpoint was wrong", "endpoint", - nacosDataSourceProperties.getEndpoint()); - assertEquals("Nacos namespace was wrong", "namespace", - nacosDataSourceProperties.getNamespace()); - assertEquals("Nacos rule type was wrong", RuleType.SYSTEM, - nacosDataSourceProperties.getRuleType()); + assertThat(nacosDataSourceProperties.getAccessKey()).isEqualTo("ak"); + assertThat(nacosDataSourceProperties.getSecretKey()).isEqualTo("sk"); + assertThat(nacosDataSourceProperties.getEndpoint()).isEqualTo("endpoint"); + assertThat(nacosDataSourceProperties.getNamespace()).isEqualTo("namespace"); + assertThat(nacosDataSourceProperties.getRuleType()).isEqualTo(RuleType.SYSTEM); } } diff --git a/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java new file mode 100644 index 00000000..c8a03b88 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/RuleTypeTests.java @@ -0,0 +1,71 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel.datasource; + +import com.alibaba.csp.sentinel.slots.block.AbstractRule; +import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; +import com.alibaba.csp.sentinel.slots.system.SystemRule; +import org.junit.Test; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Jim + */ +public class RuleTypeTests { + + @Test + public void testGetByName() { + assertThat(RuleType.getByName("").isPresent()).isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByName("test").isPresent()).isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByName("param_flow").isPresent()).isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByName("param").isPresent()).isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByName("FLOW").isPresent()).isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByName("flow").isPresent()).isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByName("degrade").isPresent()).isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByName("param-flow").isPresent()).isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByName("system").isPresent()).isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByName("authority").isPresent()).isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByName("flow").get()).isEqualTo(RuleType.FLOW); + assertThat(RuleType.getByName("degrade").get()).isEqualTo(RuleType.DEGRADE); + assertThat(RuleType.getByName("param-flow").get()).isEqualTo(RuleType.PARAM_FLOW); + assertThat(RuleType.getByName("system").get()).isEqualTo(RuleType.SYSTEM); + assertThat(RuleType.getByName("authority").get()).isEqualTo(RuleType.AUTHORITY); + } + + @Test + public void testGetByClass() { + assertThat(RuleType.getByClass(Object.class).isPresent()) + .isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByClass(AbstractRule.class).isPresent()) + .isEqualTo(Boolean.FALSE); + assertThat(RuleType.getByClass(FlowRule.class).isPresent()) + .isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByClass(DegradeRule.class).isPresent()) + .isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByClass(ParamFlowRule.class).isPresent()) + .isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByClass(SystemRule.class).isPresent()) + .isEqualTo(Boolean.TRUE); + assertThat(RuleType.getByClass(AuthorityRule.class).isPresent()) + .isEqualTo(Boolean.TRUE); + } + +} diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java similarity index 51% rename from spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java index e02aded9..1053c367 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,7 +23,6 @@ import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; import org.apache.commons.io.FileUtils; @@ -32,7 +31,7 @@ import org.junit.Test; import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim @@ -48,27 +47,23 @@ public class SentinelConverterTests { JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class); List flowRules = (List) jsonConverter .convert(readFileContent("classpath: flowrule.json")); - assertEquals("json converter flow rule size was wrong", 1, flowRules.size()); - assertEquals("json converter flow rule resource name was wrong", "resource", - flowRules.get(0).getResource()); - assertEquals("json converter flow rule limit app was wrong", "default", - flowRules.get(0).getLimitApp()); - assertEquals("json converter flow rule count was wrong", "1.0", - String.valueOf(flowRules.get(0).getCount())); - assertEquals("json converter flow rule control behavior was wrong", - RuleConstant.CONTROL_BEHAVIOR_DEFAULT, - flowRules.get(0).getControlBehavior()); - assertEquals("json converter flow rule strategy was wrong", - RuleConstant.STRATEGY_DIRECT, flowRules.get(0).getStrategy()); - assertEquals("json converter flow rule grade was wrong", - RuleConstant.FLOW_GRADE_QPS, flowRules.get(0).getGrade()); + + assertThat(flowRules.size()).isEqualTo(1); + assertThat(flowRules.get(0).getResource()).isEqualTo("resource"); + assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default"); + assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0"); + assertThat(flowRules.get(0).getControlBehavior()) + .isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); + assertThat(flowRules.get(0).getStrategy()) + .isEqualTo(RuleConstant.STRATEGY_DIRECT); + assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS); } @Test public void testConverterEmptyContent() { JsonConverter jsonConverter = new JsonConverter(objectMapper, FlowRule.class); List flowRules = (List) jsonConverter.convert(""); - assertEquals("json converter flow rule size was not empty", 0, flowRules.size()); + assertThat(flowRules.size()).isEqualTo(0); } @Test(expected = RuntimeException.class) @@ -88,34 +83,25 @@ public class SentinelConverterTests { XmlConverter jsonConverter = new XmlConverter(xmlMapper, FlowRule.class); List flowRules = (List) jsonConverter .convert(readFileContent("classpath: flowrule.xml")); - assertEquals("xml converter flow rule size was wrong", 2, flowRules.size()); - assertEquals("xml converter flow rule1 resource name was wrong", "resource", - flowRules.get(0).getResource()); - assertEquals("xml converter flow rule2 limit app was wrong", "default", - flowRules.get(0).getLimitApp()); - assertEquals("xml converter flow rule1 count was wrong", "1.0", - String.valueOf(flowRules.get(0).getCount())); - assertEquals("xml converter flow rule1 control behavior was wrong", - RuleConstant.CONTROL_BEHAVIOR_DEFAULT, - flowRules.get(0).getControlBehavior()); - assertEquals("xml converter flow rule1 strategy was wrong", - RuleConstant.STRATEGY_DIRECT, flowRules.get(0).getStrategy()); - assertEquals("xml converter flow rule1 grade was wrong", - RuleConstant.FLOW_GRADE_QPS, flowRules.get(0).getGrade()); - assertEquals("xml converter flow rule2 resource name was wrong", "test", - flowRules.get(1).getResource()); - assertEquals("xml converter flow rule2 limit app was wrong", "default", - flowRules.get(1).getLimitApp()); - assertEquals("xml converter flow rule2 count was wrong", "1.0", - String.valueOf(flowRules.get(1).getCount())); - assertEquals("xml converter flow rule2 control behavior was wrong", - RuleConstant.CONTROL_BEHAVIOR_DEFAULT, - flowRules.get(1).getControlBehavior()); - assertEquals("xml converter flow rule2 strategy was wrong", - RuleConstant.STRATEGY_DIRECT, flowRules.get(1).getStrategy()); - assertEquals("xml converter flow rule2 grade was wrong", - RuleConstant.FLOW_GRADE_QPS, flowRules.get(1).getGrade()); + assertThat(flowRules.size()).isEqualTo(2); + assertThat(flowRules.get(0).getResource()).isEqualTo("resource"); + assertThat(flowRules.get(0).getLimitApp()).isEqualTo("default"); + assertThat(String.valueOf(flowRules.get(0).getCount())).isEqualTo("1.0"); + assertThat(flowRules.get(0).getControlBehavior()) + .isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); + assertThat(flowRules.get(0).getStrategy()) + .isEqualTo(RuleConstant.STRATEGY_DIRECT); + assertThat(flowRules.get(0).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS); + + assertThat(flowRules.get(1).getResource()).isEqualTo("test"); + assertThat(flowRules.get(1).getLimitApp()).isEqualTo("default"); + assertThat(String.valueOf(flowRules.get(1).getCount())).isEqualTo("1.0"); + assertThat(flowRules.get(1).getControlBehavior()) + .isEqualTo(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); + assertThat(flowRules.get(1).getStrategy()) + .isEqualTo(RuleConstant.STRATEGY_DIRECT); + assertThat(flowRules.get(1).getGrade()).isEqualTo(RuleConstant.FLOW_GRADE_QPS); } private String readFileContent(String file) { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java similarity index 63% rename from spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java index 3070cdbb..fb7a23d9 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,10 +20,9 @@ import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.zookeeper.ZookeeperDataSource; - import org.junit.Test; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; @@ -35,7 +34,9 @@ import static org.mockito.Mockito.when; public class ZookeeperDataSourceFactoryBeanTests { private String dataId = "dataId"; + private String groupId = "groupId"; + private String serverAddr = "localhost:2181"; private String path = "/sentinel"; @@ -57,18 +58,12 @@ public class ZookeeperDataSourceFactoryBeanTests { when(zookeeperDataSource.readSource()).thenReturn("{}"); doReturn(zookeeperDataSource).when(factoryBean).getObject(); - assertEquals("ZookeeperDataSource getObject was wrong", zookeeperDataSource, - factoryBean.getObject()); - assertEquals("ZookeeperDataSource read source value was wrong", "{}", - factoryBean.getObject().readSource()); - assertEquals("ZookeeperDataSourceFactoryBean dataId was wrong", dataId, - factoryBean.getDataId()); - assertEquals("ZookeeperDataSourceFactoryBean converter was wrong", converter, - factoryBean.getConverter()); - assertEquals("ZookeeperDataSourceFactoryBean groupId was wrong", groupId, - factoryBean.getGroupId()); - assertEquals("ZookeeperDataSourceFactoryBean serverAddr was wrong", serverAddr, - factoryBean.getServerAddr()); + assertThat(factoryBean.getObject()).isEqualTo(zookeeperDataSource); + assertThat(factoryBean.getObject().readSource()).isEqualTo("{}"); + assertThat(factoryBean.getDataId()).isEqualTo(dataId); + assertThat(factoryBean.getConverter()).isEqualTo(converter); + assertThat(factoryBean.getGroupId()).isEqualTo(groupId); + assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr); } @Test @@ -87,16 +82,11 @@ public class ZookeeperDataSourceFactoryBeanTests { when(zookeeperDataSource.readSource()).thenReturn("{}"); doReturn(zookeeperDataSource).when(factoryBean).getObject(); - assertEquals("ZookeeperDataSource value was wrong", zookeeperDataSource, - factoryBean.getObject()); - assertEquals("ZookeeperDataSource read source value was wrong", "{}", - factoryBean.getObject().readSource()); - assertEquals("ZookeeperDataSourceFactoryBean converter was wrong", converter, - factoryBean.getConverter()); - assertEquals("ZookeeperDataSourceFactoryBean path was wrong", path, - factoryBean.getPath()); - assertEquals("ZookeeperDataSourceFactoryBean serverAddr was wrong", serverAddr, - factoryBean.getServerAddr()); + assertThat(factoryBean.getObject()).isEqualTo(zookeeperDataSource); + assertThat(factoryBean.getObject().readSource()).isEqualTo("{}"); + assertThat(factoryBean.getConverter()).isEqualTo(converter); + assertThat(factoryBean.getPath()).isEqualTo(path); + assertThat(factoryBean.getServerAddr()).isEqualTo(serverAddr); } } diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorcontent.json b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorcontent.json similarity index 100% rename from spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorcontent.json rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorcontent.json diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json similarity index 93% rename from spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json index 7ee3cb68..48c738b6 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule-errorformat.json @@ -6,6 +6,5 @@ "grade": 1, "limitApp": "default", "strategy": 0 - } - == + }== ] diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.json b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.json similarity index 100% rename from spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.json rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.json diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.xml b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.xml similarity index 100% rename from spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.xml rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-datasource/src/test/resources/flowrule.xml diff --git a/spring-cloud-alibaba-sentinel-gateway/README.md b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/README.md similarity index 100% rename from spring-cloud-alibaba-sentinel-gateway/README.md rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/README.md diff --git a/spring-cloud-alibaba-sentinel-gateway/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/pom.xml similarity index 93% rename from spring-cloud-alibaba-sentinel-gateway/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/pom.xml index 2eae3f5e..1bd25c69 100644 --- a/spring-cloud-alibaba-sentinel-gateway/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/pom.xml @@ -4,40 +4,56 @@ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml + 4.0.0 spring-cloud-alibaba-sentinel-gateway Spring Cloud Alibaba Sentinel Gateway + + + + org.springframework.boot + spring-boot-configuration-processor + true + + org.springframework.cloud spring-cloud-starter-netflix-zuul true + com.alibaba.csp sentinel-api-gateway-adapter-common + com.alibaba.csp sentinel-parameter-flow-control + com.alibaba.csp sentinel-zuul-adapter + com.alibaba.csp sentinel-spring-cloud-gateway-adapter + com.alibaba.cloud spring-cloud-alibaba-sentinel-datasource + org.springframework.cloud spring-cloud-starter-gateway @@ -46,14 +62,10 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - provided - - - org.springframework.boot - spring-boot-configuration-processor - provided true + + junit junit diff --git a/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java new file mode 100644 index 00000000..9cf27331 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/ConfigConstants.java @@ -0,0 +1,61 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel.gateway; + +import com.alibaba.cloud.sentinel.gateway.scg.SentinelGatewayProperties; +import com.alibaba.cloud.sentinel.gateway.zuul.SentinelZuulProperties; + +/** + * @author Jim + */ +public final class ConfigConstants { + + /** + * Netflix Zuul type. + */ + public static final String APP_TYPE_ZUUL_GATEWAY = "12"; + + /** + * Spring Cloud Gateway type. + */ + public static final String APP_TYPE_SCG_GATEWAY = "11"; + + /** + * ConfigurationProperties for {@link SentinelZuulProperties}. + */ + public static final String ZUUl_PREFIX = "spring.cloud.sentinel.zuul"; + + /** + * ConfigurationProperties for {@link SentinelGatewayProperties}. + */ + public static final String GATEWAY_PREFIX = "spring.cloud.sentinel.scg"; + + /** + * Response type for Spring Cloud Gateway fallback. + */ + public static final String FALLBACK_MSG_RESPONSE = "response"; + + /** + * Redirect type for Spring Cloud Gateway fallback. + */ + public static final String FALLBACK_REDIRECT = "redirect"; + + private ConfigConstants() { + throw new AssertionError("Must not instantiate constant utility class"); + } + +} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java similarity index 94% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java index 6d9d3a28..e7eed21a 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/FallbackProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,22 +29,26 @@ public class FallbackProperties { * `response`. */ private String mode; + /** * Redirect Url for `redirect` mode. */ private String redirect; + /** * Response Body for `response` mode. */ private String responseBody; + /** * Response Status for `response` mode. */ private Integer responseStatus = HttpStatus.TOO_MANY_REQUESTS.value(); + /** * Content-Type for `response` mode. */ - private String contentType = MediaType.APPLICATION_JSON_UTF8.toString(); + private String contentType = MediaType.APPLICATION_JSON.toString(); public String getMode() { return mode; @@ -90,4 +94,5 @@ public class FallbackProperties { this.contentType = contentType; return this; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java similarity index 97% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java index bc1bf648..c02bb78d 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.sentinel.gateway; import java.util.HashMap; diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java similarity index 99% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java index 2f068b65..d7871c2f 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -29,7 +29,6 @@ import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPathPredicateItem; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateGroupItem; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiPredicateItem; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; - import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.Version; import com.fasterxml.jackson.databind.DeserializationContext; @@ -59,6 +58,7 @@ public class SentinelGatewayAutoConfiguration { static class ApiPredicateItemDeserializer extends StdDeserializer { + private Map> registry = new HashMap>(); ApiPredicateItemDeserializer() { @@ -90,6 +90,7 @@ public class SentinelGatewayAutoConfiguration { } return mapper.readValue(root.toString(), apiPredicateItemClass); } + } @Configuration @@ -122,6 +123,7 @@ public class SentinelGatewayAutoConfiguration { public JsonConverter jsonApiConverter() { return new JsonConverter(objectMapper, ApiDefinition.class); } + } @ConditionalOnClass(XmlMapper.class) @@ -156,6 +158,7 @@ public class SentinelGatewayAutoConfiguration { } } + } } diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java similarity index 96% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java index f3ce2f11..a0d93ce6 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -50,4 +50,5 @@ public class SentinelGatewayProperties { public void setOrder(Integer order) { this.order = order; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java similarity index 87% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java index 1358c415..f5003be3 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -31,10 +31,8 @@ import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.RedirectBlockRequest import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler; import com.alibaba.csp.sentinel.config.SentinelConfig; import com.alibaba.csp.sentinel.util.StringUtil; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import reactor.core.publisher.Mono; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; @@ -51,16 +49,17 @@ import org.springframework.http.MediaType; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.result.view.ViewResolver; -import org.springframework.web.server.ServerWebExchange; import static org.springframework.web.reactive.function.BodyInserters.fromObject; + /** * @author Jim */ @Configuration @ConditionalOnClass(GlobalFilter.class) -@ConditionalOnProperty(prefix = ConfigConstants.GATEWAY_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = ConfigConstants.GATEWAY_PREFIX, name = "enabled", + havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(SentinelGatewayProperties.class) public class SentinelSCGAutoConfiguration { @@ -68,6 +67,7 @@ public class SentinelSCGAutoConfiguration { .getLogger(SentinelSCGAutoConfiguration.class); private final List viewResolvers; + private final ServerCodecConfigurer serverCodecConfigurer; @Autowired @@ -92,8 +92,7 @@ public class SentinelSCGAutoConfiguration { } private void initAppType() { - System.setProperty(SentinelConfig.APP_TYPE, - String.valueOf(ConfigConstants.APP_TYPE_SCG_GATEWAY)); + System.setProperty(SentinelConfig.APP_TYPE, ConfigConstants.APP_TYPE_SCG_GATEWAY); } private void initFallback() { @@ -104,22 +103,16 @@ public class SentinelSCGAutoConfiguration { } if (ConfigConstants.FALLBACK_MSG_RESPONSE.equals(fallbackProperties.getMode())) { if (StringUtil.isNotBlank(fallbackProperties.getResponseBody())) { - GatewayCallbackManager.setBlockHandler(new BlockRequestHandler() { - @Override - public Mono handleRequest(ServerWebExchange exchange, - Throwable t) { - return ServerResponse - .status(fallbackProperties.getResponseStatus()) - .contentType(MediaType - .valueOf(fallbackProperties.getContentType())) - .body(fromObject(fallbackProperties.getResponseBody())); - } - }); + GatewayCallbackManager.setBlockHandler((exchange, t) -> ServerResponse + .status(fallbackProperties.getResponseStatus()) + .contentType( + MediaType.valueOf(fallbackProperties.getContentType())) + .body(fromObject(fallbackProperties.getResponseBody()))); logger.info( "[Sentinel SpringCloudGateway] using AnonymousBlockRequestHandler, responseStatus: " + fallbackProperties.getResponseStatus() + ", responseBody: " - + fallbackProperties.getResponseStatus()); + + fallbackProperties.getResponseBody()); } } String redirectUrl = fallbackProperties.getRedirect(); diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java similarity index 71% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java index 06c2cf83..dd08bd24 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java @@ -1,3 +1,19 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.sentinel.gateway.zuul; import java.util.Map; @@ -5,7 +21,6 @@ import java.util.Map; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.DefaultBlockFallbackProvider; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackManager; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackProvider; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -43,4 +58,5 @@ public class FallBackProviderHandler implements SmartInitializingSingleton { ZuulBlockFallbackManager.registerProvider(new DefaultBlockFallbackProvider()); } } + } diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java similarity index 94% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java index de7eda7d..6b2a2653 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright 1999-2018 Alibaba Group Holding Ltd. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,6 @@ import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFi import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter; import com.alibaba.csp.sentinel.config.SentinelConfig; - import com.netflix.zuul.http.ZuulServlet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,13 +41,14 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * Sentinel Spring Cloud Zuul AutoConfiguration + * Sentinel Spring Cloud Zuul AutoConfiguration. * * @author tiger */ @Configuration @ConditionalOnClass(ZuulServlet.class) -@ConditionalOnProperty(prefix = ConfigConstants.ZUUl_PREFIX, name = "enabled", havingValue = "true", matchIfMissing = true) +@ConditionalOnProperty(prefix = ConfigConstants.ZUUl_PREFIX, name = "enabled", + havingValue = "true", matchIfMissing = true) @EnableConfigurationProperties(SentinelZuulProperties.class) public class SentinelZuulAutoConfiguration { diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java similarity index 93% rename from spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java index e36bc5d6..cd7bade8 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,7 +32,7 @@ import org.springframework.boot.context.properties.NestedConfigurationProperty; public class SentinelZuulProperties { @NestedConfigurationProperty - private SentinelZuulProperties.Order order; + private SentinelZuulProperties.Order order = new SentinelZuulProperties.Order(); public Order getOrder() { return order; @@ -83,6 +83,7 @@ public class SentinelZuulProperties { public void setError(int error) { this.error = error; } + } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-alibaba-sentinel-gateway/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-alibaba-sentinel-gateway/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-alicloud-oss/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/pom.xml similarity index 53% rename from spring-cloud-alicloud-oss/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/pom.xml index 8c028ca9..3f389f8e 100644 --- a/spring-cloud-alicloud-oss/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/pom.xml @@ -4,52 +4,50 @@ com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml + 4.0.0 - spring-cloud-alicloud-oss - Spring Cloud Alibaba Cloud OSS + spring-cloud-circuitbreaker-sentinel + Spring Cloud Circuit Breaker Sentinel - com.alibaba.cloud - spring-cloud-alicloud-context + org.springframework.cloud + spring-cloud-commons - com.aliyun.oss - aliyun-sdk-oss + com.alibaba.csp + sentinel-core + + + + com.alibaba.csp + sentinel-reactor-adapter org.springframework.boot - spring-boot-actuator - provided + spring-boot-starter-web true + + io.projectreactor + reactor-core + true + + + org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - - org.slf4j - slf4j-api - provided - true + spring-boot-starter-webflux + test @@ -59,10 +57,11 @@ - org.mockito - mockito-core + io.projectreactor + reactor-test test + diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreaker.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreaker.java new file mode 100644 index 00000000..37e5a2f6 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreaker.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; + +import com.alibaba.csp.sentinel.EntryType; +import com.alibaba.csp.sentinel.adapter.reactor.EntryConfig; +import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker; +import org.springframework.util.Assert; + +/** + * Sentinel implementation of {@link ReactiveCircuitBreaker}. + * + * @author Eric Zhao + */ +public class ReactiveSentinelCircuitBreaker implements ReactiveCircuitBreaker { + + private final String resourceName; + + private final EntryType entryType; + + private final List rules; + + public ReactiveSentinelCircuitBreaker(String resourceName, EntryType entryType, + List rules) { + Assert.hasText(resourceName, "resourceName cannot be blank"); + Assert.notNull(rules, "rules should not be null"); + this.resourceName = resourceName; + this.entryType = entryType; + this.rules = Collections.unmodifiableList(rules); + + applyToSentinelRuleManager(); + } + + public ReactiveSentinelCircuitBreaker(String resourceName, List rules) { + this(resourceName, EntryType.OUT, rules); + } + + public ReactiveSentinelCircuitBreaker(String resourceName) { + this(resourceName, EntryType.OUT, Collections.emptyList()); + } + + private void applyToSentinelRuleManager() { + if (this.rules == null || this.rules.isEmpty()) { + return; + } + Set ruleSet = new HashSet<>(DegradeRuleManager.getRules()); + for (DegradeRule rule : this.rules) { + if (rule == null) { + continue; + } + rule.setResource(resourceName); + ruleSet.add(rule); + } + DegradeRuleManager.loadRules(new ArrayList<>(ruleSet)); + } + + @Override + public Mono run(Mono toRun, Function> fallback) { + Mono toReturn = toRun.transform(new SentinelReactorTransformer<>( + new EntryConfig(resourceName, entryType))); + if (fallback != null) { + toReturn = toReturn.onErrorResume(fallback); + } + return toReturn; + } + + @Override + public Flux run(Flux toRun, Function> fallback) { + Flux toReturn = toRun.transform(new SentinelReactorTransformer<>( + new EntryConfig(resourceName, entryType))); + if (fallback != null) { + toReturn = toReturn.onErrorResume(fallback); + } + return toReturn; + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerAutoConfiguration.java new file mode 100644 index 00000000..974ad2cf --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerAutoConfiguration.java @@ -0,0 +1,67 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author Eric Zhao + */ +@Configuration +@ConditionalOnClass( + name = { "reactor.core.publisher.Mono", "reactor.core.publisher.Flux" }) +@ConditionalOnProperty(name = "spring.cloud.circuitbreaker.sentinel.enabled", + havingValue = "true", matchIfMissing = true) +public class ReactiveSentinelCircuitBreakerAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(ReactiveCircuitBreakerFactory.class) + public ReactiveCircuitBreakerFactory reactiveSentinelCircuitBreakerFactory() { + return new ReactiveSentinelCircuitBreakerFactory(); + } + + @Configuration + @ConditionalOnClass( + name = { "reactor.core.publisher.Mono", "reactor.core.publisher.Flux" }) + public static class ReactiveSentinelCustomizerConfiguration { + + @Autowired(required = false) + private List> customizers = new ArrayList<>(); + + @Autowired(required = false) + private ReactiveSentinelCircuitBreakerFactory factory; + + @PostConstruct + public void init() { + customizers.forEach(customizer -> customizer.customize(factory)); + } + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerFactory.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerFactory.java new file mode 100644 index 00000000..a56d9b8e --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerFactory.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.function.Function; + +import com.alibaba.cloud.circuitbreaker.sentinel.SentinelConfigBuilder.SentinelCircuitBreakerConfiguration; + +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory; +import org.springframework.util.Assert; + +/** + * Factory for {@link ReactiveSentinelCircuitBreaker}. + * + * @author Eric Zhao + */ +public class ReactiveSentinelCircuitBreakerFactory extends + ReactiveCircuitBreakerFactory { + + private Function defaultConfiguration = id -> new SentinelConfigBuilder() + .resourceName(id).rules(new ArrayList<>()).build(); + + @Override + public ReactiveCircuitBreaker create(String id) { + Assert.hasText(id, "A CircuitBreaker must have an id."); + SentinelConfigBuilder.SentinelCircuitBreakerConfiguration conf = getConfigurations() + .computeIfAbsent(id, defaultConfiguration); + return new ReactiveSentinelCircuitBreaker(id, conf.getEntryType(), + conf.getRules()); + } + + @Override + protected SentinelConfigBuilder configBuilder(String id) { + return new SentinelConfigBuilder(id); + } + + @Override + public void configureDefault( + Function defaultConfiguration) { + this.defaultConfiguration = defaultConfiguration; + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreaker.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreaker.java new file mode 100644 index 00000000..34ef0344 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreaker.java @@ -0,0 +1,114 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.function.Supplier; + +import com.alibaba.csp.sentinel.Entry; +import com.alibaba.csp.sentinel.EntryType; +import com.alibaba.csp.sentinel.SphU; +import com.alibaba.csp.sentinel.Tracer; +import com.alibaba.csp.sentinel.slots.block.BlockException; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; + +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.util.Assert; + +/** + * Sentinel implementation of {@link CircuitBreaker}. + * + * @author Eric Zhao + */ +public class SentinelCircuitBreaker implements CircuitBreaker { + + private final String resourceName; + + private final EntryType entryType; + + private final List rules; + + public SentinelCircuitBreaker(String resourceName, EntryType entryType, + List rules) { + Assert.hasText(resourceName, "resourceName cannot be blank"); + Assert.notNull(rules, "rules should not be null"); + this.resourceName = resourceName; + this.entryType = entryType; + this.rules = Collections.unmodifiableList(rules); + + applyToSentinelRuleManager(); + } + + public SentinelCircuitBreaker(String resourceName, List rules) { + this(resourceName, EntryType.OUT, rules); + } + + public SentinelCircuitBreaker(String resourceName) { + this(resourceName, EntryType.OUT, Collections.emptyList()); + } + + private void applyToSentinelRuleManager() { + if (this.rules == null || this.rules.isEmpty()) { + return; + } + Set ruleSet = new HashSet<>(DegradeRuleManager.getRules()); + for (DegradeRule rule : this.rules) { + if (rule == null) { + continue; + } + rule.setResource(resourceName); + ruleSet.add(rule); + } + DegradeRuleManager.loadRules(new ArrayList<>(ruleSet)); + } + + @Override + public T run(Supplier toRun, Function fallback) { + Entry entry = null; + try { + entry = SphU.entry(resourceName, entryType); + // If the SphU.entry() does not throw `BlockException`, it means that the + // request can pass. + return toRun.get(); + } + catch (BlockException ex) { + // SphU.entry() may throw BlockException which indicates that + // the request was rejected (flow control or circuit breaking triggered). + // So it should not be counted as the business exception. + return fallback.apply(ex); + } + catch (Exception ex) { + // For other kinds of exceptions, we'll trace the exception count via + // Tracer.trace(ex). + Tracer.trace(ex); + return fallback.apply(ex); + } + finally { + // Guarantee the invocation has been completed. + if (entry != null) { + entry.exit(); + } + } + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerAutoConfiguration.java new file mode 100644 index 00000000..d4b37325 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerAutoConfiguration.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.List; + +import javax.annotation.PostConstruct; + +import com.alibaba.csp.sentinel.SphU; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * Auto configuration for {@link SentinelCircuitBreaker}. + * + * @author Eric Zhao + */ +@Configuration +@ConditionalOnClass({ SphU.class }) +@ConditionalOnProperty(name = "spring.cloud.circuitbreaker.sentinel.enabled", + havingValue = "true", matchIfMissing = true) +public class SentinelCircuitBreakerAutoConfiguration { + + @Bean + @ConditionalOnMissingBean(CircuitBreakerFactory.class) + public CircuitBreakerFactory sentinelCircuitBreakerFactory() { + return new SentinelCircuitBreakerFactory(); + } + + @Configuration + public static class SentinelCustomizerConfiguration { + + @Autowired(required = false) + private List> customizers = new ArrayList<>(); + + @Autowired(required = false) + private SentinelCircuitBreakerFactory factory; + + @PostConstruct + public void init() { + customizers.forEach(customizer -> customizer.customize(factory)); + } + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerFactory.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerFactory.java new file mode 100644 index 00000000..692555e4 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerFactory.java @@ -0,0 +1,57 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.function.Function; + +import com.alibaba.cloud.circuitbreaker.sentinel.SentinelConfigBuilder.SentinelCircuitBreakerConfiguration; +import com.alibaba.csp.sentinel.EntryType; + +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.util.Assert; + +/** + * @author Eric Zhao + */ +public class SentinelCircuitBreakerFactory extends + CircuitBreakerFactory { + + private Function defaultConfiguration = id -> new SentinelConfigBuilder() + .resourceName(id).entryType(EntryType.OUT).rules(new ArrayList<>()).build(); + + @Override + public CircuitBreaker create(String id) { + Assert.hasText(id, "A CircuitBreaker must have an id."); + SentinelConfigBuilder.SentinelCircuitBreakerConfiguration conf = getConfigurations() + .computeIfAbsent(id, defaultConfiguration); + return new SentinelCircuitBreaker(id, conf.getEntryType(), conf.getRules()); + } + + @Override + protected SentinelConfigBuilder configBuilder(String id) { + return new SentinelConfigBuilder(id); + } + + @Override + public void configureDefault( + Function defaultConfiguration) { + this.defaultConfiguration = defaultConfiguration; + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelConfigBuilder.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelConfigBuilder.java new file mode 100644 index 00000000..b37b5d35 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelConfigBuilder.java @@ -0,0 +1,112 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +import com.alibaba.csp.sentinel.EntryType; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; + +import org.springframework.cloud.client.circuitbreaker.ConfigBuilder; +import org.springframework.util.Assert; + +/** + * @author Eric Zhao + */ +public class SentinelConfigBuilder implements + ConfigBuilder { + + private String resourceName; + + private EntryType entryType; + + private List rules; + + public SentinelConfigBuilder() { + } + + public SentinelConfigBuilder(String resourceName) { + this.resourceName = resourceName; + } + + public SentinelConfigBuilder resourceName(String resourceName) { + this.resourceName = resourceName; + return this; + } + + public SentinelConfigBuilder entryType(EntryType entryType) { + this.entryType = entryType; + return this; + } + + public SentinelConfigBuilder rules(List rules) { + this.rules = rules; + return this; + } + + @Override + public SentinelCircuitBreakerConfiguration build() { + Assert.hasText(resourceName, "resourceName cannot be empty"); + List rules = Optional.ofNullable(this.rules) + .orElse(new ArrayList<>()); + + EntryType entryType = Optional.ofNullable(this.entryType).orElse(EntryType.OUT); + return new SentinelCircuitBreakerConfiguration() + .setResourceName(this.resourceName).setEntryType(entryType) + .setRules(rules); + } + + public static class SentinelCircuitBreakerConfiguration { + + private String resourceName; + + private EntryType entryType; + + private List rules; + + public String getResourceName() { + return resourceName; + } + + public SentinelCircuitBreakerConfiguration setResourceName(String resourceName) { + this.resourceName = resourceName; + return this; + } + + public EntryType getEntryType() { + return entryType; + } + + public SentinelCircuitBreakerConfiguration setEntryType(EntryType entryType) { + this.entryType = entryType; + return this; + } + + public List getRules() { + return rules; + } + + public SentinelCircuitBreakerConfiguration setRules(List rules) { + this.rules = rules; + return this; + } + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json new file mode 100644 index 00000000..44597a6d --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -0,0 +1,7 @@ +{"properties": [ + { + "name": "spring.cloud.circuitbreaker.sentinel.enabled", + "type": "java.lang.Boolean", + "description": "enable sentinel circuitbreaker or not." + } +]} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..1fdc6769 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/main/resources/META-INF/spring.factories @@ -0,0 +1,3 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ +com.alibaba.cloud.circuitbreaker.sentinel.SentinelCircuitBreakerAutoConfiguration,\ +com.alibaba.cloud.circuitbreaker.sentinel.ReactiveSentinelCircuitBreakerAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerIntegrationTest.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerIntegrationTest.java new file mode 100644 index 00000000..5d2ed989 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerIntegrationTest.java @@ -0,0 +1,209 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.time.Duration; +import java.util.Collections; + +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.web.server.LocalServerPort; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreakerFactory; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Service; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; +import org.springframework.web.reactive.function.client.WebClient; + +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author Ryan Baxter + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT, + classes = ReactiveSentinelCircuitBreakerIntegrationTest.Application.class, + properties = { "spring.cloud.discovery.client.health-indicator.enabled=false" }) +@DirtiesContext +public class ReactiveSentinelCircuitBreakerIntegrationTest { + + @LocalServerPort + private int port = 0; + + @Autowired + private ReactiveSentinelCircuitBreakerIntegrationTest.Application.DemoControllerService service; + + @Before + public void setup() { + service.setPort(port); + } + + @Test + public void test() throws Exception { + StepVerifier.create(service.normal()).expectNext("normal").verifyComplete(); + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + + // Then in the next 5s, the fallback method should be called. + for (int i = 0; i < 5; i++) { + StepVerifier.create(service.slow()).expectNext("fallback").verifyComplete(); + Thread.sleep(1000); + } + + // Recovered. + StepVerifier.create(service.slow()).expectNext("slow").verifyComplete(); + + StepVerifier.create(service.normalFlux()).expectNext("normalflux") + .verifyComplete(); + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + // Then in the next 5s, the fallback method should be called. + for (int i = 0; i < 5; i++) { + StepVerifier.create(service.slowFlux()).expectNext("flux_fallback") + .verifyComplete(); + Thread.sleep(1000); + } + + // Recovered. + StepVerifier.create(service.slowFlux()).expectNext("slowflux").verifyComplete(); + } + + @Configuration + @EnableAutoConfiguration + @RestController + protected static class Application { + + @GetMapping("/slow") + public Mono slow() { + return Mono.just("slow").delayElement(Duration.ofMillis(500)); + } + + @GetMapping("/normal") + public Mono normal() { + return Mono.just("normal"); + } + + @GetMapping("/slow_flux") + public Flux slowFlux() { + return Flux.just("slow", "flux").delayElements(Duration.ofMillis(500)); + } + + @GetMapping("normal_flux") + public Flux normalFlux() { + return Flux.just("normal", "flux"); + } + + @Bean + public Customizer slowCustomizer() { + return factory -> { + factory.configure(builder -> builder + .rules(Collections.singletonList(new DegradeRule("slow_mono") + .setGrade(RuleConstant.DEGRADE_GRADE_RT).setCount(100) + .setTimeWindow(5))), + "slow_mono"); + factory.configure(builder -> builder + .rules(Collections.singletonList(new DegradeRule("slow_flux") + .setGrade(RuleConstant.DEGRADE_GRADE_RT).setCount(100) + .setTimeWindow(5))), + "slow_flux"); + factory.configureDefault(id -> new SentinelConfigBuilder() + .resourceName(id) + .rules(Collections.singletonList(new DegradeRule(id) + .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) + .setCount(0.5).setTimeWindow(10))) + .build()); + }; + } + + @Service + public static class DemoControllerService { + + private int port = 0; + + private ReactiveCircuitBreakerFactory cbFactory; + + DemoControllerService(ReactiveCircuitBreakerFactory cbFactory) { + this.cbFactory = cbFactory; + } + + public Mono slow() { + return WebClient.builder().baseUrl("http://localhost:" + port).build() + .get().uri("/slow").retrieve().bodyToMono(String.class) + .transform(it -> cbFactory.create("slow_mono").run(it, t -> { + t.printStackTrace(); + return Mono.just("fallback"); + })); + } + + public Mono normal() { + return WebClient.builder().baseUrl("http://localhost:" + port).build() + .get().uri("/normal").retrieve().bodyToMono(String.class) + .transform(it -> cbFactory.create("normal_mono").run(it, t -> { + t.printStackTrace(); + return Mono.just("fallback"); + })); + } + + public Flux slowFlux() { + return WebClient.builder().baseUrl("http://localhost:" + port).build() + .get().uri("/slow_flux").retrieve() + .bodyToFlux(new ParameterizedTypeReference() { + }).transform(it -> cbFactory.create("slow_flux").run(it, t -> { + t.printStackTrace(); + return Flux.just("flux_fallback"); + })); + } + + public Flux normalFlux() { + return WebClient.builder().baseUrl("http://localhost:" + port).build() + .get().uri("/normal_flux").retrieve().bodyToFlux(String.class) + .transform(it -> cbFactory.create("normal_flux").run(it, t -> { + t.printStackTrace(); + return Flux.just("flux_fallback"); + })); + } + + public void setPort(int port) { + this.port = port; + } + + } + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerTest.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerTest.java new file mode 100644 index 00000000..59d5bcaf --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/ReactiveSentinelCircuitBreakerTest.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.Arrays; +import java.util.Collections; + +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import org.junit.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; + +import org.springframework.cloud.client.circuitbreaker.ReactiveCircuitBreaker; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Eric Zhao + */ +public class ReactiveSentinelCircuitBreakerTest { + + @Test + public void testCreateWithNullRule() { + String id = "testCreateReactiveCbWithNullRule"; + ReactiveSentinelCircuitBreaker cb = new ReactiveSentinelCircuitBreaker(id, + Collections.singletonList(null)); + assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block()) + .isEqualTo("foobar"); + assertThat(DegradeRuleManager.hasConfig(id)).isFalse(); + } + + @Test + public void runMono() { + ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() + .create("foo"); + assertThat(Mono.just("foobar").transform(it -> cb.run(it)).block()) + .isEqualTo("foobar"); + } + + @Test + public void runMonoWithFallback() { + ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() + .create("foo"); + assertThat(Mono.error(new RuntimeException("boom")) + .transform(it -> cb.run(it, t -> Mono.just("fallback"))).block()) + .isEqualTo("fallback"); + } + + @Test + public void runFlux() { + ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() + .create("foo"); + assertThat(Flux.just("foobar", "hello world").transform(it -> cb.run(it)) + .collectList().block()).isEqualTo(Arrays.asList("foobar", "hello world")); + } + + @Test + public void runFluxWithFallback() { + ReactiveCircuitBreaker cb = new ReactiveSentinelCircuitBreakerFactory() + .create("foo"); + assertThat(Flux.error(new RuntimeException("boom")) + .transform(it -> cb.run(it, t -> Flux.just("fallback"))).collectList() + .block()).isEqualTo(Arrays.asList("fallback")); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerIntegrationTest.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerIntegrationTest.java new file mode 100644 index 00000000..d63abfb5 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerIntegrationTest.java @@ -0,0 +1,155 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.client.TestRestTemplate; +import org.springframework.cloud.client.circuitbreaker.CircuitBreakerFactory; +import org.springframework.cloud.client.circuitbreaker.Customizer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Service; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author Eric Zhao + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = RANDOM_PORT, + classes = SentinelCircuitBreakerIntegrationTest.Application.class, + properties = { "spring.cloud.discovery.client.health-indicator.enabled=false" }) +@DirtiesContext +public class SentinelCircuitBreakerIntegrationTest { + + @Autowired + private Application.DemoControllerService service; + + @Test + public void testSlow() throws Exception { + // The first 5 requests should pass. + assertThat(service.slow()).isEqualTo("slow"); + assertThat(service.slow()).isEqualTo("slow"); + assertThat(service.slow()).isEqualTo("slow"); + assertThat(service.slow()).isEqualTo("slow"); + assertThat(service.slow()).isEqualTo("slow"); + + // Then in the next 10s, the fallback method should be called. + for (int i = 0; i < 10; i++) { + assertThat(service.slow()).isEqualTo("fallback"); + Thread.sleep(1000); + } + + // Recovered. + assertThat(service.slow()).isEqualTo("slow"); + } + + @Test + public void testNormal() { + assertThat(service.normal()).isEqualTo("normal"); + } + + @Before + public void setUp() { + DegradeRuleManager.loadRules(new ArrayList<>()); + } + + @Before + public void tearDown() { + DegradeRuleManager.loadRules(new ArrayList<>()); + } + + @Configuration + @EnableAutoConfiguration + @RestController + protected static class Application { + + @GetMapping("/slow") + public String slow() throws InterruptedException { + Thread.sleep(500); + return "slow"; + } + + @GetMapping("/normal") + public String normal() { + return "normal"; + } + + @Bean + public Customizer slowCustomizer() { + String slowId = "slow"; + List rules = Collections.singletonList( + new DegradeRule(slowId).setGrade(RuleConstant.DEGRADE_GRADE_RT) + .setCount(100).setTimeWindow(10)); + return factory -> { + factory.configure(builder -> builder.rules(rules), slowId); + factory.configureDefault(id -> new SentinelConfigBuilder() + .resourceName(id) + .rules(Collections.singletonList(new DegradeRule(id) + .setGrade(RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) + .setCount(0.5).setTimeWindow(10))) + .build()); + }; + } + + @Service + public static class DemoControllerService { + + private TestRestTemplate rest; + + private CircuitBreakerFactory cbFactory; + + DemoControllerService(TestRestTemplate rest, + CircuitBreakerFactory cbFactory) { + this.rest = rest; + this.cbFactory = cbFactory; + } + + public String slow() { + return cbFactory.create("slow").run( + () -> rest.getForObject("/slow", String.class), t -> "fallback"); + } + + public String normal() { + return cbFactory.create("normal").run( + () -> rest.getForObject("/normal", String.class), + t -> "fallback"); + } + + } + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerTest.java b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerTest.java new file mode 100644 index 00000000..439d15c7 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-circuitbreaker-sentinel/src/test/java/com/alibaba/cloud/circuitbreaker/sentinel/SentinelCircuitBreakerTest.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013-2019 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.circuitbreaker.sentinel; + +import java.util.ArrayList; +import java.util.Collections; + +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; +import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; +import org.junit.After; +import org.junit.Test; + +import org.springframework.cloud.client.circuitbreaker.CircuitBreaker; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author Eric Zhao + */ +public class SentinelCircuitBreakerTest { + + @After + public void tearDown() { + // Clear the rules. + DegradeRuleManager.loadRules(new ArrayList<>()); + } + + @Test + public void testCreateDirectlyThenRun() { + // Create a circuit breaker without any circuit breaking rules. + CircuitBreaker cb = new SentinelCircuitBreaker( + "testSentinelCreateDirectlyThenRunA"); + assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel"); + assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunA")) + .isFalse(); + + CircuitBreaker cb2 = new SentinelCircuitBreaker( + "testSentinelCreateDirectlyThenRunB", + Collections.singletonList( + new DegradeRule("testSentinelCreateDirectlyThenRunB") + .setCount(100).setTimeWindow(10))); + assertThat(cb2.run(() -> "Sentinel")).isEqualTo("Sentinel"); + assertThat(DegradeRuleManager.hasConfig("testSentinelCreateDirectlyThenRunB")) + .isTrue(); + } + + @Test + public void testCreateWithNullRule() { + String id = "testCreateCbWithNullRule"; + CircuitBreaker cb = new SentinelCircuitBreaker(id, + Collections.singletonList(null)); + assertThat(cb.run(() -> "Sentinel")).isEqualTo("Sentinel"); + assertThat(DegradeRuleManager.hasConfig(id)).isFalse(); + } + + @Test + public void testCreateFromFactoryThenRun() { + CircuitBreaker cb = new SentinelCircuitBreakerFactory().create("testSentinelRun"); + assertThat(cb.run(() -> "foobar")).isEqualTo("foobar"); + } + + @Test + public void testRunWithFallback() { + CircuitBreaker cb = new SentinelCircuitBreakerFactory() + .create("testSentinelRunWithFallback"); + assertThat(cb.run(() -> { + throw new RuntimeException("boom"); + }, t -> "fallback")).isEqualTo("fallback"); + } + +} diff --git a/spring-cloud-alibaba-nacos-config-server/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/pom.xml similarity index 78% rename from spring-cloud-alibaba-nacos-config-server/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/pom.xml index 38e58012..78715f61 100644 --- a/spring-cloud-alibaba-nacos-config-server/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/pom.xml @@ -1,20 +1,19 @@ - - + 4.0.0 + com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE ../pom.xml - 4.0.0 - spring-cloud-alibaba-nacos-config-server - Spring Cloud Alibaba Nacos Config Server + spring-cloud-starter-alibaba-nacos-config-server + Spring Cloud Starter Alibaba Nacos Config Server - + com.alibaba.nacos @@ -58,6 +57,10 @@ test + + org.springframework.boot + spring-boot-starter + diff --git a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java similarity index 94% rename from spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java index 618da23c..a1c1b250 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.nacos.config.server; import com.alibaba.cloud.nacos.config.server.environment.NacosEnvironmentRepository; @@ -26,14 +27,14 @@ import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; /** - * Nacos Config Server Auto-Configuration + * Nacos Config Server Auto-Configuration. * * @author Mercy * @since 0.2.0 */ @ConditionalOnClass(EnableConfigServer.class) // If class of @EnableConfigServer is // present in class-path -@ComponentScan(basePackages = { "com.alibaba.nacos.config.server", }) +@ComponentScan(basePackages = { "com.alibaba.nacos.config.server" }) @AutoConfigureBefore(ConfigServerAutoConfiguration.class) @Configuration public class NacosConfigServerAutoConfiguration { diff --git a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java similarity index 96% rename from spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java index 8f5b5310..66fb2dfd 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.nacos.config.server.environment; import java.io.IOException; @@ -31,7 +32,7 @@ import org.springframework.util.StringUtils; import static com.alibaba.nacos.config.server.constant.Constants.DEFAULT_GROUP; /** - * Nacos {@link EnvironmentRepository} + * Nacos {@link EnvironmentRepository}. * * @author Mercy * @since 0.2.0 @@ -87,4 +88,5 @@ public class NacosEnvironmentRepository implements EnvironmentRepository { private static String[] of(String... values) { return values; } + } diff --git a/spring-cloud-alibaba-nacos-config-server/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-alibaba-nacos-config-server/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java similarity index 93% rename from spring-cloud-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java index a1222f39..cba01073 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.nacos.config.server.bootstrap; import org.springframework.boot.ApplicationRunner; @@ -22,7 +23,7 @@ import org.springframework.cloud.config.server.EnableConfigServer; import org.springframework.context.annotation.Bean; /** - * Nacos Config Server Bootstrap + * Nacos Config Server Bootstrap. * * @author Mercy * @since 0.2.0 @@ -43,4 +44,5 @@ public class NacosConfigServerBootstrap { System.out.println("Running..."); }; } + } diff --git a/spring-cloud-alibaba-nacos-config-server/src/test/resources/application.properties b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/resources/application.properties similarity index 50% rename from spring-cloud-alibaba-nacos-config-server/src/test/resources/application.properties rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/resources/application.properties index dcecabe7..7121d631 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/test/resources/application.properties +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config-server/src/test/resources/application.properties @@ -1,2 +1,2 @@ spring.application.name=nacos-config-server -management.endpoints.web.exposure.include=* \ No newline at end of file +management.endpoints.web.exposure.include=* diff --git a/spring-cloud-alibaba-nacos-config/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/pom.xml similarity index 83% rename from spring-cloud-alibaba-nacos-config/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/pom.xml index 47e6520e..0a39bfbb 100644 --- a/spring-cloud-alibaba-nacos-config/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/pom.xml @@ -1,19 +1,61 @@ - + 4.0.0 com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml - 4.0.0 - spring-cloud-alibaba-nacos-config - Spring Cloud Alibaba Nacos Config + spring-cloud-starter-alibaba-nacos-config + Spring Cloud Starter Alibaba Nacos Config + + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + org.springframework.boot + spring-boot-starter + true + + + + com.alibaba.spring + spring-context-support + + com.alibaba.nacos nacos-client @@ -24,61 +66,31 @@ org.springframework.cloud spring-cloud-commons + org.springframework.cloud spring-cloud-context - - - - org.springframework.boot - spring-boot-actuator - provided - true - - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - org.springframework.boot - spring-boot - provided - true - - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - + org.springframework.boot spring-boot-starter-web test + org.springframework.boot spring-boot-starter-test test + org.springframework.cloud spring-cloud-test-support test + org.powermock @@ -86,6 +98,7 @@ 2.0.0 test + org.powermock powermock-api-mockito2 diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java similarity index 76% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java index 400ad2e0..d7cdd36e 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -55,11 +55,19 @@ public class NacosConfigAutoConfiguration { } @Bean - public NacosContextRefresher nacosContextRefresher( - NacosConfigProperties configProperties, - NacosRefreshProperties nacosRefreshProperties, - NacosRefreshHistory refreshHistory) { - return new NacosContextRefresher(nacosRefreshProperties, refreshHistory, - configProperties.configServiceInstance()); + public NacosConfigManager nacosConfigManager( + NacosConfigProperties nacosConfigProperties) { + return new NacosConfigManager(nacosConfigProperties); } + + @Bean + public NacosContextRefresher nacosContextRefresher( + NacosConfigManager nacosConfigManager, + NacosRefreshHistory nacosRefreshHistory) { + // Consider that it is not necessary to be compatible with the previous + // configuration + // and use the new configuration if necessary. + return new NacosContextRefresher(nacosConfigManager, nacosRefreshHistory); + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java similarity index 79% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java index 668e4b75..4e670c60 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,9 +37,16 @@ public class NacosConfigBootstrapConfiguration { } @Bean - public NacosPropertySourceLocator nacosPropertySourceLocator( + @ConditionalOnMissingBean + public NacosConfigManager nacosConfigManager( NacosConfigProperties nacosConfigProperties) { - return new NacosPropertySourceLocator(nacosConfigProperties); + return new NacosConfigManager(nacosConfigProperties); + } + + @Bean + public NacosPropertySourceLocator nacosPropertySourceLocator( + NacosConfigManager nacosConfigManager) { + return new NacosPropertySourceLocator(nacosConfigManager); } } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java new file mode 100644 index 00000000..e27b3e06 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java @@ -0,0 +1,80 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import java.util.Objects; + +import com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureException; +import com.alibaba.nacos.api.NacosFactory; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.exception.NacosException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author zkzlx + */ +public class NacosConfigManager { + + private static final Logger log = LoggerFactory.getLogger(NacosConfigManager.class); + + private static ConfigService service = null; + + private NacosConfigProperties nacosConfigProperties; + + public NacosConfigManager(NacosConfigProperties nacosConfigProperties) { + this.nacosConfigProperties = nacosConfigProperties; + // Compatible with older code in NacosConfigProperties,It will be deleted in the + // future. + createConfigService(nacosConfigProperties); + } + + /** + * Compatible with old design,It will be perfected in the future. + */ + static ConfigService createConfigService( + NacosConfigProperties nacosConfigProperties) { + if (Objects.isNull(service)) { + synchronized (NacosConfigManager.class) { + try { + if (Objects.isNull(service)) { + service = NacosFactory.createConfigService( + nacosConfigProperties.assembleConfigServiceProperties()); + } + } + catch (NacosException e) { + log.error(e.getMessage()); + throw new NacosConnectionFailureException( + nacosConfigProperties.getServerAddr(), e.getMessage(), e); + } + } + } + return service; + } + + public ConfigService getConfigService() { + if (Objects.isNull(service)) { + createConfigService(this.nacosConfigProperties); + } + return service; + } + + public NacosConfigProperties getNacosConfigProperties() { + return nacosConfigProperties; + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java similarity index 54% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java index 1f00c1fa..1eae17f4 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,22 +16,30 @@ package com.alibaba.cloud.nacos; +import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; import java.util.Properties; +import java.util.concurrent.ConcurrentHashMap; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.PostConstruct; -import com.alibaba.cloud.nacos.diagnostics.analyzer.NacosConnectionFailureException; -import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.config.ConfigService; -import com.alibaba.nacos.api.exception.NacosException; - +import com.alibaba.spring.util.PropertySourcesUtils; +import com.fasterxml.jackson.annotation.JsonIgnore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; @@ -66,10 +74,23 @@ public class NacosConfigProperties { */ public static final String PREFIX = "spring.cloud.nacos.config"; + /** + * COMMAS , . + */ + public static final String COMMAS = ","; + + /** + * SEPARATOR , . + */ + public static final String SEPARATOR = "[,]"; + + private static final Pattern PATTERN = Pattern.compile("-(\\w)"); + private static final Logger log = LoggerFactory .getLogger(NacosConfigProperties.class); @Autowired + @JsonIgnore private Environment environment; @PostConstruct @@ -82,18 +103,18 @@ public class NacosConfigProperties { String serverAddr = environment .resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"); if (StringUtils.isEmpty(serverAddr)) { - serverAddr = environment - .resolvePlaceholders("${spring.cloud.nacos.server-addr:}"); + serverAddr = environment.resolvePlaceholders( + "${spring.cloud.nacos.server-addr:localhost:8848}"); } this.setServerAddr(serverAddr); } if (StringUtils.isEmpty(this.getUsername())) { - this.setUsername(environment - .resolvePlaceholders("${spring.cloud.nacos.username:}")); + this.setUsername( + environment.resolvePlaceholders("${spring.cloud.nacos.username:}")); } if (StringUtils.isEmpty(this.getPassword())) { - this.setPassword(environment - .resolvePlaceholders("${spring.cloud.nacos.password:}")); + this.setPassword( + environment.resolvePlaceholders("${spring.cloud.nacos.password:}")); } } @@ -103,12 +124,12 @@ public class NacosConfigProperties { private String serverAddr; /** - * nacos auth username. + * the nacos authentication username. */ private String username; /** - * nacos auth password. + * the nacos authentication password. */ private String password; @@ -198,22 +219,21 @@ public class NacosConfigProperties { private String name; /** - * the dataids for configurable multiple shared configurations , multiple separated by - * commas . + * a set of shared configurations .e.g: + * spring.cloud.nacos.config.shared-configs[0]=xxx . */ - private String sharedDataids; + private List sharedConfigs; /** - * refreshable dataids , multiple separated by commas . + * a set of extensional configurations .e.g: + * spring.cloud.nacos.config.extension-configs[0]=xxx . */ - private String refreshableDataids; + private List extensionConfigs; /** - * a set of extended configurations . + * the master switch for refresh configuration, it default opened(true). */ - private List extConfig; - - private static ConfigService configService; + private boolean refreshEnabled = true; // todo sts support @@ -225,6 +245,22 @@ public class NacosConfigProperties { this.serverAddr = serverAddr; } + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + public String getPrefix() { return prefix; } @@ -349,68 +385,163 @@ public class NacosConfigProperties { return name; } - public String getSharedDataids() { - return sharedDataids; - } - - public void setSharedDataids(String sharedDataids) { - this.sharedDataids = sharedDataids; - } - - public String getRefreshableDataids() { - return refreshableDataids; - } - - public void setRefreshableDataids(String refreshableDataids) { - this.refreshableDataids = refreshableDataids; - } - - public List getExtConfig() { - return extConfig; - } - - public void setExtConfig(List extConfig) { - this.extConfig = extConfig; - } - public void setName(String name) { this.name = name; } - public String getUsername() { - return username; + public Environment getEnvironment() { + return environment; } - public void setUsername(String username) { - this.username = username; + public void setEnvironment(Environment environment) { + this.environment = environment; } - public String getPassword() { - return password; + public List getSharedConfigs() { + return sharedConfigs; } - public void setPassword(String password) { - this.password = password; + public void setSharedConfigs(List sharedConfigs) { + this.sharedConfigs = sharedConfigs; + } + + public List getExtensionConfigs() { + return extensionConfigs; + } + + public void setExtensionConfigs(List extensionConfigs) { + this.extensionConfigs = extensionConfigs; + } + + public boolean isRefreshEnabled() { + return refreshEnabled; + } + + public void setRefreshEnabled(boolean refreshEnabled) { + this.refreshEnabled = refreshEnabled; } /** - * @return ConfigService + * recommend to use {@link NacosConfigProperties#sharedConfigs} . + * @return string */ - public ConfigService configServiceInstance() { - if (null == configService) { - try { - configService = NacosFactory - .createConfigService(getConfigServiceProperties()); - } - catch (NacosException e) { - throw new NacosConnectionFailureException(this.getServerAddr(), - e.getMessage(), e); - } - } - return configService; + @Deprecated + @DeprecatedConfigurationProperty( + reason = "replaced to NacosConfigProperties#sharedConfigs and not use it at the same time.", + replacement = PREFIX + ".shared-configs[x]") + public String getSharedDataids() { + return null == getSharedConfigs() ? null : getSharedConfigs().stream() + .map(Config::getDataId).collect(Collectors.joining(COMMAS)); } + /** + * recommend to use {@link NacosConfigProperties#sharedConfigs} and not use it at the + * same time . + * @param sharedDataids the dataids for configurable multiple shared configurations , + * multiple separated by commas . + */ + @Deprecated + public void setSharedDataids(String sharedDataids) { + if (null != sharedDataids && sharedDataids.trim().length() > 0) { + List list = new ArrayList<>(); + Stream.of(sharedDataids.split(SEPARATOR)) + .forEach(dataId -> list.add(new Config(dataId.trim()))); + this.compatibleSharedConfigs(list); + } + } + + /** + * Not providing support,the need to refresh is specified by the respective refresh + * configuration and not use it at the same time . + * @return string + */ + @Deprecated + @DeprecatedConfigurationProperty( + reason = "replaced to NacosConfigProperties#sharedConfigs and not use it at the same time.", + replacement = PREFIX + ".shared-configs[x].refresh") + public String getRefreshableDataids() { + return null == getSharedConfigs() ? null + : getSharedConfigs().stream().filter(Config::isRefresh) + .map(Config::getDataId).collect(Collectors.joining(COMMAS)); + } + + /** + * Not providing support,the need to refresh is specified by the respective refresh + * configuration and not use it at the same time . + * @param refreshableDataids refreshable dataids ,multiple separated by commas . + */ + @Deprecated + public void setRefreshableDataids(String refreshableDataids) { + if (null != refreshableDataids && refreshableDataids.trim().length() > 0) { + List list = new ArrayList<>(); + Stream.of(refreshableDataids.split(SEPARATOR)).forEach( + dataId -> list.add(new Config(dataId.trim()).setRefresh(true))); + this.compatibleSharedConfigs(list); + } + } + + private void compatibleSharedConfigs(List configList) { + if (null != this.getSharedConfigs()) { + configList.addAll(this.getSharedConfigs()); + } + List result = new ArrayList<>(); + configList.stream() + .collect(Collectors.groupingBy(cfg -> (cfg.getGroup() + cfg.getDataId()), + () -> new ConcurrentHashMap<>(new LinkedHashMap<>()), + Collectors.toList())) + .forEach((key, list) -> { + list.stream() + .reduce((a, b) -> new Config(a.getDataId(), a.getGroup(), + a.isRefresh() || (b != null && b.isRefresh()))) + .ifPresent(result::add); + }); + this.setSharedConfigs(result); + } + + /** + * recommend to use + * {@link com.alibaba.cloud.nacos.NacosConfigProperties#extensionConfigs} and not use + * it at the same time . + * @return extensionConfigs + */ + @Deprecated + @DeprecatedConfigurationProperty( + reason = "replaced to NacosConfigProperties#extensionConfigs and not use it at the same time .", + replacement = PREFIX + ".extension-configs[x]") + public List getExtConfig() { + return this.getExtensionConfigs(); + } + + @Deprecated + public void setExtConfig(List extConfig) { + this.setExtensionConfigs(extConfig); + } + + /** + * recommend to use {@link NacosConfigManager#getConfigService()}. + * @return ConfigService + */ + @Deprecated + public ConfigService configServiceInstance() { + // The following code will be migrated + return NacosConfigManager.createConfigService(this); + } + + /** + * recommend to use {@link NacosConfigProperties#assembleConfigServiceProperties()}. + * @return ConfigServiceProperties + */ + @Deprecated public Properties getConfigServiceProperties() { + return this.assembleConfigServiceProperties(); + } + + /** + * assemble properties for configService. (cause by rename : Remove the interference + * of auto prompts when writing,because autocue is based on get method. + * @return properties + */ + public Properties assembleConfigServiceProperties() { Properties properties = new Properties(); properties.put(SERVER_ADDR, Objects.toString(this.serverAddr, "")); properties.put(USERNAME, Objects.toString(this.username, "")); @@ -435,20 +566,43 @@ public class NacosConfigProperties { else { properties.put(ENDPOINT, endpoint); } + + enrichNacosConfigProperties(properties); return properties; } + private void enrichNacosConfigProperties(Properties nacosConfigProperties) { + Map properties = PropertySourcesUtils + .getSubProperties((ConfigurableEnvironment) environment, PREFIX); + properties.forEach((k, v) -> nacosConfigProperties.putIfAbsent(resolveKey(k), + String.valueOf(v))); + } + + private String resolveKey(String key) { + Matcher matcher = PATTERN.matcher(key); + StringBuffer sb = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); + } + matcher.appendTail(sb); + return sb.toString(); + } + @Override public String toString() { return "NacosConfigProperties{" + "serverAddr='" + serverAddr + '\'' + ", encode='" + encode + '\'' + ", group='" + group + '\'' + ", prefix='" + prefix + '\'' + ", fileExtension='" + fileExtension + '\'' - + ", timeout=" + timeout + ", endpoint='" + endpoint + '\'' - + ", namespace='" + namespace + '\'' + ", accessKey='" + accessKey + '\'' - + ", secretKey='" + secretKey + '\'' + ", contextPath='" + contextPath - + '\'' + ", clusterName='" + clusterName + '\'' + ", name='" + name + '\'' - + ", sharedDataids='" + sharedDataids + '\'' + ", refreshableDataids='" - + refreshableDataids + '\'' + ", extConfig=" + extConfig + '}'; + + ", timeout=" + timeout + ", maxRetry='" + maxRetry + '\'' + + ", configLongPollTimeout='" + configLongPollTimeout + '\'' + + ", configRetryTime='" + configRetryTime + '\'' + + ", enableRemoteSyncConfig=" + enableRemoteSyncConfig + ", endpoint='" + + endpoint + '\'' + ", namespace='" + namespace + '\'' + ", accessKey='" + + accessKey + '\'' + ", secretKey='" + secretKey + '\'' + + ", contextPath='" + contextPath + '\'' + ", clusterName='" + clusterName + + '\'' + ", name='" + name + '\'' + '\'' + ", shares=" + sharedConfigs + + ", extensions=" + extensionConfigs + ", refreshEnabled=" + + refreshEnabled + '}'; } public static class Config { @@ -468,28 +622,77 @@ public class NacosConfigProperties { */ private boolean refresh = false; + public Config() { + } + + public Config(String dataId) { + this.dataId = dataId; + } + + public Config(String dataId, String group) { + this(dataId); + this.group = group; + } + + public Config(String dataId, boolean refresh) { + this(dataId); + this.refresh = refresh; + } + + public Config(String dataId, String group, boolean refresh) { + this(dataId, group); + this.refresh = refresh; + } + public String getDataId() { return dataId; } - public void setDataId(String dataId) { + public Config setDataId(String dataId) { this.dataId = dataId; + return this; } public String getGroup() { return group; } - public void setGroup(String group) { + public Config setGroup(String group) { this.group = group; + return this; } public boolean isRefresh() { return refresh; } - public void setRefresh(boolean refresh) { + public Config setRefresh(boolean refresh) { this.refresh = refresh; + return this; + } + + @Override + public String toString() { + return "Config{" + "dataId='" + dataId + '\'' + ", group='" + group + '\'' + + ", refresh=" + refresh + '}'; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Config config = (Config) o; + return refresh == config.refresh && Objects.equals(dataId, config.dataId) + && Objects.equals(group, config.group); + } + + @Override + public int hashCode() { + return Objects.hash(dataId, group, refresh); } } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java new file mode 100644 index 00000000..ac391bad --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosPropertySourceRepository.java @@ -0,0 +1,83 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.ConcurrentHashMap; + +import com.alibaba.cloud.nacos.client.NacosPropertySource; + +/** + * @author xiaojing + * @author pbting + */ +public final class NacosPropertySourceRepository { + + private final static ConcurrentHashMap NACOS_PROPERTY_SOURCE_REPOSITORY = new ConcurrentHashMap<>(); + + private NacosPropertySourceRepository() { + + } + + /** + * @return all nacos properties from application context. + */ + public static List getAll() { + return new ArrayList<>(NACOS_PROPERTY_SOURCE_REPOSITORY.values()); + } + + /** + * recommend to use {@link NacosPropertySourceRepository#collectNacosPropertySource}. + * @param nacosPropertySource nacosPropertySource + */ + @Deprecated + public static void collectNacosPropertySources( + NacosPropertySource nacosPropertySource) { + NACOS_PROPERTY_SOURCE_REPOSITORY.putIfAbsent(nacosPropertySource.getDataId(), + nacosPropertySource); + } + + /** + * recommend to use + * {@link NacosPropertySourceRepository#getNacosPropertySource(java.lang.String, java.lang.String)}. + * @param dataId dataId + * @return NacosPropertySource + */ + @Deprecated + public static NacosPropertySource getNacosPropertySource(String dataId) { + return NACOS_PROPERTY_SOURCE_REPOSITORY.get(dataId); + } + + public static void collectNacosPropertySource( + NacosPropertySource nacosPropertySource) { + NACOS_PROPERTY_SOURCE_REPOSITORY + .putIfAbsent(getMapKey(nacosPropertySource.getDataId(), + nacosPropertySource.getGroup()), nacosPropertySource); + } + + public static NacosPropertySource getNacosPropertySource(String dataId, + String group) { + return NACOS_PROPERTY_SOURCE_REPOSITORY.get(getMapKey(dataId, group)); + } + + public static String getMapKey(String dataId, String group) { + return String.join(NacosConfigProperties.COMMAS, String.valueOf(dataId), + String.valueOf(group)); + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java similarity index 79% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java index d932f2b3..2d83fa5d 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySource.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,6 +19,8 @@ package com.alibaba.cloud.nacos.client; import java.util.Date; import java.util.Map; +import com.alibaba.cloud.nacos.NacosConfigProperties; + import org.springframework.core.env.MapPropertySource; /** @@ -28,28 +30,28 @@ import org.springframework.core.env.MapPropertySource; public class NacosPropertySource extends MapPropertySource { /** - * Nacos Group + * Nacos Group. */ private final String group; /** - * Nacos dataID + * Nacos dataID. */ private final String dataId; /** - * timestamp the property get + * timestamp the property get. */ private final Date timestamp; /** - * Whether to support dynamic refresh for this Property Source + * Whether to support dynamic refresh for this Property Source. */ private final boolean isRefreshable; NacosPropertySource(String group, String dataId, Map source, Date timestamp, boolean isRefreshable) { - super(dataId, source); + super(String.join(NacosConfigProperties.COMMAS, dataId, group), source); this.group = group; this.dataId = dataId; this.timestamp = timestamp; @@ -71,4 +73,5 @@ public class NacosPropertySource extends MapPropertySource { public boolean isRefreshable() { return isRefreshable; } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java similarity index 64% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java index 9dbfe8bf..7c3dbaa7 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,16 +17,13 @@ package com.alibaba.cloud.nacos.client; import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Properties; import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.parser.NacosDataParserHandler; import com.alibaba.nacos.api.config.ConfigService; import com.alibaba.nacos.api.exception.NacosException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -37,11 +34,14 @@ import org.springframework.util.StringUtils; * @author pbting */ public class NacosPropertySourceBuilder { + private static final Logger log = LoggerFactory .getLogger(NacosPropertySourceBuilder.class); - private static final Properties EMPTY_PROPERTIES = new Properties(); + + private static final Map EMPTY_MAP = new LinkedHashMap(); private ConfigService configService; + private long timeout; public NacosPropertySourceBuilder(ConfigService configService, long timeout) { @@ -71,14 +71,15 @@ public class NacosPropertySourceBuilder { */ NacosPropertySource build(String dataId, String group, String fileExtension, boolean isRefreshable) { - Properties p = loadNacosData(dataId, group, fileExtension); + Map p = loadNacosData(dataId, group, fileExtension); NacosPropertySource nacosPropertySource = new NacosPropertySource(group, dataId, - propertiesToMap(p), new Date(), isRefreshable); - NacosPropertySourceRepository.collectNacosPropertySources(nacosPropertySource); + p, new Date(), isRefreshable); + NacosPropertySourceRepository.collectNacosPropertySource(nacosPropertySource); return nacosPropertySource; } - private Properties loadNacosData(String dataId, String group, String fileExtension) { + private Map loadNacosData(String dataId, String group, + String fileExtension) { String data = null; try { data = configService.getConfig(dataId, group, timeout); @@ -86,15 +87,16 @@ public class NacosPropertySourceBuilder { log.warn( "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]", dataId, group); - return EMPTY_PROPERTIES; + return EMPTY_MAP; } - log.info(String.format( - "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, - group, data)); - - Properties properties = NacosDataParserHandler.getInstance() + if (log.isDebugEnabled()) { + log.debug(String.format( + "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, + group, data)); + } + Map dataMap = NacosDataParserHandler.getInstance() .parseNacosData(data, fileExtension); - return properties == null ? EMPTY_PROPERTIES : properties; + return dataMap == null ? EMPTY_MAP : dataMap; } catch (NacosException e) { log.error("get data from Nacos error,dataId:{}, ", dataId, e); @@ -102,24 +104,7 @@ public class NacosPropertySourceBuilder { catch (Exception e) { log.error("parse data from Nacos error,dataId:{},data:{},", dataId, data, e); } - return EMPTY_PROPERTIES; - } - - @SuppressWarnings("unchecked") - private Map propertiesToMap(Properties properties) { - Map result = new HashMap<>(16); - Enumeration keys = (Enumeration) properties.propertyNames(); - while (keys.hasMoreElements()) { - String key = keys.nextElement(); - String value = properties.getProperty(key); - if (value != null) { - result.put(key, value.trim()); - } - else { - result.put(key, null); - } - } - return result; + return EMPTY_MAP; } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java similarity index 71% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java index 5e6bc6ae..ef075bcb 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,12 +18,12 @@ package com.alibaba.cloud.nacos.client; import java.util.List; +import com.alibaba.cloud.nacos.NacosConfigManager; import com.alibaba.cloud.nacos.NacosConfigProperties; import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.parser.NacosDataParserHandler; import com.alibaba.cloud.nacos.refresh.NacosContextRefresher; import com.alibaba.nacos.api.config.ConfigService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -51,20 +51,31 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { private static final String DOT = "."; - private static final String SHARED_CONFIG_SEPARATOR_CHAR = "[,]"; - private NacosPropertySourceBuilder nacosPropertySourceBuilder; private NacosConfigProperties nacosConfigProperties; + private NacosConfigManager nacosConfigManager; + + /** + * recommend to use + * {@link NacosPropertySourceLocator#NacosPropertySourceLocator(com.alibaba.cloud.nacos.NacosConfigManager)}. + * @param nacosConfigProperties nacosConfigProperties + */ + @Deprecated public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) { this.nacosConfigProperties = nacosConfigProperties; } + public NacosPropertySourceLocator(NacosConfigManager nacosConfigManager) { + this.nacosConfigManager = nacosConfigManager; + this.nacosConfigProperties = nacosConfigManager.getNacosConfigProperties(); + } + @Override public PropertySource locate(Environment env) { - - ConfigService configService = nacosConfigProperties.configServiceInstance(); + nacosConfigProperties.setEnvironment(env); + ConfigService configService = nacosConfigManager.getConfigService(); if (null == configService) { log.warn("no instance of config service found, can't load config from nacos"); @@ -94,68 +105,39 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { return composite; } + /** + * load shared configuration. + */ private void loadSharedConfiguration( CompositePropertySource compositePropertySource) { - String sharedDataIds = nacosConfigProperties.getSharedDataids(); - String refreshDataIds = nacosConfigProperties.getRefreshableDataids(); - - if (sharedDataIds == null || sharedDataIds.trim().length() == 0) { - return; - } - - String[] sharedDataIdArray = sharedDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); - checkDataIdFileExtension(sharedDataIdArray); - - for (int i = 0; i < sharedDataIdArray.length; i++) { - String dataId = sharedDataIdArray[i]; - String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1); - boolean isRefreshable = checkDataIdIsRefreshable(refreshDataIds, - sharedDataIdArray[i]); - - loadNacosDataIfPresent(compositePropertySource, dataId, "DEFAULT_GROUP", - fileExtension, isRefreshable); + List sharedConfigs = nacosConfigProperties + .getSharedConfigs(); + if (!CollectionUtils.isEmpty(sharedConfigs)) { + checkConfiguration(sharedConfigs, "shared-configs"); + loadNacosConfiguration(compositePropertySource, sharedConfigs); } } + /** + * load extensional configuration. + */ private void loadExtConfiguration(CompositePropertySource compositePropertySource) { List extConfigs = nacosConfigProperties - .getExtConfig(); - - if (CollectionUtils.isEmpty(extConfigs)) { - return; - } - - checkExtConfiguration(extConfigs); - - for (NacosConfigProperties.Config config : extConfigs) { - String dataId = config.getDataId(); - String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1); - loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(), - fileExtension, config.isRefresh()); + .getExtensionConfigs(); + if (!CollectionUtils.isEmpty(extConfigs)) { + checkConfiguration(extConfigs, "extension-configs"); + loadNacosConfiguration(compositePropertySource, extConfigs); } } - private void checkExtConfiguration(List extConfigs) { - String[] dataIds = new String[extConfigs.size()]; - for (int i = 0; i < extConfigs.size(); i++) { - String dataId = extConfigs.get(i).getDataId(); - if (dataId == null || dataId.trim().length() == 0) { - throw new IllegalStateException(String.format( - "the [ spring.cloud.nacos.config.ext-config[%s] ] must give a dataId", - i)); - } - dataIds[i] = dataId; - } - checkDataIdFileExtension(dataIds); - } - + /** + * load configuration of application. + */ private void loadApplicationConfiguration( CompositePropertySource compositePropertySource, String dataIdPrefix, NacosConfigProperties properties, Environment environment) { - String fileExtension = properties.getFileExtension(); String nacosGroup = properties.getGroup(); - // load directly once by default loadNacosDataIfPresent(compositePropertySource, dataIdPrefix, nacosGroup, fileExtension, true); @@ -168,6 +150,33 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup, fileExtension, true); } + + } + + private void loadNacosConfiguration(final CompositePropertySource composite, + List configs) { + for (NacosConfigProperties.Config config : configs) { + String dataId = config.getDataId(); + String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1); + loadNacosDataIfPresent(composite, dataId, config.getGroup(), fileExtension, + config.isRefresh()); + } + } + + private void checkConfiguration(List configs, + String tips) { + String[] dataIds = new String[configs.size()]; + for (int i = 0; i < configs.size(); i++) { + String dataId = configs.get(i).getDataId(); + if (dataId == null || dataId.trim().length() == 0) { + throw new IllegalStateException(String.format( + "the [ spring.cloud.nacos.config.%s[%s] ] must give a dataId", + tips, i)); + } + dataIds[i] = dataId; + } + // Just decide that the current dataId must have a suffix + NacosDataParserHandler.getInstance().checkDataId(dataIds); } private void loadNacosDataIfPresent(final CompositePropertySource composite, @@ -188,7 +197,8 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { final String group, String fileExtension, boolean isRefreshable) { if (NacosContextRefresher.getRefreshCount() != 0) { if (!isRefreshable) { - return NacosPropertySourceRepository.getNacosPropertySource(dataId); + return NacosPropertySourceRepository.getNacosPropertySource(dataId, + group); } } return nacosPropertySourceBuilder.build(dataId, group, fileExtension, @@ -210,27 +220,8 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { composite.addFirstPropertySource(nacosPropertySource); } - private static void checkDataIdFileExtension(String[] dataIdArray) { - if (dataIdArray == null || dataIdArray.length < 1) { - throw new IllegalStateException("The dataId cannot be empty"); - } - // Just decide that the current dataId must have a suffix - NacosDataParserHandler.getInstance().checkDataId(dataIdArray); - } - - private boolean checkDataIdIsRefreshable(String refreshDataIds, String sharedDataId) { - if (StringUtils.isEmpty(refreshDataIds)) { - return false; - } - - String[] refreshDataIdArray = refreshDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); - for (String refreshDataId : refreshDataIdArray) { - if (refreshDataId.equals(sharedDataId)) { - return true; - } - } - - return false; + public void setNacosConfigManager(NacosConfigManager nacosConfigManager) { + this.nacosConfigManager = nacosConfigManager; } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java similarity index 92% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java index 3c7ae0e2..33c1b2e4 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java similarity index 91% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java index 2e9efd94..e4fdae5e 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java similarity index 95% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java index 7241bb55..d5b51660 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -71,4 +71,5 @@ public class NacosConfigEndpoint { return result; } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java similarity index 73% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java index 457b7ebb..42908218 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,11 +16,12 @@ package com.alibaba.cloud.nacos.endpoint; -import com.alibaba.cloud.nacos.NacosConfigProperties; +import com.alibaba.cloud.nacos.NacosConfigManager; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; +import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -32,12 +33,12 @@ import org.springframework.context.annotation.Bean; * @author xiaojing */ @ConditionalOnWebApplication -@ConditionalOnClass(value = Endpoint.class) +@ConditionalOnClass(Endpoint.class) @ConditionalOnProperty(name = "spring.cloud.nacos.config.enabled", matchIfMissing = true) public class NacosConfigEndpointAutoConfiguration { @Autowired - private NacosConfigProperties nacosConfigProperties; + private NacosConfigManager nacosConfigManager; @Autowired private NacosRefreshHistory nacosRefreshHistory; @@ -46,12 +47,15 @@ public class NacosConfigEndpointAutoConfiguration { @ConditionalOnEnabledEndpoint @Bean public NacosConfigEndpoint nacosConfigEndpoint() { - return new NacosConfigEndpoint(nacosConfigProperties, nacosRefreshHistory); + return new NacosConfigEndpoint(nacosConfigManager.getNacosConfigProperties(), + nacosRefreshHistory); } @Bean + @ConditionalOnMissingBean + @ConditionalOnEnabledHealthIndicator("nacos-config") public NacosConfigHealthIndicator nacosConfigHealthIndicator() { - return new NacosConfigHealthIndicator( - nacosConfigProperties.configServiceInstance()); + return new NacosConfigHealthIndicator(nacosConfigManager.getConfigService()); } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java similarity index 70% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java index bdbd56f9..affd0139 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,9 +20,13 @@ import com.alibaba.nacos.api.config.ConfigService; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; /** + * The {@link HealthIndicator} for Nacos Config. + * * @author xiaojing + * @author Mercy */ public class NacosConfigHealthIndicator extends AbstractHealthIndicator { @@ -34,9 +38,21 @@ public class NacosConfigHealthIndicator extends AbstractHealthIndicator { @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - builder.up(); - + // Just return "UP" or "DOWN" String status = configService.getServerStatus(); + // Set the status to Builder builder.status(status); + switch (status) { + case "UP": + builder.up(); + break; + case "DOWN": + builder.down(); + break; + default: + builder.unknown(); + break; + } } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java similarity index 68% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java index 0e7bc3bc..6f94cb6c 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,9 +17,12 @@ package com.alibaba.cloud.nacos.parser; import java.io.IOException; -import java.util.HashMap; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Properties; +import java.util.Set; import org.springframework.util.StringUtils; @@ -32,6 +35,8 @@ public abstract class AbstractNacosDataParser { protected static final String VALUE = "value"; + protected static final String EMPTY_STRING = ""; + private String extension; private AbstractNacosDataParser nextParser; @@ -66,7 +71,7 @@ public abstract class AbstractNacosDataParser { * @return result of Properties * @throws IOException thrown if there is a problem parsing config. */ - public final Properties parseNacosData(String data, String extension) + public final Map parseNacosData(String data, String extension) throws IOException { if (extension == null || extension.length() < 1) { throw new IllegalStateException("The file extension cannot be empty"); @@ -86,7 +91,7 @@ public abstract class AbstractNacosDataParser { * @return result of Properties * @throws IOException thrown if there is a problem parsing config. */ - protected abstract Properties doParse(String data) throws IOException; + protected abstract Map doParse(String data) throws IOException; protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) { this.nextParser = nextParser; @@ -108,34 +113,47 @@ public abstract class AbstractNacosDataParser { || this.extension.contains(extension); } - /** - * Generate key-value pairs from the map. - */ - protected Properties generateProperties(Map map) { - if (null == map || map.isEmpty()) { - return null; - } - Properties properties = new Properties(); - for (Map.Entry entry : map.entrySet()) { + protected void flattenedMap(Map result, Map dataMap, + String parentKey) { + Set> entries = dataMap.entrySet(); + for (Iterator> iterator = entries.iterator(); iterator + .hasNext();) { + Map.Entry entry = iterator.next(); String key = entry.getKey(); - if (StringUtils.isEmpty(key)) { + Object value = entry.getValue(); + + String fullKey = StringUtils.isEmpty(parentKey) ? key : key.startsWith("[") + ? parentKey.concat(key) : parentKey.concat(DOT).concat(key); + + if (value instanceof Map) { + Map map = (Map) value; + flattenedMap(result, map, fullKey); continue; } - key = key.startsWith(DOT) ? key.replaceFirst("\\.", "") : key; - properties.put(key, entry.getValue()); + else if (value instanceof Collection) { + int count = 0; + Collection collection = (Collection) value; + for (Object object : collection) { + flattenedMap(result, + Collections.singletonMap("[" + (count++) + "]", object), + fullKey); + } + continue; + } + + result.put(fullKey, value); } - return properties; } /** * Reload the key ending in `value` if need. */ - protected Map reloadMap(Map map) { + protected Map reloadMap(Map map) { if (map == null || map.isEmpty()) { return null; } - Map result = new HashMap<>(map); - for (Map.Entry entry : map.entrySet()) { + Map result = new LinkedHashMap<>(map); + for (Map.Entry entry : map.entrySet()) { String key = entry.getKey(); if (key.contains(DOT)) { int idx = key.lastIndexOf(DOT); diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java new file mode 100644 index 00000000..d33cf62f --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java @@ -0,0 +1,66 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.parser; + +import java.io.IOException; +import java.util.LinkedHashMap; +import java.util.Map; + +import com.fasterxml.jackson.databind.ObjectMapper; + +import org.springframework.util.CollectionUtils; +import org.springframework.util.StringUtils; + +/** + * @author zkz + * @author yuhuangbin + */ +public class NacosDataJsonParser extends AbstractNacosDataParser { + + protected NacosDataJsonParser() { + super("json"); + } + + @Override + protected Map doParse(String data) throws IOException { + if (StringUtils.isEmpty(data)) { + return null; + } + Map map = parseJSON2Map(data); + return this.reloadMap(map); + } + + /** + * JSON to Map. + * @param json json data + * @return the map convert by json string + * @throws IOException thrown if there is a problem parsing config. + */ + private Map parseJSON2Map(String json) throws IOException { + Map result = new LinkedHashMap<>(32); + + ObjectMapper mapper = new ObjectMapper(); + Map nacosDataMap = mapper.readValue(json, LinkedHashMap.class); + + if (CollectionUtils.isEmpty(nacosDataMap)) { + return result; + } + flattenedMap(result, nacosDataMap, EMPTY_STRING); + return result; + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java similarity index 89% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java index e40f7f24..f5787e79 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,7 +17,7 @@ package com.alibaba.cloud.nacos.parser; import java.io.IOException; -import java.util.Properties; +import java.util.Map; /** * @author zkz @@ -34,10 +34,11 @@ public final class NacosDataParserHandler { * Parsing nacos configuration content. * @param data config from Nacos * @param extension file extension. json or xml or yml or yaml or properties - * @return result of properties + * @return result of LinkedHashMap * @throws IOException thrown if there is a problem parsing config. */ - public Properties parseNacosData(String data, String extension) throws IOException { + public Map parseNacosData(String data, String extension) + throws IOException { if (null == parser) { parser = this.createParser(); } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java new file mode 100644 index 00000000..315caccb --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.parser; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.StringReader; +import java.util.LinkedHashMap; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.util.StringUtils; + +/** + * @author zkz + */ +public class NacosDataPropertiesParser extends AbstractNacosDataParser { + + private static final Logger log = LoggerFactory + .getLogger(NacosDataPropertiesParser.class); + + public NacosDataPropertiesParser() { + super("properties"); + } + + @Override + protected Map doParse(String data) throws IOException { + Map result = new LinkedHashMap<>(); + + try (BufferedReader reader = new BufferedReader(new StringReader(data))) { + for (String line = reader.readLine(); line != null; line = reader + .readLine()) { + String dataLine = line.trim(); + if (StringUtils.isEmpty(dataLine) || dataLine.startsWith("#")) { + continue; + } + int index = dataLine.indexOf("="); + if (index == -1) { + log.warn("the config data is invalid {}", dataLine); + continue; + } + result.put(dataLine.substring(0, index), dataLine.substring(index + 1)); + } + } + return result; + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java similarity index 84% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java index b2d55daf..eab890b9 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,9 +18,8 @@ package com.alibaba.cloud.nacos.parser; import java.io.IOException; import java.io.StringReader; -import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.Map; -import java.util.Properties; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; @@ -46,17 +45,17 @@ public class NacosDataXmlParser extends AbstractNacosDataParser { } @Override - protected Properties doParse(String data) throws IOException { + protected Map doParse(String data) throws IOException { if (StringUtils.isEmpty(data)) { return null; } - Map map = parseXml2Map(data); - return this.generateProperties(this.reloadMap(map)); + Map map = parseXml2Map(data); + return this.reloadMap(map); } - private Map parseXml2Map(String xml) throws IOException { + private Map parseXml2Map(String xml) throws IOException { xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", ""); - Map map = new HashMap<>(32); + Map map = new LinkedHashMap<>(32); try { DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() .newDocumentBuilder(); @@ -73,7 +72,7 @@ public class NacosDataXmlParser extends AbstractNacosDataParser { return map; } - private void parseNodeList(NodeList nodeList, Map map, + private void parseNodeList(NodeList nodeList, Map map, String parentKey) { if (nodeList == null || nodeList.getLength() < 1) { return; @@ -104,7 +103,7 @@ public class NacosDataXmlParser extends AbstractNacosDataParser { } } - private void parseNodeAttr(NamedNodeMap nodeMap, Map map, + private void parseNodeAttr(NamedNodeMap nodeMap, Map map, String parentKey) { if (null == nodeMap || nodeMap.getLength() < 1) { return; diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java similarity index 63% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java index 74898027..b963a097 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,9 +16,10 @@ package com.alibaba.cloud.nacos.parser; -import java.util.Properties; +import java.util.LinkedHashMap; +import java.util.Map; -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.beans.factory.config.YamlMapFactoryBean; import org.springframework.core.io.ByteArrayResource; /** @@ -31,9 +32,13 @@ public class NacosDataYamlParser extends AbstractNacosDataParser { } @Override - protected Properties doParse(String data) { - YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); + protected Map doParse(String data) { + YamlMapFactoryBean yamlFactory = new YamlMapFactoryBean(); yamlFactory.setResources(new ByteArrayResource(data.getBytes())); - return yamlFactory.getObject(); + + Map result = new LinkedHashMap<>(); + flattenedMap(result, yamlFactory.getObject(), EMPTY_STRING); + return result; } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java new file mode 100644 index 00000000..609a6c61 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosContextRefresher.java @@ -0,0 +1,181 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.refresh; + +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicLong; + +import com.alibaba.cloud.nacos.NacosConfigManager; +import com.alibaba.cloud.nacos.NacosConfigProperties; +import com.alibaba.cloud.nacos.NacosPropertySourceRepository; +import com.alibaba.cloud.nacos.client.NacosPropertySource; +import com.alibaba.nacos.api.config.ConfigService; +import com.alibaba.nacos.api.config.listener.AbstractSharedListener; +import com.alibaba.nacos.api.config.listener.Listener; +import com.alibaba.nacos.api.exception.NacosException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.boot.context.event.ApplicationReadyEvent; +import org.springframework.cloud.endpoint.event.RefreshEvent; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.ApplicationListener; + +/** + * On application start up, NacosContextRefresher add nacos listeners to all application + * level dataIds, when there is a change in the data, listeners will refresh + * configurations. + * + * @author juven.xuxb + * @author pbting + */ +public class NacosContextRefresher + implements ApplicationListener, ApplicationContextAware { + + private final static Logger log = LoggerFactory + .getLogger(NacosContextRefresher.class); + + private static final AtomicLong REFRESH_COUNT = new AtomicLong(0); + + private NacosConfigProperties nacosConfigProperties; + + private final boolean isRefreshEnabled; + + private final NacosRefreshHistory nacosRefreshHistory; + + private final ConfigService configService; + + private ApplicationContext applicationContext; + + private AtomicBoolean ready = new AtomicBoolean(false); + + private Map listenerMap = new ConcurrentHashMap<>(16); + + public NacosContextRefresher(NacosConfigManager nacosConfigManager, + NacosRefreshHistory refreshHistory) { + this.nacosConfigProperties = nacosConfigManager.getNacosConfigProperties(); + this.nacosRefreshHistory = refreshHistory; + this.configService = nacosConfigManager.getConfigService(); + this.isRefreshEnabled = this.nacosConfigProperties.isRefreshEnabled(); + } + + /** + * recommend to use + * {@link NacosContextRefresher#NacosContextRefresher(NacosConfigManager, NacosRefreshHistory)}. + * @param refreshProperties refreshProperties + * @param refreshHistory refreshHistory + * @param configService configService + */ + @Deprecated + public NacosContextRefresher(NacosRefreshProperties refreshProperties, + NacosRefreshHistory refreshHistory, ConfigService configService) { + this.isRefreshEnabled = refreshProperties.isEnabled(); + this.nacosRefreshHistory = refreshHistory; + this.configService = configService; + } + + @Override + public void onApplicationEvent(ApplicationReadyEvent event) { + // many Spring context + if (this.ready.compareAndSet(false, true)) { + this.registerNacosListenersForApplications(); + } + } + + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + + /** + * register Nacos Listeners. + */ + private void registerNacosListenersForApplications() { + if (isRefreshEnabled()) { + for (NacosPropertySource propertySource : NacosPropertySourceRepository + .getAll()) { + if (!propertySource.isRefreshable()) { + continue; + } + String dataId = propertySource.getDataId(); + registerNacosListener(propertySource.getGroup(), dataId); + } + } + } + + private void registerNacosListener(final String groupKey, final String dataKey) { + String key = NacosPropertySourceRepository.getMapKey(dataKey, groupKey); + Listener listener = listenerMap.computeIfAbsent(key, + lst -> new AbstractSharedListener() { + @Override + public void innerReceive(String dataId, String group, + String configInfo) { + refreshCountIncrement(); + nacosRefreshHistory.addRefreshRecord(dataId, group, configInfo); + // todo feature: support single refresh for listening + applicationContext.publishEvent( + new RefreshEvent(this, null, "Refresh Nacos config")); + if (log.isDebugEnabled()) { + log.debug(String.format( + "Refresh Nacos config group=%s,dataId=%s,configInfo=%s", + group, dataId, configInfo)); + } + } + }); + try { + configService.addListener(dataKey, groupKey, listener); + } + catch (NacosException e) { + log.warn(String.format( + "register fail for nacos listener ,dataId=[%s],group=[%s]", dataKey, + groupKey), e); + } + } + + public NacosConfigProperties getNacosConfigProperties() { + return nacosConfigProperties; + } + + public NacosContextRefresher setNacosConfigProperties( + NacosConfigProperties nacosConfigProperties) { + this.nacosConfigProperties = nacosConfigProperties; + return this; + } + + public boolean isRefreshEnabled() { + if (null == nacosConfigProperties) { + return isRefreshEnabled; + } + // Compatible with older configurations + if (nacosConfigProperties.isRefreshEnabled() && !isRefreshEnabled) { + return false; + } + return isRefreshEnabled; + } + + public static long getRefreshCount() { + return REFRESH_COUNT.get(); + } + + public static void refreshCountIncrement() { + REFRESH_COUNT.incrementAndGet(); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java new file mode 100644 index 00000000..7fcd4be0 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshHistory.java @@ -0,0 +1,135 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.refresh; + +import java.math.BigInteger; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.Date; +import java.util.LinkedList; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.util.StringUtils; + +public class NacosRefreshHistory { + + private final static Logger log = LoggerFactory.getLogger(NacosRefreshHistory.class); + + private static final int MAX_SIZE = 20; + + private final LinkedList records = new LinkedList<>(); + + private final ThreadLocal DATE_FORMAT = ThreadLocal + .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); + + private MessageDigest md; + + public NacosRefreshHistory() { + try { + md = MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException e) { + log.error("failed to initialize MessageDigest : ", e); + } + } + + /** + * recommend to use + * {@link NacosRefreshHistory#addRefreshRecord(java.lang.String, java.lang.String, java.lang.String)}. + * @param dataId dataId + * @param md5 md5 + */ + @Deprecated + public void add(String dataId, String md5) { + records.addFirst( + new Record(DATE_FORMAT.get().format(new Date()), dataId, "", md5, null)); + if (records.size() > MAX_SIZE) { + records.removeLast(); + } + } + + public void addRefreshRecord(String dataId, String group, String data) { + records.addFirst(new Record(DATE_FORMAT.get().format(new Date()), dataId, group, + md5(data), null)); + if (records.size() > MAX_SIZE) { + records.removeLast(); + } + } + + public LinkedList getRecords() { + return records; + } + + private String md5(String data) { + if (StringUtils.isEmpty(data)) { + return null; + } + if (null == md) { + try { + md = MessageDigest.getInstance("MD5"); + } + catch (NoSuchAlgorithmException ignored) { + return "unable to get md5"; + } + } + return new BigInteger(1, md.digest(data.getBytes(StandardCharsets.UTF_8))) + .toString(16); + } + + static class Record { + + private final String timestamp; + + private final String dataId; + + private final String group; + + private final String md5; + + Record(String timestamp, String dataId, String group, String md5, + Map last) { + this.timestamp = timestamp; + this.dataId = dataId; + this.group = group; + this.md5 = md5; + } + + public String getTimestamp() { + return timestamp; + } + + public String getDataId() { + return dataId; + } + + public String getGroup() { + return group; + } + + public String getMd5() { + return md5; + } + + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java similarity index 75% rename from spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java index 6d07e794..0dae5d16 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/refresh/NacosRefreshProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,15 +16,22 @@ package com.alibaba.cloud.nacos.refresh; +import com.alibaba.cloud.nacos.NacosConfigProperties; + import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** * @author xiaojing */ +@Deprecated @Component public class NacosRefreshProperties { + /** + * recommend to use {@code NacosConfigProperties#refreshEnabled} + * {@link NacosConfigProperties#setRefreshEnabled(boolean)}. + */ @Value("${spring.cloud.nacos.config.refresh.enabled:true}") private boolean enabled = true; @@ -35,4 +42,5 @@ public class NacosRefreshProperties { public void setEnabled(boolean enabled) { this.enabled = enabled; } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json similarity index 76% rename from spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 593bab8c..f6f3fe41 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -3,6 +3,7 @@ { "name": "spring.cloud.nacos.server-addr", "type": "java.lang.String", + "defaultValue": "localhost:8848", "description": "nacos server address." }, { @@ -34,16 +35,32 @@ "type": "java.lang.String", "description": "the dataids for configurable multiple shared configurations , multiple separated by commas ." }, + { + "name": "spring.cloud.nacos.config.shared-configs", + "type": "java.util.List", + "description": "a set of shared configurations .e.g: spring.cloud.nacos.config.shared-configs[0]=xxx ." + }, { "name": "spring.cloud.nacos.config.refreshable-dataids", "type": "java.lang.String", - "description": "refreshable dataids , multiple separated by commas ." + "description": "refreshable dataids , multiple separated by commas .Not providing support,the need to refresh is specified by the respective refresh configuration." }, { "name": "spring.cloud.nacos.config.ext-config", "type": "java.util.List", "description": "a set of extended configurations ." }, + { + "name": "spring.cloud.nacos.config.extension-configs", + "type": "java.util.List", + "description": "a set of extensional configurations .e.g: spring.cloud.nacos.config.extension-configs[0]=xxx ." + }, + { + "name": "spring.cloud.nacos.config.refresh-enabled", + "type": "java.lang.Boolean", + "defaultValue": true, + "description": "the master switch for refresh configuration, it default opened(true)." + }, { "name": "spring.cloud.nacos.config.enabled", "type": "java.lang.Boolean", diff --git a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java similarity index 52% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java index 328c1859..d0e13489 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java @@ -1,7 +1,22 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.nacos; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; - import org.junit.Test; import org.junit.runner.RunWith; @@ -12,16 +27,18 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author lyuzb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, properties = { - "spring.cloud.nacos.config.server-addr=321,321,321,321:8848", - "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT) +@SpringBootTest( + classes = NacosConfigPropertiesServerAddressBothLevelTests.TestConfig.class, + properties = { "spring.cloud.nacos.config.server-addr=321,321,321,321:8848", + "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, + webEnvironment = RANDOM_PORT) public class NacosConfigPropertiesServerAddressBothLevelTests { @Autowired @@ -29,8 +46,7 @@ public class NacosConfigPropertiesServerAddressBothLevelTests { @Test public void testGetServerAddr() { - assertEquals("NacosConfigProperties server address was wrong", - "321,321,321,321:8848", properties.getServerAddr()); + assertThat(properties.getServerAddr()).isEqualTo("321,321,321,321:8848"); } @Configuration @@ -38,5 +54,7 @@ public class NacosConfigPropertiesServerAddressBothLevelTests { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java similarity index 54% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java index a32e4b4a..c080fe6b 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java @@ -1,7 +1,22 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.nacos; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; - import org.junit.Test; import org.junit.runner.RunWith; @@ -12,15 +27,17 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author lyuzb */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = { - "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT) +@SpringBootTest( + classes = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, + properties = { "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, + webEnvironment = RANDOM_PORT) public class NacosConfigPropertiesServerAddressTopLevelTests { @Autowired @@ -28,8 +45,7 @@ public class NacosConfigPropertiesServerAddressTopLevelTests { @Test public void testGetServerAddr() { - assertEquals("NacosConfigProperties server address was wrong", - "123.123.123.123:8848", properties.getServerAddr()); + assertThat(properties.getServerAddr()).isEqualTo("123.123.123.123:8848"); } @Configuration @@ -37,5 +53,7 @@ public class NacosConfigPropertiesServerAddressTopLevelTests { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java similarity index 74% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java index a7a3def2..73f8b80f 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,8 +22,6 @@ import java.lang.reflect.Method; import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.nacos.client.config.NacosConfigService; - -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; @@ -41,7 +39,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** @@ -52,18 +50,20 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @PowerMockIgnore("javax.management.*") @PowerMockRunnerDelegate(SpringRunner.class) @PrepareForTest({ NacosConfigService.class }) -@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", "spring.profiles.active=dev,test", - "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.config.encode=utf-8", - "spring.cloud.nacos.config.timeout=1000", - "spring.cloud.nacos.config.file-extension=properties", - "spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties", - "spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties", - "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", - "spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties", - "spring.cloud.nacos.config.accessKey=test-accessKey", - "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) +@SpringBootTest(classes = NacosConfigurationExtConfigTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "spring.profiles.active=dev,test", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.encode=utf-8", + "spring.cloud.nacos.config.timeout=1000", + "spring.cloud.nacos.config.file-extension=properties", + "spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties", + "spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties", + "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", + "spring.cloud.nacos.config.shared-dataids=common1.properties,common2.properties", + "spring.cloud.nacos.config.accessKey=test-accessKey", + "spring.cloud.nacos.config.secretKey=test-secretKey" }, + webEnvironment = NONE) public class NacosConfigurationExtConfigTests { static { @@ -131,14 +131,13 @@ public class NacosConfigurationExtConfigTests { @Test public void contextLoads() throws Exception { - assertNotNull("NacosPropertySourceLocator was not created", locator); - assertNotNull("NacosConfigProperties was not created", properties); - - Assert.assertEquals(environment.getProperty("test-ext-config1"), "config1"); - Assert.assertEquals(environment.getProperty("test-ext-config2"), "config2"); - Assert.assertEquals(environment.getProperty("test-common1"), "common1"); - Assert.assertEquals(environment.getProperty("test-common2"), "common2"); + assertThat(locator).isNotNull(); + assertThat(properties).isNotNull(); + assertThat("config1").isEqualTo(environment.getProperty("test-ext-config1")); + assertThat("config2").isEqualTo(environment.getProperty("test-ext-config2")); + assertThat("common1").isEqualTo(environment.getProperty("test-common1")); + assertThat("common2").isEqualTo(environment.getProperty("test-common2")); } @Configuration @@ -146,5 +145,7 @@ public class NacosConfigurationExtConfigTests { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNewTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNewTest.java new file mode 100644 index 00000000..7ec80f71 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNewTest.java @@ -0,0 +1,242 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Map; + +import com.alibaba.cloud.nacos.NacosConfigProperties.Config; +import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; +import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; +import com.alibaba.nacos.client.config.NacosConfigService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +/** + * @author xiaojing + */ +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosConfigService.class }) +@SpringBootTest(classes = NacosConfigurationNewTest.TestConfig.class, properties = { + "spring.application.name=myTestService1", "spring.profiles.active=dev,test", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.namespace=test-namespace", + "spring.cloud.nacos.config.encode=utf-8", + "spring.cloud.nacos.config.timeout=1000", + "spring.cloud.nacos.config.group=test-group", + "spring.cloud.nacos.config.name=test-name", + "spring.cloud.nacos.config.cluster-name=test-cluster", + "spring.cloud.nacos.config.file-extension=properties", + "spring.cloud.nacos.config.contextPath=test-contextpath", + "spring.cloud.nacos.config.extension-configs[0].data-id=ext-config-common01.properties", + "spring.cloud.nacos.config.extension-configs[1].data-id=ext-config-common02.properties", + "spring.cloud.nacos.config.extension-configs[1].group=GLOBAL_GROUP", + "spring.cloud.nacos.config.shared-configs[0]=common1.properties", + "spring.cloud.nacos.config.shared-configs[1]=common2.properties", + "spring.cloud.nacos.config.accessKey=test-accessKey", + "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) +public class NacosConfigurationNewTest { + + static { + + try { + + Method method = PowerMockito.method(NacosConfigService.class, "getConfig", + String.class, String.class, long.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + + if ("test-name.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "user.name=hello\nuser.age=12"; + } + + if ("test-name-dev.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "user.name=dev"; + } + + if ("ext-config-common01.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "test-ext-config1=config1\ntest-ext-config2=config1"; + } + if ("ext-config-common02.properties".equals(args[0]) + && "GLOBAL_GROUP".equals(args[1])) { + return "test-ext-config2=config2"; + } + + if ("common1.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "test-common1=common1\ntest-common2=common1"; + } + + if ("common2.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "test-common2=common2"; + } + + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private Environment environment; + + @Autowired + private NacosPropertySourceLocator locator; + + @Autowired + private NacosConfigProperties properties; + + @Autowired + private NacosRefreshHistory refreshHistory; + + @Test + public void contextLoads() throws Exception { + + assertThat(locator).isNotNull(); + assertThat(properties).isNotNull(); + + checkoutNacosConfigServerAddr(); + checkoutNacosConfigNamespace(); + checkoutNacosConfigClusterName(); + checkoutNacosConfigAccessKey(); + checkoutNacosConfigSecrectKey(); + checkoutNacosConfigName(); + checkoutNacosConfigGroup(); + checkoutNacosConfigContextPath(); + checkoutNacosConfigFileExtension(); + checkoutNacosConfigTimeout(); + checkoutNacosConfigEncode(); + checkShareConfigs(); + checkExtensionConfigs(); + + checkoutEndpoint(); + checkoutDataLoad(); + System.out.println(properties.toString()); + } + + private void checkoutNacosConfigServerAddr() { + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); + } + + private void checkoutNacosConfigNamespace() { + assertThat(properties.getNamespace()).isEqualTo("test-namespace"); + } + + private void checkoutNacosConfigClusterName() { + assertThat(properties.getClusterName()).isEqualTo("test-cluster"); + } + + private void checkoutNacosConfigAccessKey() { + assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); + } + + private void checkoutNacosConfigSecrectKey() { + assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); + } + + private void checkoutNacosConfigContextPath() { + assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); + } + + private void checkoutNacosConfigName() { + assertThat(properties.getName()).isEqualTo("test-name"); + } + + private void checkoutNacosConfigGroup() { + assertThat(properties.getGroup()).isEqualTo("test-group"); + } + + private void checkoutNacosConfigFileExtension() { + assertThat(properties.getFileExtension()).isEqualTo("properties"); + } + + private void checkoutNacosConfigTimeout() { + assertThat(properties.getTimeout()).isEqualTo(1000); + } + + private void checkoutNacosConfigEncode() { + assertThat(properties.getEncode()).isEqualTo("utf-8"); + } + + private void checkoutDataLoad() { + assertThat(environment.getProperty("user.name")).isEqualTo("dev"); + assertThat(environment.getProperty("user.age")).isEqualTo("12"); + } + + private void checkoutEndpoint() throws Exception { + NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, + refreshHistory); + Map map = nacosConfigEndpoint.invoke(); + assertThat(map.get("NacosConfigProperties")).isEqualTo(properties); + assertThat(map.get("RefreshHistory")).isEqualTo(refreshHistory.getRecords()); + } + + private void checkShareConfigs() throws Exception { + assertThat(properties.getSharedConfigs() != null); + assertThat(properties.getSharedConfigs()).contains( + new Config("common1.properties"), new Config("common2.properties")); + } + + private void checkExtensionConfigs() throws Exception { + assertThat(properties.getExtensionConfigs() != null); + assertThat(properties.getExtensionConfigs()).contains( + new Config("ext-config-common01.properties"), + new Config("ext-config-common02.properties", "GLOBAL_GROUP")); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, + NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNoSuffixTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNoSuffixTest.java new file mode 100644 index 00000000..a5c992ef --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationNoSuffixTest.java @@ -0,0 +1,254 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Map; + +import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; +import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; +import com.alibaba.nacos.client.config.NacosConfigService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; + +/** + * @author zkz + */ + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosConfigService.class }) +@SpringBootTest(classes = NacosConfigurationNoSuffixTest.TestConfig.class, properties = { + "spring.application.name=app-no-suffix", "spring.profiles.active=dev", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.namespace=test-namespace", + "spring.cloud.nacos.config.encode=utf-8", + "spring.cloud.nacos.config.timeout=1000", + "spring.cloud.nacos.config.group=test-group", + "spring.cloud.nacos.config.name=test-no-suffix-name", + "spring.cloud.nacos.config.cluster-name=test-cluster", + "spring.cloud.nacos.config.contextPath=test-contextpath", + "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json", + "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties", + "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", + "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data2.xml", + "spring.cloud.nacos.config.accessKey=test-accessKey", + "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) +public class NacosConfigurationNoSuffixTest { + + static { + + try { + + Method method = PowerMockito.method(NacosConfigService.class, "getConfig", + String.class, String.class, long.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + + if ("app-no-suffix".equals(args[0]) && "test-group".equals(args[1])) { + return "test-no-suffix=value-no-suffix-1"; + } + if ("app-no-suffix.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "test-no-suffix=value-no-suffix-2"; + } + + if ("test-no-suffix-name".equals(args[0]) + && "test-group".equals(args[1])) { + return "test-no-suffix-assign=assign-value-no-suffix-111"; + } + if ("test-no-suffix-name.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "test-no-suffix-assign=assign-value-no-suffix-222"; + } + if ("test-no-suffix-name-dev.properties".equals(args[0]) + && "test-group".equals(args[1])) { + return "test-no-suffix-assign=assign-dev-value-no-suffix-333"; + } + + if ("ext-json-test.json".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "{\n" + " \"people\":{\n" + + " \"firstName\":\"Brett\",\n" + + " \"lastName\":\"McLaughlin\"\n" + " }\n" + + "}"; + } + + if ("ext-config-common02.properties".equals(args[0]) + && "GLOBAL_GROUP".equals(args[1])) { + return "global-ext-config=global-config-value-2"; + } + + if ("shared-data1.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "shared-name=shared-value-1"; + } + + if ("shared-data2.xml".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return " \n" + + " \n" + + " \n" + + " 开启服务 \n" + + " 初始化一下 \n" + + " \n" + " \n" + + " one\n" + + " \n" + + " three\n" + + " \n" + + " \n" + " \n" + + " 销毁一下 \n" + + " 关闭服务 \n" + + " \n" + " \n" + + " "; + } + + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private NacosPropertySourceLocator locator; + + @Autowired + private NacosConfigProperties properties; + + @Autowired + private NacosRefreshHistory refreshHistory; + + @Autowired + private Environment environment; + + @Test + public void contextLoads() throws Exception { + + assertThat(locator).isNotNull(); + assertThat(properties).isNotNull(); + + checkoutNacosConfigServerAddr(); + checkoutNacosConfigNamespace(); + checkoutNacosConfigClusterName(); + checkoutNacosConfigAccessKey(); + checkoutNacosConfigSecrectKey(); + checkoutNacosConfigName(); + checkoutNacosConfigGroup(); + checkoutNacosConfigContextPath(); + checkoutNacosConfigFileExtension(); + checkoutNacosConfigTimeout(); + checkoutNacosConfigEncode(); + + checkoutEndpoint(); + checkEnvironmentProperties(); + } + + private void checkEnvironmentProperties() { + assertThat(environment.getProperty("test-no-suffix")).isNull(); + assertThat(environment.getProperty("test-no-suffix-assign")) + .isEqualTo("assign-dev-value-no-suffix-333"); + } + + private void checkoutNacosConfigServerAddr() { + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); + } + + private void checkoutNacosConfigNamespace() { + assertThat(properties.getNamespace()).isEqualTo("test-namespace"); + } + + private void checkoutNacosConfigClusterName() { + assertThat(properties.getClusterName()).isEqualTo("test-cluster"); + } + + private void checkoutNacosConfigAccessKey() { + assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); + } + + private void checkoutNacosConfigSecrectKey() { + assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); + } + + private void checkoutNacosConfigContextPath() { + assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); + } + + private void checkoutNacosConfigName() { + assertThat(properties.getName()).isEqualTo("test-no-suffix-name"); + } + + private void checkoutNacosConfigGroup() { + assertThat(properties.getGroup()).isEqualTo("test-group"); + } + + private void checkoutNacosConfigFileExtension() { + assertThat(properties.getFileExtension()).isEqualTo("properties"); + } + + private void checkoutNacosConfigTimeout() { + assertThat(properties.getTimeout()).isEqualTo(1000); + } + + private void checkoutNacosConfigEncode() { + assertThat(properties.getEncode()).isEqualTo("utf-8"); + } + + private void checkoutEndpoint() throws Exception { + NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, + refreshHistory); + Map map = nacosConfigEndpoint.invoke(); + assertThat(properties).isEqualTo(map.get("NacosConfigProperties")); + assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory")); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, + NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java similarity index 77% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java index 9f6380b5..102e3185 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,8 +25,6 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import com.alibaba.nacos.client.config.NacosConfigService; - -import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; @@ -44,14 +42,12 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing */ - @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") @PowerMockRunnerDelegate(SpringRunner.class) @@ -141,8 +137,8 @@ public class NacosConfigurationTests { @Test public void contextLoads() throws Exception { - assertNotNull("NacosPropertySourceLocator was not created", locator); - assertNotNull("NacosConfigProperties was not created", properties); + assertThat(locator).isNotNull(); + assertThat(properties).isNotNull(); checkoutNacosConfigServerAddr(); checkoutNacosConfigNamespace(); @@ -162,72 +158,60 @@ public class NacosConfigurationTests { } private void checkoutNacosConfigServerAddr() { - assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848", - properties.getServerAddr()); + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); } private void checkoutNacosConfigNamespace() { - assertEquals("NacosConfigProperties namespace is wrong", "test-namespace", - properties.getNamespace()); + assertThat(properties.getNamespace()).isEqualTo("test-namespace"); } private void checkoutNacosConfigClusterName() { - assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster", - properties.getClusterName()); + assertThat(properties.getClusterName()).isEqualTo("test-cluster"); } private void checkoutNacosConfigAccessKey() { - assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey", - properties.getAccessKey()); + assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); } private void checkoutNacosConfigSecrectKey() { - assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey", - properties.getSecretKey()); + assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); } private void checkoutNacosConfigContextPath() { - assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath", - properties.getContextPath()); + assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); } private void checkoutNacosConfigName() { - assertEquals("NacosConfigProperties' name is wrong", "test-name", - properties.getName()); + assertThat(properties.getName()).isEqualTo("test-name"); } private void checkoutNacosConfigGroup() { - assertEquals("NacosConfigProperties' group is wrong", "test-group", - properties.getGroup()); + assertThat(properties.getGroup()).isEqualTo("test-group"); } private void checkoutNacosConfigFileExtension() { - assertEquals("NacosConfigProperties' file extension is wrong", "properties", - properties.getFileExtension()); + assertThat(properties.getFileExtension()).isEqualTo("properties"); } private void checkoutNacosConfigTimeout() { - assertEquals("NacosConfigProperties' timeout is wrong", 1000, - properties.getTimeout()); + assertThat(properties.getTimeout()).isEqualTo(1000); } private void checkoutNacosConfigEncode() { - assertEquals("NacosConfigProperties' encode is wrong", "utf-8", - properties.getEncode()); + assertThat(properties.getEncode()).isEqualTo("utf-8"); } private void checkoutDataLoad() { - - Assert.assertEquals("dev", environment.getProperty("user.name")); - Assert.assertEquals("12", environment.getProperty("user.age")); + assertThat(environment.getProperty("user.name")).isEqualTo("dev"); + assertThat(environment.getProperty("user.age")).isEqualTo("12"); } private void checkoutEndpoint() throws Exception { NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, refreshHistory); Map map = nacosConfigEndpoint.invoke(); - assertEquals(map.get("NacosConfigProperties"), properties); - assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords()); + assertThat(map.get("NacosConfigProperties")).isEqualTo(properties); + assertThat(map.get("RefreshHistory")).isEqualTo(refreshHistory.getRecords()); } @Configuration @@ -235,5 +219,7 @@ public class NacosConfigurationTests { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java similarity index 73% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java index 43c19456..b06cfd86 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +25,6 @@ import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpoint; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import com.alibaba.nacos.client.config.NacosConfigService; - import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; @@ -40,16 +39,15 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author zkz */ - @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") @PowerMockRunnerDelegate(SpringRunner.class) @@ -68,7 +66,7 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen "spring.cloud.nacos.config.ext-config[0].data-id=ext-json-test.json", "spring.cloud.nacos.config.ext-config[1].data-id=ext-common02.properties", "spring.cloud.nacos.config.ext-config[1].group=GLOBAL_GROUP", - "spring.cloud.nacos.config.shared-dataids=shared-data1.properties", + "spring.cloud.nacos.config.shared-dataids=shared-data1.properties,shared-data.json", "spring.cloud.nacos.config.accessKey=test-accessKey", "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) public class NacosConfigurationXmlJsonTest { @@ -138,6 +136,22 @@ public class NacosConfigurationXmlJsonTest { return "shared-name=shared-value-1"; } + if ("shared-data.json".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "{\n" + " \"test\" : {\n" + + " \"name\" : \"test\",\n" + + " \"list\" : [\n" + " {\n" + + " \"name\" :\"listname1\",\n" + + " \"age\":1\n" + " },\n" + + " {\n" + + " \"name\" :\"listname2\",\n" + + " \"age\":2\n" + " }\n" + + " ],\n" + " \"metadata\" : {\n" + + " \"intKey\" : 123,\n" + + " \"booleanKey\" : true\n" + " }\n" + + " }\n" + "}"; + } + return ""; } }); @@ -158,11 +172,14 @@ public class NacosConfigurationXmlJsonTest { @Autowired private NacosRefreshHistory refreshHistory; + @Autowired + private Environment environment; + @Test public void contextLoads() throws Exception { - assertNotNull("NacosPropertySourceLocator was not created", locator); - assertNotNull("NacosConfigProperties was not created", properties); + assertThat(locator).isNotNull(); + assertThat(properties).isNotNull(); checkoutNacosConfigServerAddr(); checkoutNacosConfigNamespace(); @@ -178,69 +195,79 @@ public class NacosConfigurationXmlJsonTest { checkoutEndpoint(); + checkJsonParser(); + } + + private void checkJsonParser() { + assertThat(environment.getProperty("test.name", String.class)).isEqualTo("test"); + + assertThat(environment.getProperty("test.list[0].name", String.class)) + .isEqualTo("listname1"); + assertThat(environment.getProperty("test.list[0].age", Integer.class)) + .isEqualTo(1); + + assertThat(environment.getProperty("test.list[1].name", String.class)) + .isEqualTo("listname2"); + assertThat(environment.getProperty("test.list[1].age", Integer.class)) + .isEqualTo(2); + + assertThat( + (Integer) environment.getProperty("test.metadata.intKey", Object.class)) + .isEqualTo(123); + assertThat((Boolean) environment.getProperty("test.metadata.booleanKey", + Object.class)).isEqualTo(true); } private void checkoutNacosConfigServerAddr() { - assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848", - properties.getServerAddr()); + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); } private void checkoutNacosConfigNamespace() { - assertEquals("NacosConfigProperties namespace is wrong", "test-namespace", - properties.getNamespace()); + assertThat(properties.getNamespace()).isEqualTo("test-namespace"); } private void checkoutNacosConfigClusterName() { - assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster", - properties.getClusterName()); + assertThat(properties.getClusterName()).isEqualTo("test-cluster"); } private void checkoutNacosConfigAccessKey() { - assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey", - properties.getAccessKey()); + assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); } private void checkoutNacosConfigSecrectKey() { - assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey", - properties.getSecretKey()); + assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); } private void checkoutNacosConfigContextPath() { - assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath", - properties.getContextPath()); + assertThat(properties.getContextPath()).isEqualTo("test-contextpath"); } private void checkoutNacosConfigName() { - assertEquals("NacosConfigProperties' name is wrong", "test-name", - properties.getName()); + assertThat(properties.getName()).isEqualTo("test-name"); } private void checkoutNacosConfigGroup() { - assertEquals("NacosConfigProperties' group is wrong", "test-group", - properties.getGroup()); + assertThat(properties.getGroup()).isEqualTo("test-group"); } private void checkoutNacosConfigFileExtension() { - assertEquals("NacosConfigProperties' file extension is wrong", "xml", - properties.getFileExtension()); + assertThat(properties.getFileExtension()).isEqualTo("xml"); } private void checkoutNacosConfigTimeout() { - assertEquals("NacosConfigProperties' timeout is wrong", 1000, - properties.getTimeout()); + assertThat(properties.getTimeout()).isEqualTo(1000); } private void checkoutNacosConfigEncode() { - assertEquals("NacosConfigProperties' encode is wrong", "utf-8", - properties.getEncode()); + assertThat(properties.getEncode()).isEqualTo("utf-8"); } private void checkoutEndpoint() throws Exception { NacosConfigEndpoint nacosConfigEndpoint = new NacosConfigEndpoint(properties, refreshHistory); Map map = nacosConfigEndpoint.invoke(); - assertEquals(map.get("NacosConfigProperties"), properties); - assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords()); + assertThat(properties).isEqualTo(map.get("NacosConfigProperties")); + assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory")); } @Configuration @@ -248,5 +275,7 @@ public class NacosConfigurationXmlJsonTest { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java similarity index 90% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java index ef99aaf6..22961051 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,6 @@ import java.lang.reflect.Method; import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; import com.alibaba.nacos.client.config.NacosConfigService; - import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -50,10 +49,11 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen @PowerMockIgnore("javax.management.*") @PowerMockRunnerDelegate(SpringRunner.class) @PrepareForTest({ NacosConfigService.class }) -@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class, properties = { - "spring.application.name=test-name", - "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.config.file-extension=yaml" }, webEnvironment = NONE) +@SpringBootTest(classes = NacosFileExtensionTest.TestConfig.class, + properties = { "spring.application.name=test-name", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.file-extension=yaml" }, + webEnvironment = NONE) public class NacosFileExtensionTest { static { @@ -95,5 +95,7 @@ public class NacosFileExtensionTest { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java similarity index 79% rename from spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java index 84b38f4e..810137cf 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,6 @@ import com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration; import com.alibaba.cloud.nacos.NacosConfigProperties; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; import com.alibaba.nacos.client.config.NacosConfigService; - import org.junit.Test; import org.junit.runner.RunWith; import org.powermock.api.mockito.PowerMockito; @@ -42,37 +41,30 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing */ - @RunWith(PowerMockRunner.class) @PowerMockIgnore("javax.management.*") @PowerMockRunnerDelegate(SpringRunner.class) @PrepareForTest({ NacosConfigService.class }) -@SpringBootTest(classes = NacosConfigEndpointTests.TestConfig.class, properties = { - "spring.application.name=test-name", - "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.config.file-extension=properties" }, webEnvironment = NONE) +@SpringBootTest(classes = NacosConfigEndpointTests.TestConfig.class, + properties = { "spring.application.name=test-name", + "spring.cloud.nacos.config.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.config.file-extension=properties" }, + webEnvironment = NONE) public class NacosConfigEndpointTests { static { try { - Method method = PowerMockito.method(NacosConfigService.class, "getConfig", - String.class, String.class, long.class); - MethodProxy.proxy(method, (proxy, method1, args) -> { - - if ("test-name.properties".equals(args[0]) - && "DEFAULT_GROUP".equals(args[1])) { - return "user.name=hello\nuser.age=12"; - } - return ""; - }); + Method method = PowerMockito.method(NacosConfigService.class, + "getServerStatus"); + MethodProxy.proxy(method, (proxy, method1, args) -> "UP"); } catch (Exception ignore) { @@ -91,7 +83,7 @@ public class NacosConfigEndpointTests { public void contextLoads() throws Exception { checkoutEndpoint(); - // checkoutAcmHealthIndicator(); + checkoutAcmHealthIndicator(); } @@ -106,8 +98,7 @@ public class NacosConfigEndpointTests { Builder builder1 = new Builder(); builder1.up(); - assertEquals(builder1.build(), builder.build()); - + assertThat(builder.build()).isEqualTo(builder1.build()); } catch (Exception ignore) { @@ -119,8 +110,9 @@ public class NacosConfigEndpointTests { NacosConfigEndpoint endpoint = new NacosConfigEndpoint(properties, refreshHistory); Map map = endpoint.invoke(); - assertEquals(map.get("NacosConfigProperties"), properties); - assertEquals(map.get("RefreshHistory"), refreshHistory.getRecords()); + + assertThat(properties).isEqualTo(map.get("NacosConfigProperties")); + assertThat(refreshHistory.getRecords()).isEqualTo(map.get("RefreshHistory")); } @Configuration @@ -128,5 +120,7 @@ public class NacosConfigEndpointTests { @ImportAutoConfiguration({ NacosConfigEndpointAutoConfiguration.class, NacosConfigAutoConfiguration.class, NacosConfigBootstrapConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/pom.xml similarity index 68% rename from spring-cloud-alibaba-nacos-discovery/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/pom.xml index e4b2ec03..6e75c8db 100644 --- a/spring-cloud-alibaba-nacos-discovery/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/pom.xml @@ -1,28 +1,76 @@ - + 4.0.0 com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml - 4.0.0 - spring-cloud-alibaba-nacos-discovery - Spring Cloud Alibaba Nacos Discovery + spring-cloud-starter-alibaba-nacos-discovery + Spring Cloud Starter Alibaba Nacos Discovery + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + org.springframework.boot + spring-boot-starter + true + + + + org.springframework.boot + spring-boot-starter-webflux + true + + com.alibaba.nacos nacos-client + + com.alibaba.spring + spring-context-support + + org.springframework.cloud spring-cloud-commons + org.springframework.cloud spring-cloud-context @@ -45,52 +93,44 @@ true - - org.springframework.boot - spring-boot-actuator - true - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - org.springframework.boot - spring-boot - provided - true - - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - org.springframework.boot spring-boot-starter-web test + + org.springframework.boot spring-boot-starter-test test + org.springframework.cloud spring-cloud-test-support test + + + io.projectreactor + reactor-test + test + + + + org.powermock + powermock-module-junit4 + 2.0.0 + test + + + + org.powermock + powermock-api-mockito2 + 2.0.0 + test + diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java similarity index 87% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java index d576b879..18c4db13 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ConditionalOnNacosDiscoveryEnabled.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +25,8 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.TYPE, ElementType.METHOD }) -@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled", matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.nacos.discovery.enabled", + matchIfMissing = true) public @interface ConditionalOnNacosDiscoveryEnabled { } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java similarity index 89% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java index e7fb8444..5b283c9a 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,6 +25,8 @@ import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import javax.annotation.PostConstruct; @@ -34,7 +36,7 @@ import com.alibaba.nacos.api.naming.NamingMaintainService; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.client.naming.utils.UtilAndComs; - +import com.alibaba.spring.util.PropertySourcesUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,6 +44,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.cloud.commons.util.InetUtils; +import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; @@ -69,18 +72,25 @@ public class NacosDiscoveryProperties { private static final Logger log = LoggerFactory .getLogger(NacosDiscoveryProperties.class); + /** + * Prefix of {@link NacosDiscoveryProperties}. + */ + public static final String PREFIX = "spring.cloud.nacos.discovery"; + + private static final Pattern PATTERN = Pattern.compile("-(\\w)"); + /** * nacos discovery server address. */ private String serverAddr; /** - * nacos auth username. + * the nacos authentication username. */ private String username; /** - * nacos auth password. + * the nacos authentication password. */ private String password; @@ -459,8 +469,8 @@ public class NacosDiscoveryProperties { String serverAddr = env .resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"); if (StringUtils.isEmpty(serverAddr)) { - serverAddr = env - .resolvePlaceholders("${spring.cloud.nacos.server-addr:}"); + serverAddr = env.resolvePlaceholders( + "${spring.cloud.nacos.server-addr:localhost:8848}"); } this.setServerAddr(serverAddr); } @@ -493,12 +503,10 @@ public class NacosDiscoveryProperties { env.resolvePlaceholders("${spring.cloud.nacos.discovery.group:}")); } if (StringUtils.isEmpty(this.getUsername())) { - this.setUsername( - env.resolvePlaceholders("${spring.cloud.nacos.username:}")); + this.setUsername(env.resolvePlaceholders("${spring.cloud.nacos.username:}")); } if (StringUtils.isEmpty(this.getPassword())) { - this.setPassword( - env.resolvePlaceholders("${spring.cloud.nacos.password:}")); + this.setPassword(env.resolvePlaceholders("${spring.cloud.nacos.password:}")); } } @@ -518,6 +526,7 @@ public class NacosDiscoveryProperties { return namingService; } + @Deprecated public NamingMaintainService namingMaintainServiceInstance() { if (null != namingMaintainService) { @@ -538,8 +547,8 @@ public class NacosDiscoveryProperties { private Properties getNacosProperties() { Properties properties = new Properties(); properties.put(SERVER_ADDR, serverAddr); - properties.put(USERNAME, Objects.toString(username,"")); - properties.put(PASSWORD, Objects.toString(password,"")); + properties.put(USERNAME, Objects.toString(username, "")); + properties.put(PASSWORD, Objects.toString(password, "")); properties.put(NAMESPACE, namespace); properties.put(UtilAndComs.NACOS_NAMING_LOG_NAME, logName); @@ -556,7 +565,26 @@ public class NacosDiscoveryProperties { properties.put(SECRET_KEY, secretKey); properties.put(CLUSTER_NAME, clusterName); properties.put(NAMING_LOAD_CACHE_AT_START, namingLoadCacheAtStart); + + enrichNacosDiscoveryProperties(properties); return properties; } + private void enrichNacosDiscoveryProperties(Properties nacosDiscoveryProperties) { + Map properties = PropertySourcesUtils + .getSubProperties((ConfigurableEnvironment) environment, PREFIX); + properties.forEach((k, v) -> nacosDiscoveryProperties.putIfAbsent(resolveKey(k), + String.valueOf(v))); + } + + private String resolveKey(String key) { + Matcher matcher = PATTERN.matcher(key); + StringBuffer sb = new StringBuffer(); + while (matcher.find()) { + matcher.appendReplacement(sb, matcher.group(1).toUpperCase()); + } + matcher.appendTail(sb); + return sb.toString(); + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java similarity index 93% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java index 407a1560..1db22449 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosServiceInstance.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,10 +26,15 @@ import org.springframework.cloud.client.ServiceInstance; * @author xiaojing */ public class NacosServiceInstance implements ServiceInstance { + private String serviceId; + private String host; + private int port; + private boolean secure; + private Map metadata; @Override diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfiguration.java new file mode 100644 index 00000000..0af3a187 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfiguration.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery; + +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author echooymxq + **/ +@Configuration +@ConditionalOnDiscoveryEnabled +@ConditionalOnNacosDiscoveryEnabled +public class NacosDiscoveryAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public NacosDiscoveryProperties nacosProperties() { + return new NacosDiscoveryProperties(); + } + + @Bean + @ConditionalOnMissingBean + public NacosServiceDiscovery nacosServiceDiscovery( + NacosDiscoveryProperties discoveryProperties) { + return new NacosServiceDiscovery(discoveryProperties); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java new file mode 100644 index 00000000..d446e292 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java @@ -0,0 +1,75 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery; + +import java.util.Collections; +import java.util.List; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; + +/** + * @author xiaojing + * @author renhaojun + * @author echooymxq + */ +public class NacosDiscoveryClient implements DiscoveryClient { + + private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class); + + /** + * Nacos Discovery Client Description. + */ + public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; + + private NacosServiceDiscovery serviceDiscovery; + + public NacosDiscoveryClient(NacosServiceDiscovery nacosServiceDiscovery) { + this.serviceDiscovery = nacosServiceDiscovery; + } + + @Override + public String description() { + return DESCRIPTION; + } + + @Override + public List getInstances(String serviceId) { + try { + return serviceDiscovery.getInstances(serviceId); + } + catch (Exception e) { + throw new RuntimeException( + "Can not get hosts from nacos server. serviceId: " + serviceId, e); + } + } + + @Override + public List getServices() { + try { + return serviceDiscovery.getServices(); + } + catch (Exception e) { + log.error("get service name from nacos server fail,", e); + return Collections.emptyList(); + } + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfiguration.java similarity index 64% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfiguration.java index abcd947e..f2453f41 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,40 +19,46 @@ package com.alibaba.cloud.nacos.discovery; import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.client.CommonsClientAutoConfiguration; +import org.springframework.cloud.client.ConditionalOnBlockingDiscoveryEnabled; +import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.scheduling.TaskScheduler; /** * @author xiaojing + * @author echooymxq */ @Configuration +@ConditionalOnDiscoveryEnabled +@ConditionalOnBlockingDiscoveryEnabled @ConditionalOnNacosDiscoveryEnabled @AutoConfigureBefore({ SimpleDiscoveryClientAutoConfiguration.class, CommonsClientAutoConfiguration.class }) -public class NacosDiscoveryClientAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public NacosDiscoveryProperties nacosProperties() { - return new NacosDiscoveryProperties(); - } +@AutoConfigureAfter(NacosDiscoveryAutoConfiguration.class) +public class NacosDiscoveryClientConfiguration { @Bean public DiscoveryClient nacosDiscoveryClient( - NacosDiscoveryProperties discoveryProperties) { - return new NacosDiscoveryClient(discoveryProperties); + NacosServiceDiscovery nacosServiceDiscovery) { + return new NacosDiscoveryClient(nacosServiceDiscovery); } @Bean @ConditionalOnMissingBean - @ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled", matchIfMissing = true) - public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties) { - return new NacosWatch(nacosDiscoveryProperties); + @ConditionalOnProperty(value = "spring.cloud.nacos.discovery.watch.enabled", + matchIfMissing = true) + public NacosWatch nacosWatch(NacosDiscoveryProperties nacosDiscoveryProperties, + ObjectProvider taskScheduler) { + return new NacosWatch(nacosDiscoveryProperties, taskScheduler); } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscovery.java similarity index 61% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscovery.java index 550d17b2..ffe73aaf 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscovery.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,54 +17,64 @@ package com.alibaba.cloud.nacos.discovery; import java.util.ArrayList; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.NacosServiceInstance; +import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; /** - * @author xiaojing - * @author renhaojun - */ -public class NacosDiscoveryClient implements DiscoveryClient { - - private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class); - public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; + * @author echooymxq + **/ +public class NacosServiceDiscovery { private NacosDiscoveryProperties discoveryProperties; - public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) { + public NacosServiceDiscovery(NacosDiscoveryProperties discoveryProperties) { this.discoveryProperties = discoveryProperties; } - @Override - public String description() { - return DESCRIPTION; + /** + * Return all instances for the given service. + * @param serviceId id of service + * @return list of instances + * @throws NacosException nacosException + */ + public List getInstances(String serviceId) throws NacosException { + String group = discoveryProperties.getGroup(); + List instances = discoveryProperties.namingServiceInstance() + .selectInstances(serviceId, group, true); + return hostToServiceInstanceList(instances, serviceId); } - @Override - public List getInstances(String serviceId) { - try { - String group = discoveryProperties.getGroup(); - List instances = discoveryProperties.namingServiceInstance() - .selectInstances(serviceId, group, true); - return hostToServiceInstanceList(instances, serviceId); - } - catch (Exception e) { - throw new RuntimeException( - "Can not get hosts from nacos server. serviceId: " + serviceId, e); + /** + * Return the names of all services. + * @return list of service names + * @throws NacosException nacosException + */ + public List getServices() throws NacosException { + String group = discoveryProperties.getGroup(); + ListView services = discoveryProperties.namingServiceInstance() + .getServicesOfServer(1, Integer.MAX_VALUE, group); + return services.getData(); + } + + public static List hostToServiceInstanceList( + List instances, String serviceId) { + List result = new ArrayList<>(instances.size()); + for (Instance instance : instances) { + ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId); + if (serviceInstance != null) { + result.add(serviceInstance); + } } + return result; } public static ServiceInstance hostToServiceInstance(Instance instance, @@ -92,30 +102,4 @@ public class NacosDiscoveryClient implements DiscoveryClient { return nacosServiceInstance; } - public static List hostToServiceInstanceList( - List instances, String serviceId) { - List result = new ArrayList<>(instances.size()); - for (Instance instance : instances) { - ServiceInstance serviceInstance = hostToServiceInstance(instance, serviceId); - if (serviceInstance != null) { - result.add(serviceInstance); - } - } - return result; - } - - @Override - public List getServices() { - - try { - String group = discoveryProperties.getGroup(); - ListView services = discoveryProperties.namingServiceInstance() - .getServicesOfServer(1, Integer.MAX_VALUE, group); - return services.getData(); - } - catch (Exception e) { - log.error("get service name from nacos server fail,", e); - return Collections.emptyList(); - } - } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java similarity index 78% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java index fb777c0e..d10ef0a5 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,19 +16,15 @@ package com.alibaba.cloud.nacos.discovery; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.nacos.api.naming.listener.EventListener; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.ObjectProvider; import org.springframework.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -55,10 +51,6 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl private ScheduledFuture watchFuture; - private Set cacheServices = new HashSet<>(); - - private HashMap subscribeListeners = new HashMap<>(); - public NacosWatch(NacosDiscoveryProperties properties) { this(properties, getTaskScheduler()); } @@ -68,8 +60,21 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl this.taskScheduler = taskScheduler; } + /** + * The constructor with {@link NacosDiscoveryProperties} bean and the optional. + * {@link TaskScheduler} bean + * @param properties {@link NacosDiscoveryProperties} bean + * @param taskScheduler the optional {@link TaskScheduler} bean + * @since 2.2.0 + */ + public NacosWatch(NacosDiscoveryProperties properties, + ObjectProvider taskScheduler) { + this(properties, taskScheduler.getIfAvailable(NacosWatch::getTaskScheduler)); + } + private static ThreadPoolTaskScheduler getTaskScheduler() { ThreadPoolTaskScheduler taskScheduler = new ThreadPoolTaskScheduler(); + taskScheduler.setBeanName("Nacso-Watch-Task-Scheduler"); taskScheduler.initialize(); return taskScheduler; } @@ -101,13 +106,17 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl @Override public void stop() { if (this.running.compareAndSet(true, false) && this.watchFuture != null) { + // shutdown current user-thread, + // then the other daemon-threads will terminate automatic. + ((ThreadPoolTaskScheduler) this.taskScheduler).shutdown(); + this.watchFuture.cancel(true); } } @Override public boolean isRunning() { - return false; + return this.running.get(); } @Override @@ -122,4 +131,5 @@ public class NacosWatch implements ApplicationEventPublisherAware, SmartLifecycl new HeartbeatEvent(this, nacosWatchIndex.getAndIncrement())); } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/actuate/health/NacosDiscoveryHealthIndicator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/actuate/health/NacosDiscoveryHealthIndicator.java new file mode 100644 index 00000000..5a925ec3 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/actuate/health/NacosDiscoveryHealthIndicator.java @@ -0,0 +1,59 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery.actuate.health; + +import com.alibaba.nacos.api.naming.NamingService; + +import org.springframework.boot.actuate.health.AbstractHealthIndicator; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.HealthIndicator; + +/** + * The {@link HealthIndicator} for Nacos Discovery. + * + * @author Mercy + * @since 2.2.0 + * @see HealthIndicator + */ +public class NacosDiscoveryHealthIndicator extends AbstractHealthIndicator { + + private final NamingService namingService; + + public NacosDiscoveryHealthIndicator(NamingService namingService) { + this.namingService = namingService; + } + + @Override + protected void doHealthCheck(Health.Builder builder) throws Exception { + // Just return "UP" or "DOWN" + String status = namingService.getServerStatus(); + // Set the status to Builder + builder.status(status); + switch (status) { + case "UP": + builder.up(); + break; + case "DOWN": + builder.down(); + break; + default: + builder.unknown(); + break; + } + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java similarity index 94% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java index 2c916bad..56785ed4 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java similarity index 70% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java index 6ee2aaad..73a01d93 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,9 @@ package com.alibaba.cloud.nacos.discovery.configclient; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -31,10 +32,12 @@ import org.springframework.context.annotation.Configuration; * @author JevonYang */ @ConditionalOnClass(ConfigServicePropertySourceLocator.class) -@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", matchIfMissing = false) +@ConditionalOnProperty(value = "spring.cloud.config.discovery.enabled", + matchIfMissing = false) @Configuration -@ImportAutoConfiguration({ NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) +@ImportAutoConfiguration({ NacosDiscoveryAutoConfiguration.class, + NacosDiscoveryClientConfiguration.class, + NacosReactiveDiscoveryClientConfiguration.class }) public class NacosDiscoveryClientConfigServiceBootstrapConfiguration { } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClient.java new file mode 100644 index 00000000..d01731a6 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClient.java @@ -0,0 +1,84 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery.reactive; + +import java.util.function.Function; + +import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery; +import com.alibaba.nacos.api.exception.NacosException; +import org.reactivestreams.Publisher; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; + +/** + * @author echooymxq + **/ +public class NacosReactiveDiscoveryClient implements ReactiveDiscoveryClient { + + private static final Logger log = LoggerFactory + .getLogger(NacosReactiveDiscoveryClient.class); + + private NacosServiceDiscovery serviceDiscovery; + + public NacosReactiveDiscoveryClient(NacosServiceDiscovery nacosServiceDiscovery) { + this.serviceDiscovery = nacosServiceDiscovery; + } + + @Override + public String description() { + return "Spring Cloud Nacos Reactive Discovery Client"; + } + + @Override + public Flux getInstances(String serviceId) { + + return Mono.justOrEmpty(serviceId).flatMapMany(loadInstancesFromNacos()) + .subscribeOn(Schedulers.boundedElastic()); + } + + private Function> loadInstancesFromNacos() { + return serviceId -> { + try { + return Flux.fromIterable(serviceDiscovery.getInstances(serviceId)); + } + catch (NacosException e) { + log.error("get service instance[{}] from nacos error!", serviceId, e); + return Flux.empty(); + } + }; + } + + @Override + public Flux getServices() { + return Flux.defer(() -> { + try { + return Flux.fromIterable(serviceDiscovery.getServices()); + } + catch (Exception e) { + log.error("get services from nacos server fail,", e); + return Flux.empty(); + } + }).subscribeOn(Schedulers.boundedElastic()); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfiguration.java new file mode 100644 index 00000000..96c32767 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfiguration.java @@ -0,0 +1,52 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery.reactive; + +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration; +import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery; + +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.client.ConditionalOnDiscoveryEnabled; +import org.springframework.cloud.client.ConditionalOnReactiveDiscoveryEnabled; +import org.springframework.cloud.client.ReactiveCommonsClientAutoConfiguration; +import org.springframework.cloud.client.discovery.composite.reactive.ReactiveCompositeDiscoveryClientAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author echooymxq + **/ +@Configuration +@ConditionalOnDiscoveryEnabled +@ConditionalOnReactiveDiscoveryEnabled +@ConditionalOnNacosDiscoveryEnabled +@AutoConfigureAfter({ NacosDiscoveryAutoConfiguration.class, + ReactiveCompositeDiscoveryClientAutoConfiguration.class }) +@AutoConfigureBefore({ ReactiveCommonsClientAutoConfiguration.class }) +public class NacosReactiveDiscoveryClientConfiguration { + + @Bean + @ConditionalOnMissingBean + public NacosReactiveDiscoveryClient nacosReactiveDiscoveryClient( + NacosServiceDiscovery nacosServiceDiscovery) { + return new NacosReactiveDiscoveryClient(nacosServiceDiscovery); + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java similarity index 94% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java index 1c8045a5..a824675e 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,6 @@ import java.util.Map; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -32,7 +31,8 @@ import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; /** - * Endpoint for nacos discovery, get nacos properties and subscribed services + * Endpoint for nacos discovery, get nacos properties and subscribed services. + * * @author xiaojing */ @Endpoint(id = "nacos-discovery") @@ -67,4 +67,5 @@ public class NacosDiscoveryEndpoint { result.put("subscribe", subscribe); return result; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java similarity index 67% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java index 144bfe8b..ff3b65f3 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,16 +18,22 @@ package com.alibaba.cloud.nacos.endpoint; import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.actuate.health.NacosDiscoveryHealthIndicator; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; +import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** + * The AutoConfiguration class for Nacos Discovery's Endpoints. + * * @author xiaojing + * @author Mercy */ @Configuration @ConditionalOnClass(Endpoint.class) @@ -42,4 +48,12 @@ public class NacosDiscoveryEndpointAutoConfiguration { return new NacosDiscoveryEndpoint(nacosDiscoveryProperties); } + @Bean + @ConditionalOnEnabledHealthIndicator("nacos-discovery") + public HealthIndicator nacosDiscoveryHealthIndicator( + NacosDiscoveryProperties nacosDiscoveryProperties) { + return new NacosDiscoveryHealthIndicator( + nacosDiscoveryProperties.namingServiceInstance()); + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java similarity index 96% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java index 61db22b0..649ddd67 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -32,6 +32,7 @@ import org.springframework.util.StringUtils; */ public class NacosAutoServiceRegistration extends AbstractAutoServiceRegistration { + private static final Logger log = LoggerFactory .getLogger(NacosAutoServiceRegistration.class); diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java similarity index 93% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java index 50add569..aac1b82f 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -38,9 +38,24 @@ import org.springframework.util.StringUtils; */ public class NacosRegistration implements Registration, ServiceInstance { + /** + * The metadata key of management port. + */ public static final String MANAGEMENT_PORT = "management.port"; + + /** + * The metadata key of management context-path. + */ public static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; + + /** + * The metadata key of management address. + */ public static final String MANAGEMENT_ADDRESS = "management.address"; + + /** + * The metadata key of management endpoints web base path. + */ public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path"; private NacosDiscoveryProperties nacosDiscoveryProperties; @@ -151,4 +166,5 @@ public class NacosRegistration implements Registration, ServiceInstance { return "NacosRegistration{" + "nacosDiscoveryProperties=" + nacosDiscoveryProperties + '}'; } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java similarity index 91% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java index dd69ba84..b0974a55 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,6 @@ import java.util.List; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -29,6 +28,8 @@ import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.util.StringUtils; +import static org.springframework.util.ReflectionUtils.rethrowRuntimeException; + /** * @author xiaojing * @author Mercy @@ -67,6 +68,9 @@ public class NacosServiceRegistry implements ServiceRegistry { catch (Exception e) { log.error("nacos registry, {} register failed...{},", serviceId, registration.toString(), e); + // rethrow a RuntimeException if the registration is failed. + // issue : https://github.com/alibaba/spring-cloud-alibaba/issues/1132 + rethrowRuntimeException(e); } } @@ -80,6 +84,7 @@ public class NacosServiceRegistry implements ServiceRegistry { return; } + NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); String serviceId = registration.getServiceId(); String group = nacosDiscoveryProperties.getGroup(); @@ -138,8 +143,9 @@ public class NacosServiceRegistry implements ServiceRegistry { .getAllInstances(serviceName); for (Instance instance : instances) { if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp()) - && instance.getPort() == nacosDiscoveryProperties.getPort()) + && instance.getPort() == nacosDiscoveryProperties.getPort()) { return instance.isEnabled() ? "UP" : "DOWN"; + } } } catch (Exception e) { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistryAutoConfiguration.java similarity index 81% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistryAutoConfiguration.java index 4158db50..5ff6fa22 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistryAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,11 +14,11 @@ * limitations under the License. */ -package com.alibaba.cloud.nacos; +package com.alibaba.cloud.nacos.registry; -import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration; -import com.alibaba.cloud.nacos.registry.NacosRegistration; -import com.alibaba.cloud.nacos.registry.NacosServiceRegistry; +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -38,10 +38,12 @@ import org.springframework.context.annotation.Configuration; @Configuration @EnableConfigurationProperties @ConditionalOnNacosDiscoveryEnabled -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", + matchIfMissing = true) @AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, - AutoServiceRegistrationAutoConfiguration.class }) -public class NacosDiscoveryAutoConfiguration { + AutoServiceRegistrationAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class }) +public class NacosServiceRegistryAutoConfiguration { @Bean public NacosServiceRegistry nacosServiceRegistry( @@ -66,4 +68,5 @@ public class NacosDiscoveryAutoConfiguration { return new NacosAutoServiceRegistration(registry, autoServiceRegistrationProperties, registration); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java similarity index 90% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java index 1e25ec47..1cbdb659 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ConditionalOnRibbonNacos.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java similarity index 90% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java index 48424f74..e52278cb 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java @@ -25,13 +25,14 @@ import com.alibaba.nacos.client.naming.core.Balancer; * @author itmuch.com */ public class ExtendBalancer extends Balancer { + /** - * 根据权重,随机选择实例 - * - * @param instances 实例列表 - * @return 选择的实例 + * Choose instance by weight. + * @param instances Instance List + * @return the chosen instance */ public static Instance getHostByRandomWeight2(List instances) { return getHostByRandomWeight(instances); } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java similarity index 71% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java index 10edd67c..647d7003 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,26 +17,37 @@ package com.alibaba.cloud.nacos.ribbon; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; - import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.ServerList; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; +import org.springframework.cloud.netflix.ribbon.PropertiesFactory; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * integrated Ribbon by default + * integrated Ribbon by default. + * * @author xiaojing + * @author liujunjie */ @Configuration @ConditionalOnRibbonNacos public class NacosRibbonClientConfiguration { + @Autowired + private PropertiesFactory propertiesFactory; + @Bean @ConditionalOnMissingBean public ServerList ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) { + if (this.propertiesFactory.isSet(ServerList.class, config.getClientName())) { + ServerList serverList = this.propertiesFactory.get(ServerList.class, config, + config.getClientName()); + return serverList; + } NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); serverList.initWithNiwsConfig(config); return serverList; @@ -47,4 +58,5 @@ public class NacosRibbonClientConfiguration { public NacosServerIntrospector nacosServerIntrospector() { return new NacosServerIntrospector(); } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java similarity index 97% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java index 0c3cad20..db0a6d9c 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java @@ -23,7 +23,6 @@ import java.util.stream.Collectors; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; - import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; @@ -42,6 +41,7 @@ import org.springframework.util.CollectionUtils; * @author itmuch.com */ public class NacosRule extends AbstractLoadBalancerRule { + private static final Logger LOGGER = LoggerFactory.getLogger(NacosRule.class); @Autowired @@ -54,7 +54,7 @@ public class NacosRule extends AbstractLoadBalancerRule { DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); String name = loadBalancer.getName(); - NamingService namingService = this.nacosDiscoveryProperties + NamingService namingService = nacosDiscoveryProperties .namingServiceInstance(); List instances = namingService.selectInstances(name, true); if (CollectionUtils.isEmpty(instances)) { @@ -91,4 +91,5 @@ public class NacosRule extends AbstractLoadBalancerRule { @Override public void initWithNiwsConfig(IClientConfig iClientConfig) { } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java similarity index 93% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java index 73d9579e..9c292a9a 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServer.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +19,6 @@ package com.alibaba.cloud.nacos.ribbon; import java.util.Map; import com.alibaba.nacos.api.naming.pojo.Instance; - import com.netflix.loadbalancer.Server; /** @@ -29,7 +28,9 @@ import com.netflix.loadbalancer.Server; public class NacosServer extends Server { private final MetaInfo metaInfo; + private final Instance instance; + private final Map metadata; public NacosServer(final Instance instance) { @@ -71,4 +72,5 @@ public class NacosServer extends Server { public Map getMetadata() { return metadata; } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java similarity index 91% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java index 35fc86c4..d186446d 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -43,4 +43,5 @@ public class NacosServerIntrospector extends DefaultServerIntrospector { return super.isSecure(server); } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java similarity index 95% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java index bc7740bb..55928f26 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,6 @@ import java.util.List; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.client.naming.utils.CollectionUtils; - import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractServerList; @@ -84,4 +83,5 @@ public class NacosServerList extends AbstractServerList { public void initWithNiwsConfig(IClientConfig iClientConfig) { this.serviceId = iClientConfig.getClientName(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java similarity index 93% rename from spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java index 7a6a1225..77410e56 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -38,4 +38,5 @@ import org.springframework.context.annotation.Configuration; @AutoConfigureAfter(RibbonAutoConfiguration.class) @RibbonClients(defaultConfiguration = NacosRibbonClientConfiguration.class) public class RibbonNacosAutoConfiguration { -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json similarity index 98% rename from spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json index c60dd521..5cb5e588 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -2,6 +2,7 @@ { "name": "spring.cloud.nacos.server-addr", "type": "java.lang.String", + "defaultValue": "localhost:8848", "description": "nacos server address." }, { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories similarity index 59% rename from spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories index 409c2720..6189df59 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/main/resources/META-INF/spring.factories @@ -1,8 +1,10 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration,\ + com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration,\ com.alibaba.cloud.nacos.ribbon.RibbonNacosAutoConfiguration,\ com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpointAutoConfiguration,\ - com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration,\ + com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration,\ + com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration,\ + com.alibaba.cloud.nacos.discovery.reactive.NacosReactiveDiscoveryClientConfiguration,\ com.alibaba.cloud.nacos.discovery.configclient.NacosConfigServerAutoConfiguration org.springframework.cloud.bootstrap.BootstrapConfiguration=\ com.alibaba.cloud.nacos.discovery.configclient.NacosDiscoveryClientConfigServiceBootstrapConfiguration diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java new file mode 100644 index 00000000..4f4a6aa7 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import java.util.List; + +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient; +import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import org.springframework.cloud.client.ServiceInstance; + +import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.when; + +/** + * @author xiaojing + * @author echooymxq + */ +@ExtendWith(MockitoExtension.class) +public class NacosDiscoveryClientTests { + + @Mock + private NacosServiceDiscovery serviceDiscovery; + + @Mock + private NacosServiceInstance serviceInstance; + + @InjectMocks + private NacosDiscoveryClient client; + + @Test + public void testGetInstances() throws Exception { + + when(serviceDiscovery.getInstances("service-1")) + .thenReturn(singletonList(serviceInstance)); + + List serviceInstances = client.getInstances("service-1"); + + assertThat(serviceInstances).isNotEmpty(); + + } + + @Test + public void testGetServices() throws Exception { + + when(serviceDiscovery.getServices()).thenReturn(singletonList("service-1")); + + List services = client.getServices(); + + assertThat(services).contains("service-1").size().isEqualTo(1); + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java new file mode 100644 index 00000000..9e1ce8ae --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author lyuzb + */ +@RunWith(SpringRunner.class) +@SpringBootTest( + classes = NacosDiscoveryPropertiesServerAddressBothLevelTests.TestConfig.class, + properties = { "spring.cloud.nacos.discovery.server-addr=321.321.321.321:8848", + "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, + webEnvironment = RANDOM_PORT) +public class NacosDiscoveryPropertiesServerAddressBothLevelTests { + + @Autowired + private NacosDiscoveryProperties properties; + + @Test + public void testGetServerAddr() { + assertThat(properties.getServerAddr()).isEqualTo("321.321.321.321:8848"); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java new file mode 100644 index 00000000..db90b57a --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java @@ -0,0 +1,64 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos; + +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.cloud.nacos.registry.NacosServiceRegistryAutoConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author lyuzb + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest( + classes = NacosDiscoveryPropertiesServerAddressTopLevelTests.TestConfig.class, + properties = { "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, + webEnvironment = RANDOM_PORT) + +public class NacosDiscoveryPropertiesServerAddressTopLevelTests { + + @Autowired + private NacosDiscoveryProperties properties; + + @Test + public void testGetServerAddr() { + assertThat(properties.getServerAddr()).isEqualTo("123.123.123.123:8848"); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfigurationTests.java new file mode 100644 index 00000000..ae04cee5 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryAutoConfigurationTests.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author echooymxq + **/ +public class NacosDiscoveryAutoConfigurationTests { + + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class)); + + @Test + public void testDefaultInitialization() { + contextRunner.run(context -> { + assertThat(context).hasSingleBean(NacosDiscoveryProperties.class); + assertThat(context).hasSingleBean(NacosServiceDiscovery.class); + }); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfigurationTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfigurationTest.java new file mode 100644 index 00000000..862799cd --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientConfigurationTest.java @@ -0,0 +1,63 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery; + +import org.junit.jupiter.api.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; +import org.springframework.context.annotation.Bean; +import org.springframework.scheduling.TaskScheduler; +import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author echooymxq + **/ +public class NacosDiscoveryClientConfigurationTest { + + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class, + NacosDiscoveryClientConfiguration.class, this.getClass())); + + @Bean + public TaskScheduler taskScheduler() { + return new ThreadPoolTaskScheduler(); + } + + @Test + public void testDefaultInitialization() { + contextRunner.run(context -> { + assertThat(context).hasSingleBean(DiscoveryClient.class); + assertThat(context).hasSingleBean(NacosWatch.class); + }); + } + + @Test + public void testDiscoveryBlockingDisabled() { + contextRunner.withPropertyValues("spring.cloud.discovery.blocking.enabled=false") + .run(context -> { + assertThat(context).doesNotHaveBean(DiscoveryClient.class); + assertThat(context).doesNotHaveBean(NacosWatch.class); + }); + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscoveryTest.java similarity index 83% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscoveryTest.java index fd5c108e..74404079 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/NacosServiceDiscoveryTest.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -14,19 +14,19 @@ * limitations under the License. */ -package com.alibaba.cloud.nacos; +package com.alibaba.cloud.nacos.discovery; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedList; import java.util.List; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; import com.alibaba.nacos.api.naming.pojo.ListView; - -import org.junit.Test; +import org.junit.jupiter.api.Test; import org.springframework.cloud.client.ServiceInstance; @@ -38,16 +38,18 @@ import static org.mockito.Mockito.when; /** * @author xiaojing - */ -public class NacosDiscoveryClientTests { + * @author echooymxq + **/ +public class NacosServiceDiscoveryTest { private String host = "123.123.123.123"; + private int port = 8888; + private String serviceName = "test-service"; @Test - public void testGetServers() throws Exception { - + public void testGetInstances() throws NacosException { ArrayList instances = new ArrayList<>(); HashMap map = new HashMap<>(); @@ -66,10 +68,10 @@ public class NacosDiscoveryClientTests { when(namingService.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true))) .thenReturn(instances); - NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( + NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery( nacosDiscoveryProperties); - List serviceInstances = discoveryClient + List serviceInstances = serviceDiscovery .getInstances(serviceName); assertThat(serviceInstances.size()).isEqualTo(1); @@ -83,12 +85,10 @@ public class NacosDiscoveryClientTests { assertThat(serviceInstance.getUri().toString()) .isEqualTo(getUri(serviceInstance)); assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); - } @Test - public void testGetAllService() throws Exception { - + public void testGetServices() throws NacosException { ListView nacosServices = new ListView<>(); nacosServices.setData(new LinkedList<>()); @@ -99,23 +99,23 @@ public class NacosDiscoveryClientTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); - NamingService namingService = mock(NamingService.class); - NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( - nacosDiscoveryProperties); + NamingService namingService = mock(NamingService.class); when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE), eq("DEFAULT"))).thenReturn(nacosServices); - List services = discoveryClient.getServices(); + NacosServiceDiscovery serviceDiscovery = new NacosServiceDiscovery( + nacosDiscoveryProperties); + + List services = serviceDiscovery.getServices(); assertThat(services.size()).isEqualTo(3); assertThat(services.contains(serviceName + "1")); assertThat(services.contains(serviceName + "2")); assertThat(services.contains(serviceName + "3")); - } private String getUri(ServiceInstance instance) { @@ -126,4 +126,5 @@ public class NacosDiscoveryClientTests { return "http://" + host + ":" + port; } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfigurationTests.java new file mode 100644 index 00000000..9700581e --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientConfigurationTests.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery.reactive; + +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration; +import org.junit.jupiter.api.Test; + +import org.springframework.boot.autoconfigure.AutoConfigurations; +import org.springframework.boot.test.context.runner.ApplicationContextRunner; +import org.springframework.cloud.client.discovery.ReactiveDiscoveryClient; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * @author echooymxq + **/ +public class NacosReactiveDiscoveryClientConfigurationTests { + + private ApplicationContextRunner contextRunner = new ApplicationContextRunner() + .withConfiguration(AutoConfigurations.of(UtilAutoConfiguration.class, + NacosDiscoveryAutoConfiguration.class, + NacosReactiveDiscoveryClientConfiguration.class)); + + @Test + public void testDefaultInitialization() { + contextRunner.run(context -> assertThat(context) + .hasSingleBean(ReactiveDiscoveryClient.class)); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientTests.java new file mode 100644 index 00000000..ff474fdc --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/discovery/reactive/NacosReactiveDiscoveryClientTests.java @@ -0,0 +1,74 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.discovery.reactive; + +import java.util.Arrays; + +import com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery; +import com.alibaba.nacos.api.exception.NacosException; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import reactor.core.publisher.Flux; +import reactor.test.StepVerifier; + +import org.springframework.cloud.client.ServiceInstance; + +import static java.util.Collections.singletonList; +import static org.mockito.Mockito.when; + +/** + * @author echooymxq + **/ +@ExtendWith(MockitoExtension.class) +class NacosReactiveDiscoveryClientTests { + + @Mock + private NacosServiceDiscovery serviceDiscovery; + + @Mock + private ServiceInstance serviceInstance; + + @InjectMocks + private NacosReactiveDiscoveryClient client; + + @Test + void testGetInstances() throws NacosException { + + when(serviceDiscovery.getInstances("reactive-service")) + .thenReturn(singletonList(serviceInstance)); + + Flux instances = this.client.getInstances("reactive-service"); + + StepVerifier.create(instances).expectNextCount(1).expectComplete().verify(); + } + + @Test + void testGetServices() throws NacosException { + + when(serviceDiscovery.getServices()) + .thenReturn(Arrays.asList("reactive-service1", "reactive-service2")); + + Flux services = this.client.getServices(); + + StepVerifier.create(services).expectNext("reactive-service1", "reactive-service2") + .expectComplete().verify(); + } + +} diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/MockNamingService.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/MockNamingService.java new file mode 100644 index 00000000..66753af7 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/MockNamingService.java @@ -0,0 +1,331 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.registry; + +import java.util.List; + +import com.alibaba.nacos.api.exception.NacosException; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.listener.EventListener; +import com.alibaba.nacos.api.naming.pojo.Instance; +import com.alibaba.nacos.api.naming.pojo.ListView; +import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import com.alibaba.nacos.api.selector.AbstractSelector; + +/** + * @author Jim + */ +public class MockNamingService implements NamingService { + + @Override + public void registerInstance(String serviceName, String ip, int port) + throws NacosException { + + } + + @Override + public void registerInstance(String serviceName, String groupName, String ip, + int port) throws NacosException { + + } + + @Override + public void registerInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + + } + + @Override + public void registerInstance(String serviceName, String groupName, String ip, + int port, String clusterName) throws NacosException { + + } + + @Override + public void registerInstance(String serviceName, Instance instance) + throws NacosException { + + } + + @Override + public void registerInstance(String serviceName, String groupName, Instance instance) + throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, String ip, int port) + throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, String groupName, String ip, + int port) throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, String ip, int port, + String clusterName) throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, String groupName, String ip, + int port, String clusterName) throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, Instance instance) + throws NacosException { + + } + + @Override + public void deregisterInstance(String serviceName, String groupName, + Instance instance) throws NacosException { + + } + + @Override + public List getAllInstances(String serviceName) throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, String groupName) + throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, boolean subscribe) + throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, String groupName, + boolean subscribe) throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, List clusters) + throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, String groupName, + List clusters) throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, List clusters, + boolean subscribe) throws NacosException { + return null; + } + + @Override + public List getAllInstances(String serviceName, String groupName, + List clusters, boolean subscribe) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, boolean healthy) + throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, String groupName, + boolean healthy) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, boolean healthy, + boolean subscribe) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, String groupName, + boolean healthy, boolean subscribe) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, String groupName, + List clusters, boolean healthy) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, List clusters, + boolean healthy, boolean subscribe) throws NacosException { + return null; + } + + @Override + public List selectInstances(String serviceName, String groupName, + List clusters, boolean healthy, boolean subscribe) + throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName) throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName) + throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, boolean subscribe) + throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + boolean subscribe) throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters) + throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + List clusters) throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, List clusters, + boolean subscribe) throws NacosException { + return null; + } + + @Override + public Instance selectOneHealthyInstance(String serviceName, String groupName, + List clusters, boolean subscribe) throws NacosException { + return null; + } + + @Override + public void subscribe(String serviceName, EventListener listener) + throws NacosException { + + } + + @Override + public void subscribe(String serviceName, String groupName, EventListener listener) + throws NacosException { + + } + + @Override + public void subscribe(String serviceName, List clusters, + EventListener listener) throws NacosException { + + } + + @Override + public void subscribe(String serviceName, String groupName, List clusters, + EventListener listener) throws NacosException { + + } + + @Override + public void unsubscribe(String serviceName, EventListener listener) + throws NacosException { + + } + + @Override + public void unsubscribe(String serviceName, String groupName, EventListener listener) + throws NacosException { + + } + + @Override + public void unsubscribe(String serviceName, List clusters, + EventListener listener) throws NacosException { + + } + + @Override + public void unsubscribe(String serviceName, String groupName, List clusters, + EventListener listener) throws NacosException { + + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize) + throws NacosException { + return null; + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + String groupName) throws NacosException { + return null; + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + AbstractSelector selector) throws NacosException { + return null; + } + + @Override + public ListView getServicesOfServer(int pageNo, int pageSize, + String groupName, AbstractSelector selector) throws NacosException { + return null; + } + + @Override + public List getSubscribeServices() throws NacosException { + return null; + } + + @Override + public String getServerStatus() { + return null; + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java similarity index 66% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java index f2611a66..dc8f5376 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,17 +16,25 @@ package com.alibaba.cloud.nacos.registry; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; +import java.util.Properties; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.nacos.api.NacosFactory; import org.junit.Test; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -37,18 +45,22 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author xiaojing */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848" }, webEnvironment = RANDOM_PORT) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosFactory.class }) +@SpringBootTest( + classes = NacosAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848" }, + webEnvironment = RANDOM_PORT) public class NacosAutoServiceRegistrationIpNetworkInterfaceTests { @Autowired @@ -63,23 +75,35 @@ public class NacosAutoServiceRegistrationIpNetworkInterfaceTests { @Autowired private InetUtils inetUtils; + static { + try { + Method method = PowerMockito.method(NacosFactory.class, "createNamingService", + Properties.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + return new MockNamingService(); + } + }); + } + catch (Exception e) { + e.printStackTrace(); + } + } + @Test public void contextLoads() throws Exception { - - assertNotNull("NacosRegistration was not created", registration); - assertNotNull("NacosDiscoveryProperties was not created", properties); - assertNotNull("NacosAutoServiceRegistration was not created", - nacosAutoServiceRegistration); + assertThat(registration).isNotNull(); + assertThat(properties).isNotNull(); + assertThat(nacosAutoServiceRegistration).isNotNull(); checkoutNacosDiscoveryServiceIP(); - } private void checkoutNacosDiscoveryServiceIP() { - assertEquals("NacosDiscoveryProperties service IP was wrong", - getIPFromNetworkInterface(TestConfig.netWorkInterfaceName), - registration.getHost()); - + assertThat(registration.getHost()) + .isEqualTo(getIPFromNetworkInterface(TestConfig.netWorkInterfaceName)); } private String getIPFromNetworkInterface(String networkInterface) { @@ -109,8 +133,8 @@ public class NacosAutoServiceRegistrationIpNetworkInterfaceTests { @Configuration @EnableAutoConfiguration @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) public static class TestConfig { static boolean hasValidNetworkInterface = false; @@ -144,6 +168,7 @@ public class NacosAutoServiceRegistrationIpNetworkInterfaceTests { } } + } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java similarity index 51% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java index 05ebf753..99fef767 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,12 +16,21 @@ package com.alibaba.cloud.nacos.registry; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Properties; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.nacos.api.NacosFactory; import org.junit.Test; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -31,19 +40,22 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author xiaojing */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosAutoServiceRegistrationIpTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.discovery.ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosFactory.class }) +@SpringBootTest(classes = NacosAutoServiceRegistrationIpTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.ip=123.123.123.123" }, + webEnvironment = RANDOM_PORT) public class NacosAutoServiceRegistrationIpTests { @Autowired @@ -55,29 +67,43 @@ public class NacosAutoServiceRegistrationIpTests { @Autowired private NacosDiscoveryProperties properties; + static { + try { + Method method = PowerMockito.method(NacosFactory.class, "createNamingService", + Properties.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + return new MockNamingService(); + } + }); + } + catch (Exception e) { + e.printStackTrace(); + } + } + @Test public void contextLoads() throws Exception { - - assertNotNull("NacosRegistration was not created", registration); - assertNotNull("NacosDiscoveryProperties was not created", properties); - assertNotNull("NacosAutoServiceRegistration was not created", - nacosAutoServiceRegistration); + assertThat(registration).isNotNull(); + assertThat(properties).isNotNull(); + assertThat(nacosAutoServiceRegistration).isNotNull(); checkoutNacosDiscoveryServiceIP(); - } private void checkoutNacosDiscoveryServiceIP() { - assertEquals("NacosDiscoveryProperties service IP was wrong", "123.123.123.123", - registration.getHost()); - + assertThat(registration.getHost()).isEqualTo("123.123.123.123"); } @Configuration @EnableAutoConfiguration @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java new file mode 100644 index 00000000..83989ca8 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationManagementPortTests.java @@ -0,0 +1,116 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.registry; + +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Properties; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.nacos.api.NacosFactory; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; + +/** + * @author xiaojing + */ + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosFactory.class }) +@SpringBootTest( + classes = NacosAutoServiceRegistrationManagementPortTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "management.server.port=8888", + "management.server.servlet.context-path=/test-context-path", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.port=8888" }, + webEnvironment = RANDOM_PORT) +public class NacosAutoServiceRegistrationManagementPortTests { + + @Autowired + private NacosRegistration registration; + + @Autowired + private NacosAutoServiceRegistration nacosAutoServiceRegistration; + + @Autowired + private NacosDiscoveryProperties properties; + + static { + try { + Method method = PowerMockito.method(NacosFactory.class, "createNamingService", + Properties.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + return new MockNamingService(); + } + }); + } + catch (Exception e) { + e.printStackTrace(); + } + } + + @Test + public void contextLoads() throws Exception { + assertThat(registration).isNotNull(); + assertThat(properties).isNotNull(); + assertThat(nacosAutoServiceRegistration).isNotNull(); + + checkoutNacosDiscoveryManagementData(); + } + + private void checkoutNacosDiscoveryManagementData() { + assertThat(properties.getMetadata().get(NacosRegistration.MANAGEMENT_PORT)) + .isEqualTo("8888"); + assertThat( + properties.getMetadata().get(NacosRegistration.MANAGEMENT_CONTEXT_PATH)) + .isEqualTo("/test-context-path"); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) + public static class TestConfig { + + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java similarity index 51% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java index 0492ea71..1c52b391 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,12 +16,21 @@ package com.alibaba.cloud.nacos.registry; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; +import java.util.Properties; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.alibaba.nacos.api.NacosFactory; import org.junit.Test; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -31,19 +40,22 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author xiaojing */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosAutoServiceRegistrationPortTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.discovery.port=8888" }, webEnvironment = RANDOM_PORT) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosFactory.class }) +@SpringBootTest(classes = NacosAutoServiceRegistrationPortTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.port=8888" }, + webEnvironment = RANDOM_PORT) public class NacosAutoServiceRegistrationPortTests { @Autowired @@ -55,29 +67,43 @@ public class NacosAutoServiceRegistrationPortTests { @Autowired private NacosDiscoveryProperties properties; + static { + try { + Method method = PowerMockito.method(NacosFactory.class, "createNamingService", + Properties.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + return new MockNamingService(); + } + }); + } + catch (Exception e) { + e.printStackTrace(); + } + } + @Test public void contextLoads() throws Exception { - - assertNotNull("NacosRegistration was not created", registration); - assertNotNull("NacosDiscoveryProperties was not created", properties); - assertNotNull("NacosAutoServiceRegistration was not created", - nacosAutoServiceRegistration); + assertThat(registration).isNotNull(); + assertThat(properties).isNotNull(); + assertThat(nacosAutoServiceRegistration).isNotNull(); checkoutNacosDiscoveryServicePort(); - } private void checkoutNacosDiscoveryServicePort() { - assertEquals("NacosDiscoveryProperties service Port was wrong", 8888, - registration.getPort()); - + assertThat(registration.getPort()).isEqualTo(8888); } @Configuration @EnableAutoConfiguration @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java similarity index 50% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java index 3d2c57b8..926afb17 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,15 +16,23 @@ package com.alibaba.cloud.nacos.registry; +import java.lang.reflect.InvocationHandler; +import java.lang.reflect.Method; import java.util.Map; +import java.util.Properties; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint; - +import com.alibaba.nacos.api.NacosFactory; import org.junit.Test; import org.junit.runner.RunWith; +import org.powermock.api.mockito.PowerMockito; +import org.powermock.api.support.MethodProxy; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.modules.junit4.PowerMockRunnerDelegate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -36,31 +44,34 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; +import static org.assertj.core.api.Assertions.assertThat; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author xiaojing */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = NacosAutoServiceRegistrationTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", - "spring.cloud.nacos.discovery.endpoint=test-endpoint", - "spring.cloud.nacos.discovery.namespace=test-namespace", - "spring.cloud.nacos.discovery.log-name=test-logName", - "spring.cloud.nacos.discovery.weight=2", - "spring.cloud.nacos.discovery.clusterName=test-cluster", - "spring.cloud.nacos.discovery.namingLoadCacheAtStart=true", - "spring.cloud.nacos.discovery.secure=true", - "spring.cloud.nacos.discovery.accessKey=test-accessKey", - "spring.cloud.nacos.discovery.secretKey=test-secretKey", - "spring.cloud.nacos.discovery.heart-beat-interval=3", - "spring.cloud.nacos.discovery.heart-beat-timeout=6", - "spring.cloud.nacos.discovery.ip-delete-timeout=9", }, webEnvironment = RANDOM_PORT) +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosFactory.class }) +@SpringBootTest(classes = NacosAutoServiceRegistrationTests.TestConfig.class, + properties = { "spring.application.name=myTestService1", + "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.endpoint=test-endpoint", + "spring.cloud.nacos.discovery.namespace=test-namespace", + "spring.cloud.nacos.discovery.log-name=test-logName", + "spring.cloud.nacos.discovery.weight=2", + "spring.cloud.nacos.discovery.clusterName=test-cluster", + "spring.cloud.nacos.discovery.namingLoadCacheAtStart=true", + "spring.cloud.nacos.discovery.secure=true", + "spring.cloud.nacos.discovery.accessKey=test-accessKey", + "spring.cloud.nacos.discovery.ip=8.8.8.8", + "spring.cloud.nacos.discovery.secretKey=test-secretKey", + "spring.cloud.nacos.discovery.heart-beat-interval=3", + "spring.cloud.nacos.discovery.heart-beat-timeout=6", + "spring.cloud.nacos.discovery.ip-delete-timeout=9" }, + webEnvironment = RANDOM_PORT) public class NacosAutoServiceRegistrationTests { @Autowired @@ -78,13 +89,28 @@ public class NacosAutoServiceRegistrationTests { @Autowired private InetUtils inetUtils; + static { + try { + Method method = PowerMockito.method(NacosFactory.class, "createNamingService", + Properties.class); + MethodProxy.proxy(method, new InvocationHandler() { + @Override + public Object invoke(Object proxy, Method method, Object[] args) + throws Throwable { + return new MockNamingService(); + } + }); + } + catch (Exception e) { + e.printStackTrace(); + } + } + @Test public void contextLoads() throws Exception { - - assertNotNull("NacosRegistration was not created", registration); - assertNotNull("NacosDiscoveryProperties was not created", properties); - assertNotNull("NacosAutoServiceRegistration was not created", - nacosAutoServiceRegistration); + assertThat(registration).isNotNull(); + assertThat(properties).isNotNull(); + assertThat(nacosAutoServiceRegistration).isNotNull(); checkoutNacosDiscoveryServerAddr(); checkoutNacosDiscoveryEndpoint(); @@ -111,112 +137,91 @@ public class NacosAutoServiceRegistrationTests { } private void checkAutoRegister() { - assertTrue("Nacos Auto Registration was not start", - nacosAutoServiceRegistration.isRunning()); + assertThat(nacosAutoServiceRegistration.isRunning()).isEqualTo(Boolean.TRUE); } private void checkoutNacosDiscoveryServerAddr() { - assertEquals("NacosDiscoveryProperties server address was wrong", - "127.0.0.1:8848", properties.getServerAddr()); - + assertThat(properties.getServerAddr()).isEqualTo("127.0.0.1:8848"); } private void checkoutNacosDiscoveryEndpoint() { - assertEquals("NacosDiscoveryProperties endpoint was wrong", "test-endpoint", - properties.getEndpoint()); - + assertThat(properties.getEndpoint()).isEqualTo("test-endpoint"); } private void checkoutNacosDiscoveryNamespace() { - assertEquals("NacosDiscoveryProperties namespace was wrong", "test-namespace", - properties.getNamespace()); - + assertThat(properties.getNamespace()).isEqualTo("test-namespace"); } private void checkoutNacosDiscoveryLogName() { - assertEquals("NacosDiscoveryProperties logName was wrong", "test-logName", - properties.getLogName()); + assertThat(properties.getLogName()).isEqualTo("test-logName"); } private void checkoutNacosDiscoveryWeight() { - assertEquals(2, properties.getWeight(), 0.00000001); + assertThat(properties.getWeight()).isEqualTo(2); } private void checkoutNacosDiscoveryClusterName() { - assertEquals("NacosDiscoveryProperties cluster was wrong", "test-cluster", - properties.getClusterName()); + assertThat(properties.getClusterName()).isEqualTo("test-cluster"); } private void checkoutNacosDiscoveryCache() { - assertEquals("NacosDiscoveryProperties naming load cache was wrong", "true", - properties.getNamingLoadCacheAtStart()); + assertThat(properties.getNamingLoadCacheAtStart()).isEqualTo("true"); } private void checkoutNacosDiscoverySecure() { - assertEquals("NacosDiscoveryProperties is secure was wrong", true, - properties.isSecure()); - assertEquals("NacosDiscoveryProperties is secure was wrong", "true", - properties.getMetadata().get("secure")); + assertThat(properties.isSecure()).isEqualTo(true); + assertThat(properties.getMetadata().get("secure")).isEqualTo("true"); } private void checkoutNacosDiscoveryAccessKey() { - assertEquals("NacosDiscoveryProperties is access key was wrong", "test-accessKey", - properties.getAccessKey()); + assertThat(properties.getAccessKey()).isEqualTo("test-accessKey"); } private void checkoutNacosDiscoverySecrectKey() { - assertEquals("NacosDiscoveryProperties is secret key was wrong", "test-secretKey", - properties.getSecretKey()); + assertThat(properties.getSecretKey()).isEqualTo("test-secretKey"); } private void checkoutNacosDiscoveryHeartBeatInterval() { - assertEquals("NacosDiscoveryProperties heart beat interval was wrong", - Integer.valueOf(3), properties.getHeartBeatInterval()); + assertThat(properties.getHeartBeatInterval()).isEqualTo(Integer.valueOf(3)); } private void checkoutNacosDiscoveryHeartBeatTimeout() { - assertEquals("NacosDiscoveryProperties heart beat timeout was wrong", - Integer.valueOf(6), properties.getHeartBeatTimeout()); + assertThat(properties.getHeartBeatTimeout()).isEqualTo(Integer.valueOf(6)); } private void checkoutNacosDiscoveryIpDeleteTimeout() { - assertEquals("NacosDiscoveryProperties ip delete timeout was wrong", - Integer.valueOf(9), properties.getIpDeleteTimeout()); + assertThat(properties.getIpDeleteTimeout()).isEqualTo(Integer.valueOf(9)); } private void checkoutNacosDiscoveryServiceName() { - assertEquals("NacosDiscoveryProperties service name was wrong", "myTestService1", - properties.getService()); - + assertThat(properties.getService()).isEqualTo("myTestService1"); } private void checkoutNacosDiscoveryServiceIP() { - assertEquals("NacosDiscoveryProperties service IP was wrong", - inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(), - registration.getHost()); - + assertThat(registration.getHost()).isEqualTo("8.8.8.8"); } private void checkoutNacosDiscoveryServicePort() { - assertEquals("NacosDiscoveryProperties service Port was wrong", port, - registration.getPort()); - + assertThat(registration.getPort()).isEqualTo(port); } private void checkoutEndpoint() throws Exception { NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint( properties); Map map = nacosDiscoveryEndpoint.nacosDiscovery(); - assertEquals(map.get("NacosDiscoveryProperties"), properties); - assertEquals(map.get("subscribe").toString(), - properties.namingServiceInstance().getSubscribeServices().toString()); + + assertThat(properties).isEqualTo(map.get("NacosDiscoveryProperties")); + // assertThat(properties.namingServiceInstance().getSubscribeServices().toString()) + // .isEqualTo(map.get("subscribe").toString()); } @Configuration @EnableAutoConfiguration @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, - NacosDiscoveryAutoConfiguration.class }) + NacosDiscoveryClientConfiguration.class, + NacosServiceRegistryAutoConfiguration.class }) public static class TestConfig { + } + } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java similarity index 71% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java index 87cfe8c6..0256f4fb 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java @@ -1,7 +1,22 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package com.alibaba.cloud.nacos.ribbon; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; import com.netflix.client.config.DefaultClientConfigImpl; import com.netflix.client.config.IClientConfig; import org.junit.Test; @@ -25,7 +40,7 @@ public class NacosRibbonClientConfigurationTests { private WebApplicationContextRunner contextRunner = new WebApplicationContextRunner() .withConfiguration(AutoConfigurations.of(NacosRibbonTestConfiguration.class, NacosRibbonClientConfiguration.class, - NacosDiscoveryClientAutoConfiguration.class, + NacosDiscoveryClientConfiguration.class, RibbonNacosAutoConfiguration.class)) .withPropertyValues("spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848") .withPropertyValues("spring.cloud.nacos.discovery.port=18080") diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientPropertyOverrideTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientPropertyOverrideTests.java new file mode 100644 index 00000000..3692414f --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientPropertyOverrideTests.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013-2017 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.nacos.ribbon; + +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientConfiguration; +import com.netflix.loadbalancer.ConfigurationBasedServerList; +import com.netflix.loadbalancer.Server; +import com.netflix.loadbalancer.ZoneAwareLoadBalancer; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.commons.util.UtilAutoConfiguration; +import org.springframework.cloud.netflix.archaius.ArchaiusAutoConfiguration; +import org.springframework.cloud.netflix.ribbon.RibbonClients; +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; + +/** + * @author liujunjie + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = NacosRibbonClientPropertyOverrideTests.TestConfiguration.class, + properties = { "spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848", + "spring.cloud.nacos.discovery.port=18080", + "spring.cloud.nacos.discovery.service=remoteApp", + "localApp.ribbon.NIWSServerListClassName=" + + "com.netflix.loadbalancer.ConfigurationBasedServerList", + "localApp.ribbon.listOfServers=127.0.0.1:19090", + "localApp.ribbon.ServerListRefreshInterval=15000" }) +public class NacosRibbonClientPropertyOverrideTests { + + @Autowired + private SpringClientFactory factory; + + @Test + public void serverListOverridesToTest() { + ConfigurationBasedServerList.class + .cast(getLoadBalancer("localApp").getServerListImpl()); + } + + @Test + public void serverListRemoteTest() { + NacosServerList.class.cast(getLoadBalancer("remoteApp").getServerListImpl()); + } + + @SuppressWarnings("unchecked") + private ZoneAwareLoadBalancer getLoadBalancer(String name) { + return (ZoneAwareLoadBalancer) this.factory.getLoadBalancer(name); + } + + @Configuration + @RibbonClients + @EnableAutoConfiguration + @ImportAutoConfiguration({ UtilAutoConfiguration.class, + PropertyPlaceholderAutoConfiguration.class, ArchaiusAutoConfiguration.class, + RibbonNacosAutoConfiguration.class, NacosDiscoveryClientConfiguration.class }) + protected static class TestConfiguration { + + } + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java similarity index 98% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java index 49b20ff2..1c6e65d9 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,7 +26,6 @@ import com.alibaba.cloud.nacos.NacosDiscoveryProperties; import com.alibaba.cloud.nacos.test.NacosMockTest; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; - import com.netflix.client.config.IClientConfig; import org.junit.Test; @@ -162,4 +161,5 @@ public class NacosServerListTests { assertThat(servers.get(0).getInstance().getMetadata().get("instanceNum")) .isEqualTo("1"); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java similarity index 89% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java index 7e7b51ab..f4c5ee85 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/CommonTestConfig.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,4 +33,5 @@ public class CommonTestConfig { RestTemplate loadBalancedRestTemplate() { return new RestTemplate(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java similarity index 88% rename from spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java index f97870de..a541fd23 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/test/NacosMockTest.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,11 @@ import com.alibaba.nacos.api.naming.pojo.Instance; /** * @author xiaojing */ -public class NacosMockTest { +public final class NacosMockTest { + + private NacosMockTest() { + + } public static Instance serviceInstance(String serviceName, boolean isHealthy, Map metadata) { @@ -46,4 +50,5 @@ public class NacosMockTest { instance.setMetadata(metadata); return instance; } + } diff --git a/spring-cloud-alibaba-seata/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/pom.xml similarity index 79% rename from spring-cloud-alibaba-seata/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/pom.xml index c7b5c434..90033cd3 100644 --- a/spring-cloud-alibaba-seata/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/pom.xml @@ -1,50 +1,19 @@ - + 4.0.0 com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml - 4.0.0 - spring-cloud-alibaba-seata - Spring Cloud Alibaba Seata + spring-cloud-starter-alibaba-seata + Spring Cloud Starter Alibaba Seata - - io.seata - seata-all - - - - org.springframework.cloud - spring-cloud-starter-openfeign - provided - true - - - com.alibaba.cloud - spring-cloud-starter-alibaba-sentinel - provided - true - - - - org.springframework.cloud - spring-cloud-commons - true - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - provided - true - - @@ -55,41 +24,77 @@ org.springframework.boot spring-boot-actuator - provided true org.springframework.boot spring-boot-actuator-autoconfigure - provided true org.springframework.boot spring-boot-configuration-processor - provided true org.springframework.boot spring-boot - provided true org.springframework.boot spring-boot-autoconfigure - provided true + org.springframework.boot spring-boot-starter-web - provided + true + + + + org.springframework.boot + spring-boot-starter + true + + + + io.seata + seata-spring-boot-starter + + + + org.springframework.cloud + spring-cloud-starter-openfeign + true + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-sentinel + true + + + + org.springframework.cloud + spring-cloud-commons + true + + + + + + + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon true @@ -98,7 +103,7 @@ spring-boot-starter-test test - + diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java similarity index 87% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java index 4218c767..e737c0e0 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataBeanPostProcessor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,7 @@ import org.springframework.beans.factory.config.BeanPostProcessor; /** * @author xiaojing */ -final class SeataBeanPostProcessor implements BeanPostProcessor { +public class SeataBeanPostProcessor implements BeanPostProcessor { private final SeataFeignObjectWrapper seataFeignObjectWrapper; @@ -41,4 +41,5 @@ final class SeataBeanPostProcessor implements BeanPostProcessor { throws BeansException { return bean; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java similarity index 94% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java index e214bddd..37c35c26 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataContextBeanPostProcessor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,6 +27,7 @@ import org.springframework.cloud.openfeign.FeignContext; public class SeataContextBeanPostProcessor implements BeanPostProcessor { private final BeanFactory beanFactory; + private SeataFeignObjectWrapper seataFeignObjectWrapper; SeataContextBeanPostProcessor(BeanFactory beanFactory) { @@ -56,4 +57,5 @@ public class SeataContextBeanPostProcessor implements BeanPostProcessor { } return this.seataFeignObjectWrapper; } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBlockingLoadBalancerClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBlockingLoadBalancerClient.java new file mode 100644 index 00000000..b504ccc8 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBlockingLoadBalancerClient.java @@ -0,0 +1,45 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.seata.feign; + +import java.io.IOException; + +import feign.Client; +import feign.Request; +import feign.Response; + +import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; +import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; + +/** + * @author yuhuangbin + */ +public class SeataFeignBlockingLoadBalancerClient + extends FeignBlockingLoadBalancerClient { + + public SeataFeignBlockingLoadBalancerClient(Client delegate, + BlockingLoadBalancerClient loadBalancerClient, + SeataFeignObjectWrapper seataFeignObjectWrapper) { + super((Client) seataFeignObjectWrapper.wrap(delegate), loadBalancerClient); + } + + @Override + public Response execute(Request request, Request.Options options) throws IOException { + return super.execute(request, options); + } + +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java similarity index 88% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java index 9a6fd1c3..73e1dbed 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,4 +31,5 @@ final class SeataFeignBuilder { static Feign.Builder builder(BeanFactory beanFactory) { return Feign.builder().client(new SeataFeignClient(beanFactory)); } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java similarity index 94% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java index 5b125beb..5bcaebca 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,7 +37,9 @@ import org.springframework.util.StringUtils; public class SeataFeignClient implements Client { private final Client delegate; + private final BeanFactory beanFactory; + private static final int MAP_SIZE = 16; SeataFeignClient(BeanFactory beanFactory) { @@ -76,4 +78,4 @@ public class SeataFeignClient implements Client { request.charset()); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java similarity index 96% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java index 11f0d76c..98f670ea 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -80,6 +80,7 @@ public class SeataFeignClientAutoConfiguration { SeataFeignObjectWrapper seataFeignObjectWrapper(BeanFactory beanFactory) { return new SeataFeignObjectWrapper(beanFactory); } + } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java similarity index 94% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java index 1922d719..b0723f5a 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,12 +24,12 @@ import feign.Client; import org.springframework.cloud.openfeign.FeignContext; /** - * * @author xiaojing */ public class SeataFeignContext extends FeignContext { private final SeataFeignObjectWrapper seataFeignObjectWrapper; + private final FeignContext delegate; SeataFeignContext(SeataFeignObjectWrapper seataFeignObjectWrapper, @@ -65,4 +65,5 @@ public class SeataFeignContext extends FeignContext { } return convertedInstances; } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java similarity index 72% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java index 21175518..ae505058 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,9 +17,13 @@ package com.alibaba.cloud.seata.feign; import feign.Client; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; import org.springframework.beans.factory.BeanFactory; +import org.springframework.cloud.loadbalancer.blocking.client.BlockingLoadBalancerClient; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.openfeign.loadbalancer.FeignBlockingLoadBalancerClient; import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; @@ -28,9 +32,12 @@ import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; */ public class SeataFeignObjectWrapper { + private static final Log LOG = LogFactory.getLog(SeataFeignObjectWrapper.class); + private final BeanFactory beanFactory; private CachingSpringLoadBalancerFactory cachingSpringLoadBalancerFactory; + private SpringClientFactory springClientFactory; SeataFeignObjectWrapper(BeanFactory beanFactory) { @@ -42,7 +49,12 @@ public class SeataFeignObjectWrapper { if (bean instanceof LoadBalancerFeignClient) { LoadBalancerFeignClient client = ((LoadBalancerFeignClient) bean); return new SeataLoadBalancerFeignClient(client.getDelegate(), factory(), - clientFactory(), this.beanFactory); + clientFactory(), this); + } + if (bean instanceof FeignBlockingLoadBalancerClient) { + FeignBlockingLoadBalancerClient client = (FeignBlockingLoadBalancerClient) bean; + return new SeataFeignBlockingLoadBalancerClient(client.getDelegate(), + beanFactory.getBean(BlockingLoadBalancerClient.class), this); } return new SeataFeignClient(this.beanFactory, (Client) bean); } @@ -64,4 +76,5 @@ public class SeataFeignObjectWrapper { } return this.springClientFactory; } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java similarity index 89% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java index 3ffd78db..98fb605f 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -34,4 +34,5 @@ final class SeataHystrixFeignBuilder { return HystrixFeign.builder().retryer(Retryer.NEVER_RETRY) .client(new SeataFeignClient(beanFactory)); } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java new file mode 100644 index 00000000..8204fed8 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataLoadBalancerFeignClient.java @@ -0,0 +1,48 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.seata.feign; + +import java.io.IOException; + +import feign.Client; +import feign.Request; +import feign.Response; + +import org.springframework.cloud.netflix.ribbon.SpringClientFactory; +import org.springframework.cloud.openfeign.ribbon.CachingSpringLoadBalancerFactory; +import org.springframework.cloud.openfeign.ribbon.LoadBalancerFeignClient; + +/** + * @author xiaojing + * @author yuhuangbin + */ +public class SeataLoadBalancerFeignClient extends LoadBalancerFeignClient { + + SeataLoadBalancerFeignClient(Client delegate, + CachingSpringLoadBalancerFactory lbClientFactory, + SpringClientFactory clientFactory, + SeataFeignObjectWrapper seataFeignObjectWrapper) { + super((Client) seataFeignObjectWrapper.wrap(delegate), lbClientFactory, + clientFactory); + } + + @Override + public Response execute(Request request, Request.Options options) throws IOException { + return super.execute(request, options); + } + +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java similarity index 90% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java index 9c3615e6..f7ef15ed 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,7 +17,6 @@ package com.alibaba.cloud.seata.feign; import com.alibaba.cloud.sentinel.feign.SentinelFeign; - import feign.Feign; import feign.Retryer; @@ -35,4 +34,5 @@ final class SeataSentinelFeignBuilder { return SentinelFeign.builder().retryer(Retryer.NEVER_RETRY) .client(new SeataFeignClient(beanFactory)); } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java similarity index 90% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java index a6739269..e3295ed1 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.seata.feign.hystrix; import com.netflix.hystrix.HystrixCommand; @@ -24,7 +25,6 @@ import org.springframework.context.annotation.Configuration; /** * @author xiaojing */ - @Configuration @ConditionalOnClass(HystrixCommand.class) public class SeataHystrixAutoConfiguration { @@ -34,4 +34,4 @@ public class SeataHystrixAutoConfiguration { return new SeataHystrixConcurrencyStrategy(); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java similarity index 94% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java index fdd8497d..59253059 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.seata.feign.hystrix; import java.util.concurrent.Callable; @@ -77,4 +78,5 @@ public class SeataHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy } } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java similarity index 70% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java index 7dc05fde..40c37af3 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateAutoConfiguration.java @@ -1,26 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java similarity index 93% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java index 97680aa0..829ef079 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,6 +31,7 @@ import org.springframework.util.StringUtils; * @author xiaojing */ public class SeataRestTemplateInterceptor implements ClientHttpRequestInterceptor { + @Override public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] bytes, ClientHttpRequestExecution clientHttpRequestExecution) throws IOException { @@ -43,4 +44,5 @@ public class SeataRestTemplateInterceptor implements ClientHttpRequestIntercepto } return clientHttpRequestExecution.execute(requestWrapper, bytes); } + } diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java similarity index 96% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java index cc37590b..dcc0b28c 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java similarity index 90% rename from spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java index efe097b1..10aa3858 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptorConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -30,4 +30,5 @@ public class SeataHandlerInterceptorConfiguration implements WebMvcConfigurer { public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new SeataHandlerInterceptor()).addPathPatterns("/**"); } + } diff --git a/spring-cloud-alibaba-seata/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/resources/META-INF/spring.factories similarity index 84% rename from spring-cloud-alibaba-seata/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/resources/META-INF/spring.factories index ae993684..54b578ae 100644 --- a/spring-cloud-alibaba-seata/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-seata/src/main/resources/META-INF/spring.factories @@ -1,7 +1,6 @@ org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ com.alibaba.cloud.seata.rest.SeataRestTemplateAutoConfiguration,\ com.alibaba.cloud.seata.web.SeataHandlerInterceptorConfiguration,\ -com.alibaba.cloud.seata.GlobalTransactionAutoConfiguration,\ com.alibaba.cloud.seata.feign.SeataFeignClientAutoConfiguration,\ com.alibaba.cloud.seata.feign.hystrix.SeataHystrixAutoConfiguration diff --git a/spring-cloud-alibaba-sentinel/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/pom.xml similarity index 87% rename from spring-cloud-alibaba-sentinel/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/pom.xml index 2e1bec42..dcacddfa 100644 --- a/spring-cloud-alibaba-sentinel/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/pom.xml @@ -1,19 +1,92 @@ - + 4.0.0 com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml - 4.0.0 - spring-cloud-alibaba-sentinel - Spring Cloud Alibaba Sentinel + spring-cloud-starter-alibaba-sentinel + Spring Cloud Starter Alibaba Sentinel + + + org.springframework.boot + spring-boot-starter-aop + true + + + + org.springframework.boot + spring-boot-actuator + true + + + + org.springframework.boot + spring-boot-actuator-autoconfigure + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + + org.springframework.boot + spring-boot + true + + + + org.springframework.boot + spring-boot-autoconfigure + true + + + + org.springframework.boot + spring-boot-starter + true + + + + org.springframework.boot + spring-boot-starter-web + true + + + + org.springframework.boot + spring-boot-starter-webflux + true + + + + org.springframework.cloud + spring-cloud-starter-openfeign + true + + + + org.springframework.cloud + spring-cloud-commons + true + + + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + true + + com.alibaba.csp sentinel-transport-simple-http @@ -30,52 +103,25 @@ true + + com.alibaba.cloud + spring-cloud-circuitbreaker-sentinel + + com.alibaba.csp sentinel-apache-dubbo-adapter true - - com.alibaba.csp - sentinel-web-servlet - - - - org.springframework.boot - spring-boot-starter-web - true - - com.alibaba.csp sentinel-spring-webflux-adapter - org.springframework.boot - spring-boot-starter-webflux - true - - - - org.springframework.cloud - spring-cloud-starter-openfeign - provided - true - - - - org.springframework.cloud - spring-cloud-commons - true - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - provided - true + com.alibaba.csp + sentinel-spring-webmvc-adapter @@ -83,6 +129,12 @@ sentinel-parameter-flow-control + + com.alibaba.csp + sentinel-api-gateway-adapter-common + true + + com.alibaba.csp sentinel-cluster-server-default @@ -101,55 +153,6 @@ com.fasterxml.jackson.dataformat jackson-dataformat-xml - provided - - - - com.alibaba.csp - sentinel-api-gateway-adapter-common - true - - - - - - org.springframework.boot - spring-boot-starter-aop - - - - org.springframework.boot - spring-boot-actuator - provided - true - - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - - org.springframework.boot - spring-boot - provided - true - - - - org.springframework.boot - spring-boot-autoconfigure - provided - true diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java new file mode 100644 index 00000000..dd6b3dc6 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelConstants.java @@ -0,0 +1,68 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel; + +/** + * @author fangjian + */ +public final class SentinelConstants { + + /** + * Prefix of {@link SentinelProperties}. + */ + public static final String PROPERTY_PREFIX = "spring.cloud.sentinel"; + + /** + * Block page key. + */ + public static final String BLOCK_PAGE_URL_CONF_KEY = "csp.sentinel.web.servlet.block.page"; + + /** + * Block type. + */ + public static final String BLOCK_TYPE = "block"; + + /** + * Fallback type. + */ + public static final String FALLBACK_TYPE = "fallback"; + + /** + * UrlCleaner type. + */ + public static final String URLCLEANER_TYPE = "urlCleaner"; + + /** + * The cold factor. + */ + public static final String COLD_FACTOR = "3"; + + /** + * The charset. + */ + public static final String CHARSET = "UTF-8"; + + /** + * The Sentinel api port. + */ + public static final String API_PORT = "8719"; + + private SentinelConstants() { + throw new AssertionError("Must not instantiate constant utility class"); + } + +} diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java similarity index 85% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java index ac10d2b4..b6322c6f 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,6 +16,7 @@ package com.alibaba.cloud.sentinel; +import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.TreeMap; @@ -26,7 +27,9 @@ import com.alibaba.csp.sentinel.log.LogBase; import com.alibaba.csp.sentinel.transport.config.TransportConfig; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.DeprecatedConfigurationProperty; import org.springframework.core.Ordered; +import org.springframework.util.StringUtils; import org.springframework.validation.annotation.Validated; /** @@ -52,6 +55,11 @@ public class SentinelProperties { */ private boolean enabled = true; + /** + * The process page when the flow control is triggered. + */ + private String blockPage; + /** * Configurations about datasource, like 'nacos', 'apollo', 'file', 'zookeeper'. */ @@ -75,7 +83,7 @@ public class SentinelProperties { private Servlet servlet = new Servlet(); /** - * Sentinel filter when the application is web, the configuration is effective. + * Sentinel interceptor when the application is web, the configuration is effective. */ private Filter filter = new Filter(); @@ -174,12 +182,23 @@ public class SentinelProperties { this.httpMethodSpecify = httpMethodSpecify; } + public String getBlockPage() { + if (StringUtils.hasText(this.blockPage)) { + return this.blockPage; + } + return this.servlet.getBlockPage(); + } + + public void setBlockPage(String blockPage) { + this.blockPage = blockPage; + } + public static class Flow { /** * The cold factor {@link SentinelConfig#COLD_FACTOR}. */ - private String coldFactor = "3"; + private String coldFactor = SentinelConstants.COLD_FACTOR; public String getColdFactor() { return coldFactor; @@ -198,13 +217,19 @@ public class SentinelProperties { */ private String blockPage; + @Deprecated + @DeprecatedConfigurationProperty( + reason = "replaced to SentinelProperties#blockPage.", + replacement = SentinelConstants.PROPERTY_PREFIX + ".block-page") public String getBlockPage() { return blockPage; } + @Deprecated public void setBlockPage(String blockPage) { this.blockPage = blockPage; } + } public static class Metric { @@ -223,7 +248,7 @@ public class SentinelProperties { * Charset when sentinel write or search metric file. * {@link SentinelConfig#CHARSET} */ - private String charset = "UTF-8"; + private String charset = SentinelConstants.CHARSET; public String getFileSingleSize() { return fileSingleSize; @@ -248,6 +273,7 @@ public class SentinelProperties { public void setCharset(String charset) { this.charset = charset; } + } public static class Transport { @@ -255,7 +281,7 @@ public class SentinelProperties { /** * Sentinel api port, default value is 8719 {@link TransportConfig#SERVER_PORT}. */ - private String port = "8719"; + private String port = SentinelConstants.API_PORT; /** * Sentinel dashboard address, won't try to connect dashboard when address is @@ -306,23 +332,24 @@ public class SentinelProperties { public void setClientIp(String clientIp) { this.clientIp = clientIp; } + } public static class Filter { /** - * Sentinel filter chain order. + * SentinelWebInterceptor order, will be register to InterceptorRegistry. */ private int order = Ordered.HIGHEST_PRECEDENCE; /** - * URL pattern for sentinel filter, default is /* + * URL pattern for SentinelWebInterceptor, default is /**. */ - private List urlPatterns; + private List urlPatterns = Arrays.asList("/**"); /** * Enable to instance - * {@link com.alibaba.csp.sentinel.adapter.servlet.CommonFilter}. + * {@link com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor}. */ private boolean enabled = true; @@ -349,6 +376,7 @@ public class SentinelProperties { public void setEnabled(boolean enabled) { this.enabled = enabled; } + } public static class Log { diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java new file mode 100644 index 00000000..d2e89ddc --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebAutoConfiguration.java @@ -0,0 +1,120 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel; + +import java.util.Optional; + +import com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.UrlCleaner; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; +import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication.Type; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.util.StringUtils; +import org.springframework.web.servlet.config.annotation.InterceptorRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * @author xiaojing + * @author yuhuangbin + */ +@Configuration +@ConditionalOnWebApplication(type = Type.SERVLET) +@ConditionalOnProperty(name = "spring.cloud.sentinel.enabled", matchIfMissing = true) +@ConditionalOnClass(SentinelWebInterceptor.class) +@EnableConfigurationProperties(SentinelProperties.class) +public class SentinelWebAutoConfiguration implements WebMvcConfigurer { + + private static final Logger log = LoggerFactory + .getLogger(SentinelWebAutoConfiguration.class); + + @Autowired + private SentinelProperties properties; + + @Autowired + private Optional urlCleanerOptional; + + @Autowired + private Optional blockExceptionHandlerOptional; + + @Autowired + private Optional requestOriginParserOptional; + + @Autowired + private Optional sentinelWebInterceptorOptional; + + @Override + public void addInterceptors(InterceptorRegistry registry) { + if (!sentinelWebInterceptorOptional.isPresent()) { + return; + } + SentinelProperties.Filter filterConfig = properties.getFilter(); + registry.addInterceptor(sentinelWebInterceptorOptional.get()) + .order(filterConfig.getOrder()) + .addPathPatterns(filterConfig.getUrlPatterns()); + log.info( + "[Sentinel Starter] register SentinelWebInterceptor with urlPatterns: {}.", + filterConfig.getUrlPatterns()); + } + + @Bean + @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", + matchIfMissing = true) + public SentinelWebInterceptor sentinelWebInterceptor( + SentinelWebMvcConfig sentinelWebMvcConfig) { + return new SentinelWebInterceptor(sentinelWebMvcConfig); + } + + @Bean + @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", + matchIfMissing = true) + public SentinelWebMvcConfig sentinelWebMvcConfig() { + SentinelWebMvcConfig sentinelWebMvcConfig = new SentinelWebMvcConfig(); + sentinelWebMvcConfig.setHttpMethodSpecify(properties.getHttpMethodSpecify()); + + if (blockExceptionHandlerOptional.isPresent()) { + blockExceptionHandlerOptional + .ifPresent(sentinelWebMvcConfig::setBlockExceptionHandler); + } + else { + if (StringUtils.hasText(properties.getBlockPage())) { + sentinelWebMvcConfig.setBlockExceptionHandler(((request, response, + e) -> response.sendRedirect(properties.getBlockPage()))); + } + else { + sentinelWebMvcConfig + .setBlockExceptionHandler(new DefaultBlockExceptionHandler()); + } + } + + urlCleanerOptional.ifPresent(sentinelWebMvcConfig::setUrlCleaner); + requestOriginParserOptional.ifPresent(sentinelWebMvcConfig::setOriginParser); + return sentinelWebMvcConfig; + } + +} diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java similarity index 95% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java index 431a2ac1..e42133c3 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,7 +27,6 @@ import com.alibaba.csp.sentinel.adapter.spring.webflux.SentinelWebFluxFilter; import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager; import com.alibaba.csp.sentinel.adapter.spring.webflux.exception.SentinelBlockExceptionHandler; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -58,6 +57,7 @@ public class SentinelWebFluxAutoConfiguration { .getLogger(SentinelWebFluxAutoConfiguration.class); private final List viewResolvers; + private final ServerCodecConfigurer serverCodecConfigurer; @Autowired @@ -77,17 +77,19 @@ public class SentinelWebFluxAutoConfiguration { @Bean @Order(-2) - @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", + matchIfMissing = true) public SentinelBlockExceptionHandler sentinelBlockExceptionHandler() { return new SentinelBlockExceptionHandler(viewResolvers, serverCodecConfigurer); } @Bean @Order(-1) - @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", matchIfMissing = true) + @ConditionalOnProperty(name = "spring.cloud.sentinel.filter.enabled", + matchIfMissing = true) public SentinelWebFluxFilter sentinelWebFluxFilter() { log.info("[Sentinel Starter] register Sentinel SentinelWebFluxFilter"); return new SentinelWebFluxFilter(); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java similarity index 91% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java index 039c9b16..d7d00965 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -41,4 +41,5 @@ public @interface SentinelRestTemplate { String urlCleaner() default ""; Class urlCleanerClass() default void.class; + } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java similarity index 93% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java index c543802e..7bb1bf4d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -27,8 +27,14 @@ import com.alibaba.csp.sentinel.util.StringUtil; */ final class BlockClassRegistry { + private BlockClassRegistry() { + + } + private static final Map FALLBACK_MAP = new ConcurrentHashMap<>(); + private static final Map BLOCK_HANDLER_MAP = new ConcurrentHashMap<>(); + private static final Map URL_CLEANER_MAP = new ConcurrentHashMap<>(); static Method lookupFallback(Class clazz, String name) { diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java similarity index 95% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java index bfcdcd52..3d8d362c 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,6 @@ import javax.annotation.PostConstruct; import com.alibaba.cloud.sentinel.SentinelProperties; import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; -import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig; import com.alibaba.csp.sentinel.annotation.aspectj.SentinelResourceAspect; import com.alibaba.csp.sentinel.config.SentinelConfig; import com.alibaba.csp.sentinel.init.InitExecutor; @@ -33,7 +32,6 @@ import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; import com.alibaba.csp.sentinel.slots.system.SystemRule; import com.alibaba.csp.sentinel.transport.config.TransportConfig; import com.alibaba.csp.sentinel.util.AppNameUtil; - import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; @@ -51,6 +49,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; +import static com.alibaba.cloud.sentinel.SentinelConstants.BLOCK_PAGE_URL_CONF_KEY; +import static com.alibaba.csp.sentinel.config.SentinelConfig.setConfig; + /** * @author xiaojing * @author jiashuai.xie @@ -125,8 +126,8 @@ public class SentinelAutoConfiguration { System.setProperty(SentinelConfig.COLD_FACTOR, properties.getFlow().getColdFactor()); } - if (StringUtils.hasText(properties.getServlet().getBlockPage())) { - WebServletConfig.setBlockPage(properties.getServlet().getBlockPage()); + if (StringUtils.hasText(properties.getBlockPage())) { + setConfig(BLOCK_PAGE_URL_CONF_KEY, properties.getBlockPage()); } // earlier initialize @@ -145,7 +146,8 @@ public class SentinelAutoConfiguration { @Bean @ConditionalOnMissingBean @ConditionalOnClass(name = "org.springframework.web.client.RestTemplate") - @ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", matchIfMissing = true) + @ConditionalOnProperty(name = "resttemplate.sentinel.enabled", havingValue = "true", + matchIfMissing = true) public SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { return new SentinelBeanPostProcessor(applicationContext); @@ -237,6 +239,7 @@ public class SentinelAutoConfiguration { } } + } } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java similarity index 90% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java index 10baa943..79eff6ce 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,7 +23,6 @@ import java.util.concurrent.ConcurrentHashMap; import com.alibaba.cloud.sentinel.SentinelConstants; import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; import com.alibaba.csp.sentinel.slots.block.BlockException; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -34,8 +33,8 @@ import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.support.MergedBeanDefinitionPostProcessor; import org.springframework.beans.factory.support.RootBeanDefinition; import org.springframework.context.ApplicationContext; +import org.springframework.core.type.MethodMetadata; import org.springframework.core.type.StandardMethodMetadata; -import org.springframework.core.type.classreading.MethodMetadataReadingVisitor; import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpResponse; @@ -44,7 +43,8 @@ import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; /** - * PostProcessor handle @SentinelRestTemplate Annotation, add interceptor for RestTemplate + * PostProcessor handle @SentinelRestTemplate Annotation, add interceptor for + * RestTemplate. * * @author Jim * @see SentinelRestTemplate @@ -66,7 +66,7 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces @Override public void postProcessMergedBeanDefinition(RootBeanDefinition beanDefinition, Class beanType, String beanName) { - if (checkSentinelProtect(beanDefinition, beanType)) { + if (checkSentinelProtect(beanDefinition, beanType, beanName)) { SentinelRestTemplate sentinelRestTemplate; if (beanDefinition.getSource() instanceof StandardMethodMetadata) { sentinelRestTemplate = ((StandardMethodMetadata) beanDefinition @@ -166,28 +166,21 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces } private boolean checkSentinelProtect(RootBeanDefinition beanDefinition, - Class beanType) { - return beanType == RestTemplate.class - && (checkStandardMethodMetadata(beanDefinition) - || checkMethodMetadataReadingVisitor(beanDefinition)); - } - - private boolean checkStandardMethodMetadata(RootBeanDefinition beanDefinition) { - return beanDefinition.getSource() instanceof StandardMethodMetadata - && ((StandardMethodMetadata) beanDefinition.getSource()) - .isAnnotated(SentinelRestTemplate.class.getName()); + Class beanType, String beanName) { + return beanName != null && beanType == RestTemplate.class + && checkMethodMetadataReadingVisitor(beanDefinition); } private boolean checkMethodMetadataReadingVisitor(RootBeanDefinition beanDefinition) { - return beanDefinition.getSource() instanceof MethodMetadataReadingVisitor - && ((MethodMetadataReadingVisitor) beanDefinition.getSource()) + return beanDefinition.getSource() instanceof MethodMetadata + && ((MethodMetadata) beanDefinition.getSource()) .isAnnotated(SentinelRestTemplate.class.getName()); } @Override public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException { - if (cache.containsKey(beanName)) { + if (beanName != null && cache.containsKey(beanName)) { // add interceptor for each RestTemplate with @SentinelRestTemplate annotation StringBuilder interceptorBeanNamePrefix = new StringBuilder(); SentinelRestTemplate sentinelRestTemplate = cache.get(beanName); @@ -227,4 +220,4 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces interceptorBeanDefinition); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java similarity index 100% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java similarity index 99% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java index eeae2998..2de7727c 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java @@ -29,7 +29,6 @@ import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; import com.alibaba.csp.sentinel.datasource.AbstractDataSource; import com.alibaba.csp.sentinel.datasource.ReadableDataSource; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -42,7 +41,7 @@ import org.springframework.util.StringUtils; /** * Sentinel {@link ReadableDataSource} Handler Handle the configurations of - * 'spring.cloud.sentinel.datasource' + * 'spring.cloud.sentinel.datasource'. * * @author Jim * @see SentinelProperties#datasource @@ -57,7 +56,9 @@ public class SentinelDataSourceHandler implements SmartInitializingSingleton { private List dataTypeList = Arrays.asList("json", "xml"); private final String DATA_TYPE_FIELD = "dataType"; + private final String CUSTOM_DATA_TYPE = "custom"; + private final String CONVERTER_CLASS_FIELD = "converterClass"; private final DefaultListableBeanFactory beanFactory; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java similarity index 95% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java index 1c81e3ef..fbd468b2 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -37,7 +37,7 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.web.client.RestTemplate; /** - * Interceptor using by SentinelRestTemplate + * Interceptor using by SentinelRestTemplate. * * @author Jim */ @@ -73,7 +73,8 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor hostWithPathResource); } - Entry hostEntry = null, hostWithPathEntry = null; + Entry hostEntry = null; + Entry hostWithPathEntry = null; ClientHttpResponse response = null; try { hostEntry = SphU.entry(hostResource, EntryType.OUT); diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java similarity index 90% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java index bb1e1331..c1f38a85 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,7 +20,6 @@ import java.util.HashMap; import java.util.Map; import com.alibaba.cloud.sentinel.SentinelProperties; -import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig; import com.alibaba.csp.sentinel.config.SentinelConfig; import com.alibaba.csp.sentinel.log.LogBase; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRuleManager; @@ -34,8 +33,11 @@ import com.alibaba.csp.sentinel.util.AppNameUtil; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; +import static com.alibaba.cloud.sentinel.SentinelConstants.BLOCK_PAGE_URL_CONF_KEY; + /** - * Endpoint for Sentinel, contains ans properties and rules + * Endpoint for Sentinel, contains ans properties and rules. + * * @author xiaojing */ @Endpoint(id = "sentinel") @@ -55,7 +57,7 @@ public class SentinelEndpoint { result.put("appName", AppNameUtil.getAppName()); result.put("logDir", LogBase.getLogBaseDir()); result.put("logUsePid", LogBase.isLogNameUsePid()); - result.put("blockPage", WebServletConfig.getBlockPage()); + result.put("blockPage", SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY)); result.put("metricsFileSize", SentinelConfig.singleMetricFileSize()); result.put("metricsFileCharset", SentinelConfig.charset()); result.put("totalMetricsFileCount", SentinelConfig.totalMetricFileCount()); diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java similarity index 94% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java index e268e11e..caa5afd2 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -49,4 +49,5 @@ public class SentinelEndpointAutoConfiguration { SentinelProperties sentinelProperties) { return new SentinelHealthIndicator(beanFactory, sentinelProperties); } + } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java similarity index 92% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java index 72dc9bf9..2d9466b3 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -74,7 +74,7 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator { // detail if (!sentinelProperties.isEnabled()) { detailMap.put("enabled", false); - withDetails(builder.up(), detailMap); + builder.up().withDetails(detailMap); return; } @@ -139,16 +139,11 @@ public class SentinelHealthIndicator extends AbstractHealthIndicator { // If Dashboard and DataSource are both OK, the health status is UP if (dashboardUp && dataSourceUp) { - withDetails(builder.up(), detailMap); + builder.up().withDetails(detailMap); } else { - withDetails(builder.down(), detailMap); + builder.down().withDetails(detailMap); } } - private void withDetails(Health.Builder builder, Map detailMap) { - for (String key : detailMap.keySet()) { - builder.withDetail(key, detailMap.get(key)); - } - } } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java similarity index 82% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java index b83fbfd9..4c16165d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -26,7 +26,7 @@ import feign.MethodMetadata; /** * * Using static field {@link SentinelContractHolder#METADATA_MAP} to hold - * {@link MethodMetadata} data + * {@link MethodMetadata} data. * * @author Jim */ @@ -45,8 +45,8 @@ public class SentinelContractHolder implements Contract { } @Override - public List parseAndValidatateMetadata(Class targetType) { - List metadatas = delegate.parseAndValidatateMetadata(targetType); + public List parseAndValidateMetadata(Class targetType) { + List metadatas = delegate.parseAndValidateMetadata(targetType); metadatas.forEach(metadata -> METADATA_MAP .put(targetType.getName() + metadata.configKey(), metadata)); return metadatas; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java similarity index 87% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java index f3849798..5b2f89d8 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,13 +33,18 @@ import org.springframework.cloud.openfeign.FeignContext; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; /** - * {@link Feign.Builder} like {@link HystrixFeign.Builder} + * {@link Feign.Builder} like {@link HystrixFeign.Builder}. * * @author Jim */ -public class SentinelFeign { +public final class SentinelFeign { + + private SentinelFeign() { + + } public static Builder builder() { return new Builder(); @@ -82,20 +87,24 @@ public class SentinelFeign { "fallback"); Class fallbackFactory = (Class) getFieldValue(feignClientFactoryBean, "fallbackFactory"); - String name = (String) getFieldValue(feignClientFactoryBean, "name"); + String beanName = (String) getFieldValue(feignClientFactoryBean, + "contextId"); + if (!StringUtils.hasText(beanName)) { + beanName = (String) getFieldValue(feignClientFactoryBean, "name"); + } Object fallbackInstance; FallbackFactory fallbackFactoryInstance; // check fallback and fallbackFactory properties if (void.class != fallback) { - fallbackInstance = getFromContext(name, "fallback", fallback, + fallbackInstance = getFromContext(beanName, "fallback", fallback, target.type()); return new SentinelInvocationHandler(target, dispatch, new FallbackFactory.Default(fallbackInstance)); } if (void.class != fallbackFactory) { - fallbackFactoryInstance = (FallbackFactory) getFromContext(name, - "fallbackFactory", fallbackFactory, + fallbackFactoryInstance = (FallbackFactory) getFromContext( + beanName, "fallbackFactory", fallbackFactory, FallbackFactory.class); return new SentinelInvocationHandler(target, dispatch, fallbackFactoryInstance); @@ -144,6 +153,7 @@ public class SentinelFeign { this.applicationContext = applicationContext; feignContext = this.applicationContext.getBean(FeignContext.class); } + } } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java similarity index 92% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java index 5f393e6d..a3e2831d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,7 +17,6 @@ package com.alibaba.cloud.sentinel.feign; import com.alibaba.csp.sentinel.SphU; - import feign.Feign; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java similarity index 95% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java index 2693a796..e5f80a62 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -29,7 +29,6 @@ import com.alibaba.csp.sentinel.SphU; import com.alibaba.csp.sentinel.Tracer; import com.alibaba.csp.sentinel.context.ContextUtil; import com.alibaba.csp.sentinel.slots.block.BlockException; - import feign.Feign; import feign.InvocationHandlerFactory.MethodHandler; import feign.MethodMetadata; @@ -39,16 +38,18 @@ import feign.hystrix.FallbackFactory; import static feign.Util.checkNotNull; /** - * {@link InvocationHandler} handle invocation that protected by Sentinel + * {@link InvocationHandler} handle invocation that protected by Sentinel. * * @author Jim */ public class SentinelInvocationHandler implements InvocationHandler { private final Target target; + private final Map dispatch; private FallbackFactory fallbackFactory; + private Map fallbackMethodMap; SentinelInvocationHandler(Target target, Map dispatch, @@ -70,8 +71,7 @@ public class SentinelInvocationHandler implements InvocationHandler { if ("equals".equals(method.getName())) { try { Object otherHandler = args.length > 0 && args[0] != null - ? Proxy.getInvocationHandler(args[0]) - : null; + ? Proxy.getInvocationHandler(args[0]) : null; return equals(otherHandler); } catch (IllegalArgumentException e) { @@ -93,13 +93,13 @@ public class SentinelInvocationHandler implements InvocationHandler { MethodMetadata methodMetadata = SentinelContractHolder.METADATA_MAP .get(hardCodedTarget.type().getName() + Feign.configKey(hardCodedTarget.type(), method)); + // resource default is HttpMethod:protocol://url if (methodMetadata == null) { result = methodHandler.invoke(args); } else { - // resource default is HttpMethod:protocol://url String resourceName = methodMetadata.template().method().toUpperCase() - + ":" + hardCodedTarget.url() + methodMetadata.template().url(); + + ":" + hardCodedTarget.url() + methodMetadata.template().path(); Entry entry = null; try { ContextUtil.enter(resourceName); diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java similarity index 94% rename from spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java index 36dcab4d..3822d46a 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -33,7 +33,7 @@ import org.springframework.http.MediaType; import org.springframework.http.client.AbstractClientHttpResponse; /** - * Using by {@link SentinelRestTemplate} and {@link SentinelProtectInterceptor} + * Using by {@link SentinelRestTemplate} and {@link SentinelProtectInterceptor}. * * @author Jim */ @@ -77,4 +77,5 @@ public class SentinelClientHttpResponse extends AbstractClientHttpResponse { httpHeaders.putAll(headers); return httpHeaders; } + } diff --git a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json similarity index 88% rename from spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 5134a9b6..93acd7e5 100644 --- a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -43,13 +43,13 @@ "name": "spring.cloud.sentinel.filter.order", "type": "java.lang.Integer", "defaultValue": "Integer.MIN_VALUE", - "description": "sentinel filter chain order, will be set to FilterRegistrationBean." + "description": "SentinelWebInterceptor order, will be register to InterceptorRegistry." }, { "name": "spring.cloud.sentinel.filter.enabled", "type": "java.lang.Boolean", "defaultValue": true, - "description": "Enable to instance com.alibaba.csp.sentinel.adapter.servlet.CommonFilter." + "description": "Enable to register com.alibaba.csp.sentinel.adapter.spring.webmvc.SentinelWebInterceptor." }, { "name": "spring.cloud.sentinel.metric.charset", @@ -79,27 +79,32 @@ "description": "log file should with pid." }, { - "name": "spring.cloud.sentinel.servlet.blockPage", + "name": "spring.cloud.sentinel.block-page", "type": "java.lang.String", "description": "the process page when the flow control is triggered." }, + { + "name": "spring.cloud.sentinel.servlet.block-page", + "type": "java.lang.String", + "description": "recommoned use spring.cloud.sentinel.block-page." + }, { "name": "spring.cloud.sentinel.flow.coldFactor", "type": "java.lang.String", "defaultValue": "3", "description": "sentinel the cold factor." }, - { - "defaultValue": "false", - "name": "feign.sentinel.enabled", - "description": "If true, an OpenFeign client will be wrapped with a Sentinel circuit breaker.", - "type": "java.lang.Boolean" - }, { "name": "management.health.sentinel.enabled", "type": "java.lang.Boolean", "description": "Whether to enable sentinel health check.", "defaultValue": true + }, + { + "defaultValue": "false", + "name": "feign.sentinel.enabled", + "description": "If true, an OpenFeign client will be wrapped with a Sentinel circuit breaker.", + "type": "java.lang.Boolean" } ] } diff --git a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/spring.factories similarity index 99% rename from spring-cloud-alibaba-sentinel/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/spring.factories index 8d07d335..9ce988d8 100644 --- a/spring-cloud-alibaba-sentinel/src/main/resources/META-INF/spring.factories +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/main/resources/META-INF/spring.factories @@ -4,5 +4,6 @@ com.alibaba.cloud.sentinel.SentinelWebFluxAutoConfiguration,\ com.alibaba.cloud.sentinel.endpoint.SentinelEndpointAutoConfiguration,\ com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration,\ com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration + org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker=\ com.alibaba.cloud.sentinel.custom.SentinelCircuitBreakerConfiguration diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/ContextIdSentinelFeignTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/ContextIdSentinelFeignTests.java new file mode 100644 index 00000000..7bd67724 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/ContextIdSentinelFeignTests.java @@ -0,0 +1,136 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel; + +import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration; +import org.junit.Test; +import org.junit.runner.RunWith; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.EnableAutoConfiguration; +import org.springframework.boot.autoconfigure.ImportAutoConfiguration; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.cloud.openfeign.EnableFeignClients; +import org.springframework.cloud.openfeign.FeignClient; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Add this unit test to verify https://github.com/alibaba/spring-cloud-alibaba/pull/838. + * + * @author Jim + */ +@RunWith(SpringRunner.class) +@SpringBootTest(classes = { ContextIdSentinelFeignTests.TestConfig.class }, + properties = { "feign.sentinel.enabled=true" }) +public class ContextIdSentinelFeignTests { + + @Autowired + private EchoService echoService; + + @Autowired + private FooService fooService; + + @Test + public void testFeignClient() { + assertThat(echoService.echo("test")).isEqualTo("echo fallback"); + assertThat(fooService.echo("test")).isEqualTo("foo fallback"); + assertThat(fooService.toString()).isNotEqualTo(echoService.toString()); + assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode()); + assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE); + } + + @Configuration + @EnableAutoConfiguration + @ImportAutoConfiguration({ SentinelFeignAutoConfiguration.class }) + @EnableFeignClients + public static class TestConfig { + + } + + @FeignClient(contextId = "echoService", name = "service-provider", + fallback = EchoServiceFallback.class, + configuration = FeignConfiguration.class) + public interface EchoService { + + @GetMapping("/echo/{str}") + String echo(@PathVariable("str") String str); + + } + + @FeignClient(contextId = "fooService", value = "foo-service", + fallbackFactory = CustomFallbackFactory.class, + configuration = FeignConfiguration.class) + public interface FooService { + + @RequestMapping(path = "echo/{str}") + String echo(@RequestParam("str") String param); + + } + + public static class FeignConfiguration { + + @Bean + public EchoServiceFallback echoServiceFallback() { + return new EchoServiceFallback(); + } + + @Bean + public CustomFallbackFactory customFallbackFactory() { + return new CustomFallbackFactory(); + } + + } + + public static class EchoServiceFallback implements EchoService { + + @Override + public String echo(@RequestParam("str") String param) { + return "echo fallback"; + } + + } + + public static class FooServiceFallback implements FooService { + + @Override + public String echo(@RequestParam("str") String param) { + return "foo fallback"; + } + + } + + public static class CustomFallbackFactory + implements feign.hystrix.FallbackFactory { + + private FooService fooService = new FooServiceFallback(); + + @Override + public FooService create(Throwable throwable) { + return fooService; + } + + } + +} diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java similarity index 53% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java index 5a0ba2e3..ae67bd38 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -24,7 +24,6 @@ import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration; import com.alibaba.cloud.sentinel.custom.SentinelBeanPostProcessor; import com.alibaba.cloud.sentinel.endpoint.SentinelEndpoint; import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; -import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig; import com.alibaba.csp.sentinel.config.SentinelConfig; import com.alibaba.csp.sentinel.log.LogBase; import com.alibaba.csp.sentinel.slots.block.BlockException; @@ -34,7 +33,6 @@ import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.alibaba.csp.sentinel.transport.config.TransportConfig; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -44,7 +42,6 @@ import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.http.HttpRequest; @@ -56,9 +53,9 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static com.alibaba.cloud.sentinel.SentinelConstants.BLOCK_PAGE_URL_CONF_KEY; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; @@ -67,28 +64,25 @@ import static org.springframework.boot.test.context.SpringBootTest.WebEnvironmen * @author jiashuai.xie */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { - SentinelAutoConfigurationTests.TestConfig.class }, properties = { - "spring.cloud.sentinel.filter.order=123", +@SpringBootTest(classes = { SentinelAutoConfigurationTests.TestConfig.class }, + properties = { "spring.cloud.sentinel.filter.order=123", "spring.cloud.sentinel.filter.urlPatterns=/*,/test", "spring.cloud.sentinel.metric.fileSingleSize=9999", "spring.cloud.sentinel.metric.fileTotalCount=100", - "spring.cloud.sentinel.servlet.blockPage=/error", + "spring.cloud.sentinel.blockPage=/error", "spring.cloud.sentinel.flow.coldFactor=3", "spring.cloud.sentinel.eager=true", "spring.cloud.sentinel.log.switchPid=true", "spring.cloud.sentinel.transport.dashboard=http://localhost:8080", "spring.cloud.sentinel.transport.port=9999", "spring.cloud.sentinel.transport.clientIp=1.1.1.1", - "spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, webEnvironment = RANDOM_PORT) + "spring.cloud.sentinel.transport.heartbeatIntervalMs=20000" }, + webEnvironment = RANDOM_PORT) public class SentinelAutoConfigurationTests { @Autowired private SentinelProperties sentinelProperties; - @Autowired - private FilterRegistrationBean filterRegistrationBean; - @Autowired private SentinelBeanPostProcessor sentinelBeanPostProcessor; @@ -132,10 +126,7 @@ public class SentinelAutoConfigurationTests { @Test public void contextLoads() throws Exception { - assertNotNull("FilterRegistrationBean was not created", filterRegistrationBean); - assertNotNull("SentinelProperties was not created", sentinelProperties); - assertNotNull("SentinelBeanPostProcessor was not created", - sentinelBeanPostProcessor); + assertThat(sentinelBeanPostProcessor).isNotNull(); checkSentinelLog(); checkSentinelEager(); @@ -149,139 +140,104 @@ public class SentinelAutoConfigurationTests { private void checkEndpoint() { SentinelEndpoint sentinelEndpoint = new SentinelEndpoint(sentinelProperties); Map map = sentinelEndpoint.invoke(); - assertEquals("Endpoint Sentinel log pid was wrong", true, map.get("logUsePid")); - assertEquals("Endpoint Sentinel transport console server was wrong", - "http://localhost:8080", map.get("consoleServer")); - assertEquals("Endpoint Sentinel transport port was wrong", "9999", - map.get("clientPort")); - assertEquals("Endpoint Sentinel transport heartbeatIntervalMs was wrong", 20000l, - map.get("heartbeatIntervalMs")); - assertEquals("Endpoint Sentinel transport clientIp was wrong", "1.1.1.1", - map.get("clientIp")); - assertEquals("Endpoint Sentinel metric file size was wrong", 9999l, - map.get("metricsFileSize")); - assertEquals("Endpoint Sentinel metric file count was wrong", 100, - map.get("totalMetricsFileCount")); - assertEquals("Endpoint Sentinel metric file charset was wrong", "UTF-8", - map.get("metricsFileCharset")); - assertEquals("Endpoint Sentinel block page was wrong", "/error", - map.get("blockPage")); + + assertThat(map.get("logUsePid")).isEqualTo(Boolean.TRUE); + assertThat(map.get("consoleServer")).isEqualTo("http://localhost:8080"); + assertThat(map.get("clientPort")).isEqualTo("9999"); + assertThat(map.get("heartbeatIntervalMs")).isEqualTo(20000L); + assertThat(map.get("clientIp")).isEqualTo("1.1.1.1"); + assertThat(map.get("metricsFileSize")).isEqualTo(9999L); + assertThat(map.get("totalMetricsFileCount")).isEqualTo(100); + assertThat(map.get("metricsFileCharset")).isEqualTo("UTF-8"); + assertThat(map.get("blockPage")).isEqualTo("/error"); } private void checkSentinelFilter() { - assertEquals("SentinelProperties filter order was wrong", 123, - sentinelProperties.getFilter().getOrder()); - assertEquals("SentinelProperties filter url pattern size was wrong", 2, - sentinelProperties.getFilter().getUrlPatterns().size()); - assertEquals("SentinelProperties filter url pattern item was wrong", "/*", - sentinelProperties.getFilter().getUrlPatterns().get(0)); - assertEquals("SentinelProperties filter url pattern item was wrong", "/test", - sentinelProperties.getFilter().getUrlPatterns().get(1)); + assertThat(sentinelProperties.getFilter().getOrder()).isEqualTo(123); + assertThat(sentinelProperties.getFilter().getUrlPatterns().size()).isEqualTo(2); + assertThat(sentinelProperties.getFilter().getUrlPatterns().get(0)) + .isEqualTo("/*"); + assertThat(sentinelProperties.getFilter().getUrlPatterns().get(1)) + .isEqualTo("/test"); } private void checkSentinelMetric() { - assertEquals("SentinelProperties metric charset was wrong", "UTF-8", - sentinelProperties.getMetric().getCharset()); - assertEquals("SentinelProperties metric file single size was wrong", "9999", - sentinelProperties.getMetric().getFileSingleSize()); - assertEquals("SentinelProperties metric file total count was wrong", "100", - sentinelProperties.getMetric().getFileTotalCount()); + assertThat(sentinelProperties.getMetric().getCharset()).isEqualTo("UTF-8"); + assertThat(sentinelProperties.getMetric().getFileSingleSize()).isEqualTo("9999"); + assertThat(sentinelProperties.getMetric().getFileTotalCount()).isEqualTo("100"); } private void checkSentinelColdFactor() { - assertEquals("SentinelProperties coldFactor was wrong", "3", - sentinelProperties.getFlow().getColdFactor()); + assertThat(sentinelProperties.getFlow().getColdFactor()).isEqualTo("3"); } private void checkSentinelTransport() { - assertEquals("SentinelProperties transport port was wrong", "9999", - sentinelProperties.getTransport().getPort()); - assertEquals("SentinelProperties transport dashboard was wrong", - "http://localhost:8080", - sentinelProperties.getTransport().getDashboard()); - assertEquals("SentinelProperties transport clientIp was wrong", "1.1.1.1", - sentinelProperties.getTransport().getClientIp()); - assertEquals("SentinelProperties transport heartbeatIntervalMs was wrong", - "20000", sentinelProperties.getTransport().getHeartbeatIntervalMs()); + assertThat(sentinelProperties.getTransport().getPort()).isEqualTo("9999"); + assertThat(sentinelProperties.getTransport().getDashboard()) + .isEqualTo("http://localhost:8080"); + assertThat(sentinelProperties.getTransport().getClientIp()).isEqualTo("1.1.1.1"); + assertThat(sentinelProperties.getTransport().getHeartbeatIntervalMs()) + .isEqualTo("20000"); } private void checkSentinelEager() { - assertEquals("SentinelProperties eager was wrong", true, - sentinelProperties.isEager()); + assertThat(sentinelProperties.isEager()).isEqualTo(true); } private void checkSentinelLog() { - assertEquals("SentinelProperties log file pid was wrong", true, - sentinelProperties.getLog().isSwitchPid()); - } - - @Test - public void testFilter() { - assertEquals("Sentinel Filter order was wrong", filterRegistrationBean.getOrder(), - 123); - assertEquals("Sentinel Filter url-pattern was wrong", - filterRegistrationBean.getUrlPatterns().size(), 2); + assertThat(sentinelProperties.getLog().isSwitchPid()).isEqualTo(true); } @Test public void testSentinelSystemProperties() { - assertEquals("Sentinel log pid was wrong", true, LogBase.isLogNameUsePid()); - assertEquals("Sentinel transport console server was wrong", - "http://localhost:8080", TransportConfig.getConsoleServer()); - assertEquals("Sentinel transport port was wrong", "9999", - TransportConfig.getPort()); - assertEquals("Sentinel transport heartbeatIntervalMs was wrong", 20000l, - TransportConfig.getHeartbeatIntervalMs().longValue()); - assertEquals("Sentinel transport clientIp was wrong", "1.1.1.1", - TransportConfig.getHeartbeatClientIp()); - assertEquals("Sentinel metric file size was wrong", 9999, - SentinelConfig.singleMetricFileSize()); - assertEquals("Sentinel metric file count was wrong", 100, - SentinelConfig.totalMetricFileCount()); - assertEquals("Sentinel metric file charset was wrong", "UTF-8", - SentinelConfig.charset()); - assertEquals("Sentinel block page was wrong", "/error", - WebServletConfig.getBlockPage()); + assertThat(LogBase.isLogNameUsePid()).isEqualTo(true); + assertThat(TransportConfig.getConsoleServer()).isEqualTo("http://localhost:8080"); + assertThat(TransportConfig.getPort()).isEqualTo("9999"); + assertThat(TransportConfig.getHeartbeatIntervalMs().longValue()) + .isEqualTo(20000L); + assertThat(TransportConfig.getHeartbeatClientIp()).isEqualTo("1.1.1.1"); + assertThat(SentinelConfig.singleMetricFileSize()).isEqualTo(9999); + assertThat(SentinelConfig.totalMetricFileCount()).isEqualTo(100); + assertThat(SentinelConfig.charset()).isEqualTo("UTF-8"); + assertThat(SentinelConfig.getConfig(BLOCK_PAGE_URL_CONF_KEY)).isEqualTo("/error"); } @Test public void testFlowRestTemplate() { - assertEquals("RestTemplate interceptors size was wrong", 2, - restTemplate.getInterceptors().size()); - assertEquals("RestTemplateWithBlockClass interceptors size was wrong", 1, - restTemplateWithBlockClass.getInterceptors().size()); + + assertThat(restTemplate.getInterceptors().size()).isEqualTo(2); + assertThat(restTemplateWithBlockClass.getInterceptors().size()).isEqualTo(1); + ResponseEntity responseEntityBlock = restTemplateWithBlockClass .getForEntity(flowUrl, String.class); - assertEquals("RestTemplateWithBlockClass Sentinel Block Message was wrong", - "Oops", responseEntityBlock.getBody()); - assertEquals( - "RestTemplateWithBlockClass Sentinel Block Http Status Code was wrong", - HttpStatus.OK, responseEntityBlock.getStatusCode()); + + assertThat(responseEntityBlock.getBody()).isEqualTo("Oops"); + assertThat(responseEntityBlock.getStatusCode()).isEqualTo(HttpStatus.OK); + ResponseEntity responseEntityRaw = restTemplate.getForEntity(flowUrl, String.class); - assertEquals("RestTemplate Sentinel Block Message was wrong", - "RestTemplate request block by sentinel", responseEntityRaw.getBody()); - assertEquals("RestTemplate Sentinel Block Http Status Code was wrong", - HttpStatus.OK, responseEntityRaw.getStatusCode()); + + assertThat(responseEntityRaw.getBody()) + .isEqualTo("RestTemplate request block by sentinel"); + assertThat(responseEntityRaw.getStatusCode()).isEqualTo(HttpStatus.OK); } @Test public void testNormalRestTemplate() { - assertEquals("RestTemplateWithoutBlockClass interceptors size was wrong", 0, - restTemplateWithoutBlockClass.getInterceptors().size()); - assertThatExceptionOfType(RestClientException.class).isThrownBy(() -> { + assertThat(restTemplateWithoutBlockClass.getInterceptors().size()).isEqualTo(0); + + assertThatThrownBy(() -> { restTemplateWithoutBlockClass.getForEntity(flowUrl, String.class); - }); + }).isInstanceOf(RestClientException.class); } @Test public void testFallbackRestTemplate() { ResponseEntity responseEntity = restTemplateWithFallbackClass .getForEntity(degradeUrl, String.class); - assertEquals("RestTemplateWithFallbackClass Sentinel Message was wrong", - "Oops fallback", responseEntity.getBody()); - assertEquals("RestTemplateWithFallbackClass Sentinel Http Status Code was wrong", - HttpStatus.OK, responseEntity.getStatusCode()); + + assertThat(responseEntity.getBody()).isEqualTo("Oops fallback"); + assertThat(responseEntity.getStatusCode()).isEqualTo(HttpStatus.OK); } @Configuration @@ -296,13 +252,15 @@ public class SentinelAutoConfigurationTests { } @Bean - @SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, blockHandler = "handleException") + @SentinelRestTemplate(blockHandlerClass = ExceptionUtil.class, + blockHandler = "handleException") RestTemplate restTemplateWithBlockClass() { return new RestTemplate(); } @Bean - @SentinelRestTemplate(fallbackClass = ExceptionUtil.class, fallback = "fallbackException") + @SentinelRestTemplate(fallbackClass = ExceptionUtil.class, + fallback = "fallbackException") RestTemplate restTemplateWithFallbackClass() { return new RestTemplate(); } @@ -315,6 +273,7 @@ public class SentinelAutoConfigurationTests { } public static class ExceptionUtil { + public static SentinelClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) { System.out.println("Oops: " + ex.getClass().getCanonicalName()); @@ -326,6 +285,7 @@ public class SentinelAutoConfigurationTests { System.out.println("Oops: " + ex.getClass().getCanonicalName()); return new SentinelClientHttpResponse("Oops fallback"); } + } @Configuration @@ -333,6 +293,7 @@ public class SentinelAutoConfigurationTests { @ImportAutoConfiguration({ SentinelAutoConfiguration.class, SentinelWebAutoConfiguration.class, SentinelTestConfiguration.class }) public static class TestConfig { + } } diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java similarity index 52% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java index 7913ca18..899dde60 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,19 +16,14 @@ package com.alibaba.cloud.sentinel; -import java.io.IOException; - import javax.servlet.http.HttpServletRequest; -import javax.servlet.http.HttpServletResponse; import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration; -import com.alibaba.csp.sentinel.adapter.servlet.callback.RequestOriginParser; -import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler; -import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlCleaner; -import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager; -import com.alibaba.csp.sentinel.adapter.servlet.util.FilterUtil; -import com.alibaba.csp.sentinel.slots.block.BlockException; - +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.RequestOriginParser; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.UrlCleaner; +import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig; import org.junit.Test; import org.junit.runner.RunWith; @@ -40,22 +35,21 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class }, properties = { - "spring.cloud.sentinel.filter.order=111" }) +@SpringBootTest(classes = { SentinelBeanAutowiredTests.TestConfig.class }, + properties = { "spring.cloud.sentinel.filter.order=111" }) public class SentinelBeanAutowiredTests { @Autowired private UrlCleaner urlCleaner; @Autowired - private UrlBlockHandler urlBlockHandler; + private BlockExceptionHandler blockExceptionHandler; @Autowired private RequestOriginParser requestOriginParser; @@ -63,33 +57,32 @@ public class SentinelBeanAutowiredTests { @Autowired private SentinelProperties sentinelProperties; + @Autowired + private SentinelWebMvcConfig sentinelWebMvcConfig; + @Test public void contextLoads() throws Exception { - assertNotNull("UrlCleaner was not created", urlCleaner); - assertNotNull("UrlBlockHandler was not created", urlBlockHandler); - assertNotNull("RequestOriginParser was not created", requestOriginParser); - assertNotNull("SentinelProperties was not created", sentinelProperties); + assertThat(urlCleaner).isNotNull(); + assertThat(blockExceptionHandler).isNotNull(); + assertThat(requestOriginParser).isNotNull(); + assertThat(sentinelProperties).isNotNull(); checkUrlPattern(); } private void checkUrlPattern() { - assertEquals("SentinelProperties filter order was wrong", 111, - sentinelProperties.getFilter().getOrder()); - assertEquals("SentinelProperties filter url pattern size was wrong", 1, - sentinelProperties.getFilter().getUrlPatterns().size()); - assertEquals("SentinelProperties filter url pattern was wrong", "/*", - sentinelProperties.getFilter().getUrlPatterns().get(0)); + assertThat(sentinelProperties.getFilter().getOrder()).isEqualTo(111); + assertThat(sentinelProperties.getFilter().getUrlPatterns().size()).isEqualTo(1); + assertThat(sentinelProperties.getFilter().getUrlPatterns().get(0)) + .isEqualTo("/**"); } @Test public void testBeanAutowired() { - assertEquals("UrlCleaner was not autowired", urlCleaner, - WebCallbackManager.getUrlCleaner()); - assertEquals("UrlBlockHandler was not autowired", urlBlockHandler, - WebCallbackManager.getUrlBlockHandler()); - assertEquals("RequestOriginParser was not autowired", requestOriginParser, - WebCallbackManager.getRequestOriginParser()); + assertThat(sentinelWebMvcConfig.getUrlCleaner()).isEqualTo(urlCleaner); + assertThat(sentinelWebMvcConfig.getBlockExceptionHandler()) + .isEqualTo(blockExceptionHandler); + assertThat(sentinelWebMvcConfig.getOriginParser()).isEqualTo(requestOriginParser); } @Configuration @@ -119,15 +112,8 @@ public class SentinelBeanAutowiredTests { } @Bean - public UrlBlockHandler urlBlockHandler() { - return new UrlBlockHandler() { - @Override - public void blocked(HttpServletRequest httpServletRequest, - HttpServletResponse httpServletResponse, BlockException e) - throws IOException { - FilterUtil.blockRequest(httpServletRequest, httpServletResponse); - } - }; + public BlockExceptionHandler blockExceptionHandler() { + return new DefaultBlockExceptionHandler(); } } diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java similarity index 64% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java index 571f4cb0..21340cfb 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +18,6 @@ package com.alibaba.cloud.sentinel; import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration; import com.alibaba.cloud.sentinel.datasource.RuleType; - import org.junit.Test; import org.junit.runner.RunWith; @@ -29,9 +28,7 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim @@ -63,38 +60,31 @@ public class SentinelDataSourceTests { @Test public void contextLoads() throws Exception { - assertNotNull("SentinelProperties was not created", sentinelProperties); + assertThat(sentinelProperties).isNotNull(); checkUrlPattern(); } private void checkUrlPattern() { - assertEquals("SentinelProperties filter order was wrong", Integer.MIN_VALUE, - sentinelProperties.getFilter().getOrder()); - assertEquals("SentinelProperties filter url pattern size was wrong", 1, - sentinelProperties.getFilter().getUrlPatterns().size()); - assertEquals("SentinelProperties filter url pattern was wrong", "/*", - sentinelProperties.getFilter().getUrlPatterns().get(0)); + assertThat(sentinelProperties.getFilter().getOrder()) + .isEqualTo(Integer.MIN_VALUE); + assertThat(sentinelProperties.getFilter().getUrlPatterns().size()).isEqualTo(1); + assertThat(sentinelProperties.getFilter().getUrlPatterns().get(0)) + .isEqualTo("/**"); } @Test public void testDataSource() { - assertEquals("DataSource size was wrong", 5, - sentinelProperties.getDatasource().size()); - assertNull("DataSource ds1 apollo is not null", - sentinelProperties.getDatasource().get("ds1").getApollo()); - assertNull("DataSource ds1 nacos is not null", - sentinelProperties.getDatasource().get("ds1").getNacos()); - assertNull("DataSource ds1 zk is not null", - sentinelProperties.getDatasource().get("ds1").getZk()); - assertNotNull("DataSource ds1 file is null", - sentinelProperties.getDatasource().get("ds1").getFile()); - - assertEquals("DataSource ds1 file dataType was wrong", "json", - sentinelProperties.getDatasource().get("ds1").getFile().getDataType()); - assertEquals("DataSource ds1 file ruleType was wrong", RuleType.FLOW, - sentinelProperties.getDatasource().get("ds1").getFile().getRuleType()); + assertThat(sentinelProperties.getDatasource().size()).isEqualTo(5); + assertThat(sentinelProperties.getDatasource().get("ds1").getApollo()).isNull(); + assertThat(sentinelProperties.getDatasource().get("ds1").getNacos()).isNull(); + assertThat(sentinelProperties.getDatasource().get("ds1").getZk()).isNull(); + assertThat(sentinelProperties.getDatasource().get("ds1").getFile()).isNotNull(); + assertThat(sentinelProperties.getDatasource().get("ds1").getFile().getDataType()) + .isEqualTo("json"); + assertThat(sentinelProperties.getDatasource().get("ds1").getFile().getRuleType()) + .isEqualTo(RuleType.FLOW); } @Configuration diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java similarity index 79% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java index f5e3666d..0939bf0b 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,7 +22,6 @@ import com.alibaba.cloud.sentinel.feign.SentinelFeignAutoConfiguration; import com.alibaba.csp.sentinel.slots.block.RuleConstant; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; - import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; @@ -39,18 +38,15 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; /** * @author Jim */ @RunWith(SpringRunner.class) -@SpringBootTest(classes = { SentinelFeignTests.TestConfig.class }, properties = { - "feign.sentinel.enabled=true" }) +@SpringBootTest(classes = { SentinelFeignTests.TestConfig.class }, + properties = { "feign.sentinel.enabled=true" }) public class SentinelFeignTests { @Autowired @@ -100,29 +96,26 @@ public class SentinelFeignTests { @Test public void contextLoads() throws Exception { - assertNotNull("EchoService was not created", echoService); - assertNotNull("FooService was not created", fooService); + assertThat(echoService).isNotNull(); + assertThat(fooService).isNotNull(); } @Test public void testFeignClient() { - assertEquals("Sentinel Feign Client fallback success", "echo fallback", - echoService.echo("test")); - assertEquals("Sentinel Feign Client fallbackFactory success", "foo fallback", - fooService.echo("test")); - assertThatExceptionOfType(Exception.class).isThrownBy(() -> { - barService.bar(); - }); - assertThatExceptionOfType(Exception.class).isThrownBy(() -> { - bazService.baz(); - }); + assertThat(echoService.echo("test")).isEqualTo("echo fallback"); + assertThat(fooService.echo("test")).isEqualTo("foo fallback"); - assertNotEquals("ToString method invoke was not in SentinelInvocationHandler", - echoService.toString(), fooService.toString()); - assertNotEquals("HashCode method invoke was not in SentinelInvocationHandler", - echoService.hashCode(), fooService.hashCode()); - assertFalse("Equals method invoke was not in SentinelInvocationHandler", - echoService.equals(fooService)); + assertThatThrownBy(() -> { + barService.bar(); + }).isInstanceOf(Exception.class); + + assertThatThrownBy(() -> { + bazService.baz(); + }).isInstanceOf(Exception.class); + + assertThat(fooService.toString()).isNotEqualTo(echoService.toString()); + assertThat(fooService.hashCode()).isNotEqualTo(echoService.hashCode()); + assertThat(echoService.equals(fooService)).isEqualTo(Boolean.FALSE); } @Configuration @@ -145,29 +138,38 @@ public class SentinelFeignTests { @FeignClient(value = "test-service", fallback = EchoServiceFallback.class) public interface EchoService { + @RequestMapping(path = "echo/{str}") String echo(@RequestParam("str") String param); + } @FeignClient(value = "foo-service", fallbackFactory = CustomFallbackFactory.class) public interface FooService { + @RequestMapping(path = "echo/{str}") String echo(@RequestParam("str") String param); + } - @FeignClient(value = "bar-service") + @FeignClient("bar-service") public interface BarService { + @RequestMapping(path = "bar") String bar(); + } public interface BazService { + @RequestMapping(path = "baz") String baz(); + } - @FeignClient(value = "baz-service") + @FeignClient("baz-service") public interface BazClient extends BazService { + } public static class EchoServiceFallback implements EchoService { @@ -185,6 +187,7 @@ public class SentinelFeignTests { public String echo(@RequestParam("str") String param) { return "foo fallback"; } + } public static class CustomFallbackFactory @@ -196,6 +199,7 @@ public class SentinelFeignTests { public FooService create(Throwable throwable) { return fooService; } + } } diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java similarity index 87% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java index fe1a107c..5fb912dd 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,7 +20,6 @@ import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; import com.alibaba.cloud.sentinel.custom.SentinelBeanPostProcessor; import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; import com.alibaba.csp.sentinel.slots.block.BlockException; - import org.junit.Test; import org.springframework.beans.factory.BeanCreationException; @@ -32,7 +31,7 @@ import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.web.client.RestTemplate; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; /** * @author Jim @@ -63,8 +62,7 @@ public class SentinelRestTemplateTests { public void testNormal() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfig5.class); - assertEquals("RestTemplate size was wrong", 1, - context.getBeansOfType(RestTemplate.class).size()); + assertThat(context.getBeansOfType(RestTemplate.class).size()).isEqualTo(1); } @Test(expected = BeanCreationException.class) @@ -114,6 +112,7 @@ public class SentinelRestTemplateTests { @Configuration public static class TestConfig1 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -125,10 +124,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig2 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -140,10 +141,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig3 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -155,10 +158,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig4 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -170,10 +175,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig5 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -181,14 +188,22 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, blockHandler = "handleException", fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, fallback = "fallbackException", urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, urlCleaner = "clean") + @SentinelRestTemplate( + blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, + blockHandler = "handleException", + fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, + fallback = "fallbackException", + urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, + urlCleaner = "clean") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig6 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -196,14 +211,18 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, blockHandler = "handleException1") + @SentinelRestTemplate( + blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, + blockHandler = "handleException1") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig7 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -211,14 +230,18 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, fallback = "fallbackException1") + @SentinelRestTemplate( + fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, + fallback = "fallbackException1") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig8 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -226,14 +249,18 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, blockHandler = "handleException2") + @SentinelRestTemplate( + blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, + blockHandler = "handleException2") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig9 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -241,14 +268,18 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, fallback = "fallbackException2") + @SentinelRestTemplate( + fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, + fallback = "fallbackException2") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig10 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -266,10 +297,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate2() { return new RestTemplate(); } + } @Configuration public static class TestConfig11 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -281,10 +314,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig12 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -296,10 +331,12 @@ public class SentinelRestTemplateTests { RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig13 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -307,14 +344,18 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, urlCleaner = "clean1") + @SentinelRestTemplate( + urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, + urlCleaner = "clean1") RestTemplate restTemplate() { return new RestTemplate(); } + } @Configuration public static class TestConfig14 { + @Bean SentinelBeanPostProcessor sentinelBeanPostProcessor( ApplicationContext applicationContext) { @@ -322,13 +363,17 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, urlCleaner = "clean2") + @SentinelRestTemplate( + urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, + urlCleaner = "clean2") RestTemplate restTemplate() { return new RestTemplate(); } + } public static class ExceptionUtil { + public static SentinelClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException ex) { System.out.println("Oops: " + ex.getClass().getCanonicalName()); @@ -350,15 +395,18 @@ public class SentinelRestTemplateTests { ClientHttpRequestExecution execution, BlockException ex) { System.out.println("Oops: " + ex.getClass().getCanonicalName()); } + } public static class UrlCleanUtil { + public static String clean(String url) { return url; } public static void clean2(String url) { } + } } diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java similarity index 92% rename from spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java index b17f45ae..95e967cb 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/TestConverter.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,6 @@ import java.util.List; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowRule; - import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; @@ -29,6 +28,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; * @author Jim */ public class TestConverter implements Converter> { + private ObjectMapper objectMapper = new ObjectMapper(); @Override @@ -42,4 +42,5 @@ public class TestConverter implements Converter> { } return null; } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicatorTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicatorTests.java new file mode 100644 index 00000000..b8d68d52 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicatorTests.java @@ -0,0 +1,175 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.sentinel.endpoint; + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +import com.alibaba.cloud.sentinel.SentinelProperties; +import com.alibaba.csp.sentinel.config.SentinelConfig; +import com.alibaba.csp.sentinel.datasource.AbstractDataSource; +import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource; +import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider; +import com.alibaba.csp.sentinel.transport.HeartbeatSender; +import com.alibaba.csp.sentinel.transport.config.TransportConfig; +import org.junit.Before; +import org.junit.Test; + +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.boot.actuate.health.Health; +import org.springframework.boot.actuate.health.Status; +import org.springframework.util.ReflectionUtils; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Test cases for {@link SentinelHealthIndicator}. + * + * @author cdfive + */ +public class SentinelHealthIndicatorTests { + + private SentinelHealthIndicator sentinelHealthIndicator; + + private DefaultListableBeanFactory beanFactory; + + private SentinelProperties sentinelProperties; + + private HeartbeatSender heartbeatSender; + + @Before + public void setUp() { + beanFactory = mock(DefaultListableBeanFactory.class); + sentinelProperties = mock(SentinelProperties.class); + sentinelHealthIndicator = new SentinelHealthIndicator(beanFactory, + sentinelProperties); + + SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, ""); + + heartbeatSender = mock(HeartbeatSender.class); + Field heartbeatSenderField = ReflectionUtils + .findField(HeartbeatSenderProvider.class, "heartbeatSender"); + heartbeatSenderField.setAccessible(true); + ReflectionUtils.setField(heartbeatSenderField, null, heartbeatSender); + } + + @Test + public void testSentinelNotEnabled() { + when(sentinelProperties.isEnabled()).thenReturn(false); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("enabled")).isEqualTo(false); + } + + @Test + public void testSentinelDashboardNotConfigured() { + when(sentinelProperties.isEnabled()).thenReturn(true); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.UP); + assertThat(health.getDetails().get("dashboard")).isEqualTo(Status.UNKNOWN); + } + + @Test + public void testSentinelDashboardConfiguredSuccess() throws Exception { + when(sentinelProperties.isEnabled()).thenReturn(true); + SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080"); + when(heartbeatSender.sendHeartbeat()).thenReturn(true); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.UP); + } + + @Test + public void testSentinelDashboardConfiguredFailed() throws Exception { + when(sentinelProperties.isEnabled()).thenReturn(true); + SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080"); + when(heartbeatSender.sendHeartbeat()).thenReturn(false); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + assertThat(health.getDetails().get("dashboard")).isEqualTo( + new Status(Status.DOWN.getCode(), "localhost:8080 can't be connected")); + } + + @Test + public void testSentinelDataSourceSuccess() throws Exception { + when(sentinelProperties.isEnabled()).thenReturn(true); + SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080"); + when(heartbeatSender.sendHeartbeat()).thenReturn(true); + + Map dataSourceMap = new HashMap<>(); + + FileRefreshableDataSource fileDataSource1 = mock(FileRefreshableDataSource.class); + dataSourceMap.put("ds1-sentinel-file-datasource", fileDataSource1); + + FileRefreshableDataSource fileDataSource2 = mock(FileRefreshableDataSource.class); + dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2); + + when(beanFactory.getBeansOfType(AbstractDataSource.class)) + .thenReturn(dataSourceMap); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.UP); + Map dataSourceDetailMap = (Map) health + .getDetails().get("dataSource"); + assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource")) + .isEqualTo(Status.UP); + assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource")) + .isEqualTo(Status.UP); + } + + @Test + public void testSentinelDataSourceFailed() throws Exception { + when(sentinelProperties.isEnabled()).thenReturn(true); + SentinelConfig.setConfig(TransportConfig.CONSOLE_SERVER, "localhost:8080"); + when(heartbeatSender.sendHeartbeat()).thenReturn(true); + + Map dataSourceMap = new HashMap<>(); + + FileRefreshableDataSource fileDataSource1 = mock(FileRefreshableDataSource.class); + dataSourceMap.put("ds1-sentinel-file-datasource", fileDataSource1); + + FileRefreshableDataSource fileDataSource2 = mock(FileRefreshableDataSource.class); + when(fileDataSource2.loadConfig()) + .thenThrow(new RuntimeException("fileDataSource2 error")); + dataSourceMap.put("ds2-sentinel-file-datasource", fileDataSource2); + + when(beanFactory.getBeansOfType(AbstractDataSource.class)) + .thenReturn(dataSourceMap); + + Health health = sentinelHealthIndicator.health(); + + assertThat(health.getStatus()).isEqualTo(Status.DOWN); + Map dataSourceDetailMap = (Map) health + .getDetails().get("dataSource"); + assertThat(dataSourceDetailMap.get("ds1-sentinel-file-datasource")) + .isEqualTo(Status.UP); + assertThat(dataSourceDetailMap.get("ds2-sentinel-file-datasource")) + .isEqualTo(new Status(Status.DOWN.getCode(), "fileDataSource2 error")); + } + +} diff --git a/spring-cloud-alibaba-sentinel/src/test/resources/authority.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/authority.json similarity index 100% rename from spring-cloud-alibaba-sentinel/src/test/resources/authority.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/authority.json diff --git a/spring-cloud-alibaba-sentinel/src/test/resources/degraderule.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/degraderule.json similarity index 100% rename from spring-cloud-alibaba-sentinel/src/test/resources/degraderule.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/degraderule.json diff --git a/spring-cloud-alibaba-sentinel/src/test/resources/flowrule.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/flowrule.json similarity index 100% rename from spring-cloud-alibaba-sentinel/src/test/resources/flowrule.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/flowrule.json diff --git a/spring-cloud-alibaba-sentinel/src/test/resources/param-flow.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/param-flow.json similarity index 100% rename from spring-cloud-alibaba-sentinel/src/test/resources/param-flow.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/param-flow.json diff --git a/spring-cloud-alibaba-sentinel/src/test/resources/system.json b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/system.json similarity index 100% rename from spring-cloud-alibaba-sentinel/src/test/resources/system.json rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sentinel/src/test/resources/system.json diff --git a/spring-cloud-alibaba-sidecar/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/pom.xml similarity index 63% rename from spring-cloud-alibaba-sidecar/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/pom.xml index a1175ca4..b46dac88 100644 --- a/spring-cloud-alibaba-sidecar/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/pom.xml @@ -1,31 +1,43 @@ - + + com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE + ../pom.xml + 4.0.0 - spring-cloud-alibaba-sidecar - Spring Cloud Alibaba Sidecar - An easy way to integrate polyglot apps for Spring Cloud Alibaba. + spring-cloud-starter-alibaba-sidecar + Spring Cloud Starter Alibaba Sidecar + + org.springframework.boot + spring-boot-starter + true + + org.springframework.cloud spring-cloud-starter-gateway + true org.springframework.boot spring-boot-starter-actuator + true com.alibaba.cloud spring-cloud-starter-alibaba-nacos-discovery + true diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java similarity index 92% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java index d31e5320..83ac8c93 100644 --- a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java @@ -16,6 +16,7 @@ package com.alibaba.cloud.sidecar; +import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; @@ -37,6 +38,7 @@ public class SidecarAutoConfiguration { } @Bean + @ConditionalOnEnabledHealthIndicator("sidecar") public SidecarHealthIndicator sidecarHealthIndicator( SidecarProperties sidecarProperties, RestTemplate restTemplate) { return new SidecarHealthIndicator(sidecarProperties, restTemplate); diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java similarity index 90% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java index 51ce4a86..d3f40929 100644 --- a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java @@ -30,6 +30,7 @@ import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; import org.springframework.cloud.consul.discovery.HeartbeatProperties; import org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration; import org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationAutoConfiguration; +import org.springframework.cloud.consul.serviceregistry.ConsulManagementRegistrationCustomizer; import org.springframework.cloud.consul.serviceregistry.ConsulRegistrationCustomizer; import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistryAutoConfiguration; @@ -51,11 +52,13 @@ public class SidecarConsulAutoConfiguration { AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext applicationContext, ObjectProvider> registrationCustomizers, + ObjectProvider> managementRegistrationCustomizers, HeartbeatProperties heartbeatProperties, SidecarProperties sidecarProperties) { return SidecarConsulAutoRegistration.registration( autoServiceRegistrationProperties, properties, applicationContext, - registrationCustomizers.getIfAvailable(), heartbeatProperties, + registrationCustomizers.getIfAvailable(), + managementRegistrationCustomizers.getIfAvailable(), heartbeatProperties, sidecarProperties); } diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java similarity index 88% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java index 2e816bbb..f53a0a1d 100644 --- a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java @@ -19,13 +19,13 @@ package com.alibaba.cloud.sidecar.consul; import java.util.List; import com.alibaba.cloud.sidecar.SidecarProperties; - import com.ecwid.consul.v1.agent.model.NewService; import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; import org.springframework.cloud.consul.discovery.HeartbeatProperties; import org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration; +import org.springframework.cloud.consul.serviceregistry.ConsulManagementRegistrationCustomizer; import org.springframework.cloud.consul.serviceregistry.ConsulRegistrationCustomizer; import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; @@ -38,15 +38,17 @@ public class SidecarConsulAutoRegistration extends ConsulAutoRegistration { public SidecarConsulAutoRegistration(NewService service, AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext context, - HeartbeatProperties heartbeatProperties) { + HeartbeatProperties heartbeatProperties, + List managementRegistrationCustomizers) { super(service, autoServiceRegistrationProperties, properties, context, - heartbeatProperties); + heartbeatProperties, managementRegistrationCustomizers); } public static ConsulAutoRegistration registration( AutoServiceRegistrationProperties autoServiceRegistrationProperties, ConsulDiscoveryProperties properties, ApplicationContext context, List registrationCustomizers, + List managementRegistrationCustomizers, HeartbeatProperties heartbeatProperties, SidecarProperties sidecarProperties) { @@ -70,7 +72,7 @@ public class SidecarConsulAutoRegistration extends ConsulAutoRegistration { ConsulAutoRegistration registration = new ConsulAutoRegistration(service, autoServiceRegistrationProperties, properties, context, - heartbeatProperties); + heartbeatProperties, managementRegistrationCustomizers); customize(registrationCustomizers, registration); return registration; } diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java similarity index 96% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java index 1c1f28af..0e80d6e9 100644 --- a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java @@ -16,8 +16,8 @@ package com.alibaba.cloud.sidecar.nacos; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration; import com.alibaba.cloud.sidecar.SidecarAutoConfiguration; import com.alibaba.cloud.sidecar.SidecarDiscoveryClient; import com.alibaba.cloud.sidecar.SidecarProperties; diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java diff --git a/spring-cloud-alibaba-sidecar/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-alibaba-sidecar/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-alibaba-sidecar/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/pom.xml similarity index 86% rename from spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/pom.xml index f34064db..9236dd5d 100644 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/pom.xml @@ -2,12 +2,14 @@ + com.alibaba.cloud - spring-cloud-starter-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE ../pom.xml + 4.0.0 spring-cloud-starter-bus-rocketmq @@ -18,7 +20,7 @@ com.alibaba.cloud - spring-cloud-stream-binder-rocketmq + spring-cloud-starter-stream-rocketmq @@ -29,4 +31,4 @@ - \ No newline at end of file + diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java similarity index 96% rename from spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java index ffb28a1c..d062dc23 100644 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,9 +13,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.cloud.bus.rocketmq.env; -import static org.springframework.cloud.bus.SpringCloudBusClient.INPUT; +package com.alibaba.cloud.bus.rocketmq.env; import java.util.HashMap; import java.util.Map; @@ -29,19 +28,21 @@ import org.springframework.core.env.MapPropertySource; import org.springframework.core.env.MutablePropertySources; import org.springframework.core.env.PropertySource; +import static org.springframework.cloud.bus.SpringCloudBusClient.INPUT; + /** * The lowest precedence {@link EnvironmentPostProcessor} configures default RocketMQ Bus - * Properties that will be appended into {@link SpringApplication#defaultProperties} + * Properties that will be appended into {@link SpringApplication#defaultProperties}. * * @author Mercy - * @see BusEnvironmentPostProcessor * @since 0.2.1 + * @see BusEnvironmentPostProcessor */ public class RocketMQBusEnvironmentPostProcessor implements EnvironmentPostProcessor, Ordered { /** - * The name of {@link PropertySource} of {@link SpringApplication#defaultProperties} + * The name of {@link PropertySource} of {@link SpringApplication#defaultProperties}. */ private static final String PROPERTY_SOURCE_NAME = "defaultProperties"; @@ -81,9 +82,8 @@ public class RocketMQBusEnvironmentPostProcessor } /** - * Copy from + * Copy from. * {@link BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map)} - * * @param propertySources {@link MutablePropertySources} * @param map Default RocketMQ Bus Properties */ @@ -113,4 +113,5 @@ public class RocketMQBusEnvironmentPostProcessor public int getOrder() { return LOWEST_PRECEDENCE; } + } diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-bus-rocketmq/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README.md b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README.md new file mode 100644 index 00000000..d2cdb64f --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README.md @@ -0,0 +1,6 @@ +## Info + + + +## Features + diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README_CN.md b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README_CN.md new file mode 100644 index 00000000..a82b7e50 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/README_CN.md @@ -0,0 +1,49 @@ +## 简介 + +Dubbo Spring Cloud 基于 Dubbo Spring Boot 2.7.1[1] 和 Spring Cloud 2.x 开发,无论开发人员是 Dubbo 用户还是 Spring Cloud 用户, +都能轻松地驾驭,并以接近“零”成本的代价使应用向上迁移。Dubbo Spring Cloud 致力于简化 Cloud Native 开发成本,提高研发效能以及提升应用性能等目的。 + +Dubbo Spring Cloud 首个 Preview Release,随同 Spring Cloud Alibaba `0.2.2.RELEASE` 和 `0.9.0.RELEASE` 一同发布[2], +分别对应 Spring Cloud Finchley[3] 与 Greenwich[4] (下文分别简称为 “F” 版 和 “G” 版) 。 + + + + + +## 功能 + +由于 Dubbo Spring Cloud 构建在原生的 Spring Cloud 之上,其服务治理方面的能力可认为是 Spring Cloud Plus, +不仅完全覆盖 Spring Cloud 原生特性[5],而且提供更为稳定和成熟的实现,特性比对如下表所示: + +| 功能组件 | Spring Cloud | Dubbo Spring Cloud | +| ---------------------------------------------------- | -------------------------------------- | ------------------------------------------------------ | +| 分布式配置(Distributed configuration) | Git、Zookeeper、Consul、JDBC | Spring Cloud 分布式配置 + Dubbo 配置中心[6] | +| 服务注册与发现(Service registration and discovery) | Eureka、Zookeeper、Consul | Spring Cloud 原生注册中心[7] + Dubbo 原生注册中心[8] | +| 负载均衡(Load balancing) | Ribbon(随机、轮询等算法) | Dubbo 内建实现(随机、轮询等算法 + 权重等特性) | +| 服务熔断(Circuit Breakers) | Spring Cloud Hystrix | Spring Cloud Hystrix + Alibaba Sentinel[9] 等 | +| 服务调用(Service-to-service calls) | Open Feign、`RestTemplate` | Spring Cloud 服务调用 + Dubbo `@Reference` | +| 链路跟踪(Tracing) | Spring Cloud Sleuth[10] + Zipkin[11] | Zipkin、opentracing 等 | + + + +[1]: 从 2.7.0 开始,Dubbo Spring Boot 与 Dubbo 在版本上保持一致 + +[2]: Preview releases of Spring Cloud Alibaba are available: 0.9.0, 0.2.2, and 0.1.2 - + +[3]: 目前最新的 Spring Cloud “F” 版的版本为:`Finchley.SR2` - + +[4]: 当前Spring Cloud “G” 版为 `Greenwich.RELEASE` + +[5]: Spring Cloud 特性列表 - + +[6]: Dubbo 2.7 开始支持配置中心,可自定义适配 - + +[7]: Spring Cloud 原生注册中心,除 Eureka、Zookeeper、Consul 之外,还包括 Spring Cloud Alibaba 中的 Nacos + +[8]: Dubbo 原生注册中心 - + +[9]: Alibaba Sentinel:Sentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性 - ,目前 Sentinel 已被 Spring Cloud 项目纳为 Circuit Breaker 的候选实现 - + +[10]: Spring Cloud Sleuth - + +[11]: Zipkin - \ No newline at end of file diff --git a/spring-cloud-alibaba-dubbo/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/pom.xml similarity index 85% rename from spring-cloud-alibaba-dubbo/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/pom.xml index b20519e0..c51c53c1 100644 --- a/spring-cloud-alibaba-dubbo/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/pom.xml @@ -2,45 +2,28 @@ + com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE ../pom.xml + 4.0.0 - spring-cloud-alibaba-dubbo - Spring Cloud Alibaba Dubbo - - - - - - - org.springframework.boot - spring-boot-dependencies - ${spring-boot.version} - pom - import - - - - - org.apache.dubbo - dubbo-dependencies-bom - ${dubbo.version} - pom - import - - - - - + spring-cloud-starter-dubbo + Spring Cloud Starter Dubbo + + org.springframework.boot + spring-boot-starter + true + + org.springframework.boot spring-boot-actuator @@ -129,6 +112,7 @@ org.springframework.cloud spring-cloud-starter-consul-discovery + ${spring-cloud-consul.version} true @@ -161,7 +145,6 @@ org.apache.dubbo dubbo-spring-boot-actuator - ${dubbo-spring-boot.version} true @@ -209,7 +192,6 @@ test - \ No newline at end of file diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java similarity index 84% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java index 2433f227..d260f5d1 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.actuate; import com.alibaba.cloud.dubbo.actuate.endpoint.DubboRestMetadataEndpoint; @@ -26,12 +27,13 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; /** - * Dubbo Metadata Endpoints Auto-{@link Configuration} + * Dubbo Metadata Endpoints Auto-{@link Configuration}. * * @author Mercy */ -@ConditionalOnClass(name = "org.springframework.boot.actuate.endpoint.annotation.Endpoint") -@PropertySource(value = "classpath:/META-INF/dubbo/default/actuator-endpoints.properties") +@ConditionalOnClass( + name = "org.springframework.boot.actuate.endpoint.annotation.Endpoint") +@PropertySource("classpath:/META-INF/dubbo/default/actuator-endpoints.properties") @ManagementContextConfiguration public class DubboMetadataEndpointAutoConfiguration { @@ -41,4 +43,5 @@ public class DubboMetadataEndpointAutoConfiguration { public DubboRestMetadataEndpoint dubboRestMetadataEndpoint() { return new DubboRestMetadataEndpoint(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java index 2403a05a..e46a82be 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.actuate.endpoint; import com.alibaba.cloud.dubbo.service.DubboMetadataService; @@ -24,7 +25,7 @@ import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; /** - * Dubbo Rest Metadata {@link Endpoint} + * Dubbo Rest Metadata {@link Endpoint}. * * @author Mercy */ @@ -38,4 +39,5 @@ public class DubboRestMetadataEndpoint { public String get() { return dubboMetadataService.getServiceRestMetadata(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java similarity index 80% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java index 87ac0449..c8c61700 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.annotation; import java.lang.annotation.Documented; @@ -56,99 +57,108 @@ import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_RETRIES; * @see LoadBalanced */ @Retention(RetentionPolicy.RUNTIME) -@Target(value = { ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, +@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER }) @Documented public @interface DubboTransported { /** * The protocol of Dubbo transport whose value could be used the placeholder - * "dubbo.transport.protocol" - * + * "dubbo.transport.protocol". * @return the default protocol is "dubbo" */ String protocol() default "${dubbo.transport.protocol:dubbo}"; /** * The cluster of Dubbo transport whose value could be used the placeholder - * "dubbo.transport.cluster" - * + * "dubbo.transport.cluster". * @return the default cluster is "failover" */ String cluster() default "${dubbo.transport.cluster:failover}"; /** * Whether to reconnect if connection is lost, if not specify, reconnect is enabled by - * default, and the interval for retry connecting is 2000 ms + * default, and the interval for retry connecting is 2000 ms. * * @see Reference#reconnect() + * @return reconnect time */ String reconnect() default "${dubbo.transport.reconnect:2000}"; /** * Maximum connections service provider can accept, default value is 0 - connection is - * shared + * shared. * * @see Reference#connections() + * @return maximum connections */ int connections() default 0; /** - * Service invocation retry times + * Service invocation retry times. * * @see Reference#retries() + * @return retry times */ int retries() default DEFAULT_RETRIES; /** - * Load balance strategy, legal values include: random, roundrobin, leastactive + * Load balance strategy, legal values include: random, roundrobin, leastactive. * * @see Reference#loadbalance() + * @return load balance strategy */ String loadbalance() default "${dubbo.transport.loadbalance:}"; /** - * Maximum active requests allowed, default value is 0 + * Maximum active requests allowed, default value is 0. * * @see Reference#actives() + * @return maximum active requests */ int actives() default 0; /** - * Timeout value for service invocation, default value is 0 + * Timeout value for service invocation, default value is 0. * * @see Reference#timeout() + * @return timeout for service invocation */ int timeout() default 0; /** * Specify cache implementation for service invocation, legal values include: lru, - * threadlocal, jcache + * threadlocal, jcache. * * @see Reference#cache() + * @return specify cache implementation for service invocation */ String cache() default "${dubbo.transport.cache:}"; /** - * Filters for service invocation + * Filters for service invocation. * * @see Filter * @see Reference#filter() + * @return filters for service invocation */ String[] filter() default {}; /** - * Listeners for service exporting and unexporting + * Listeners for service exporting and unexporting. * * @see ExporterListener * @see Reference#listener() + * @return listener */ String[] listener() default {}; /** - * Customized parameter key-value pair, for example: {key1, value1, key2, value2} + * Customized parameter key-value pair, for example: {key1, value1, key2, value2}. * * @see Reference#parameters() + * @return parameters */ String[] parameters() default {}; + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java index 5e867386..23b7987d 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -111,8 +111,7 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration implements @Override public void afterSingletonsInstantiated() { loadBalancerInterceptorBean = retryLoadBalancerInterceptor != null - ? retryLoadBalancerInterceptor - : loadBalancerInterceptor; + ? retryLoadBalancerInterceptor : loadBalancerInterceptor; } /** @@ -146,7 +145,7 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration implements * Gets the annotation attributes {@link RestTemplate} bean being annotated * {@link DubboTransported @DubboTransported}. * @param beanName the bean name of {@link LoadBalanced @LoadBalanced} - * {@link RestTemplate} + * {@link RestTemplate} * @param attributesResolver {@link DubboTransportedAttributesResolver} * @return non-null {@link Map} */ @@ -171,8 +170,8 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration implements * {@link LoadBalancerInterceptor} Bean. * @param restTemplate {@link LoadBalanced @LoadBalanced} {@link RestTemplate} Bean * @param dubboTranslatedAttributes the annotation dubboTranslatedAttributes - * {@link RestTemplate} bean being annotated - * {@link DubboTransported @DubboTransported} + * {@link RestTemplate} bean being annotated + * {@link DubboTransported @DubboTransported} */ private void adaptRestTemplate(RestTemplate restTemplate, Map dubboTranslatedAttributes) { diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java similarity index 91% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java index d3aaa4c5..5b1cddf7 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import java.util.Collection; import java.util.Optional; import java.util.function.Supplier; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; import com.alibaba.cloud.dubbo.metadata.DubboProtocolConfigSupplier; import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; import com.alibaba.cloud.dubbo.metadata.repository.MetadataServiceInstanceSelector; @@ -30,7 +30,6 @@ import com.alibaba.cloud.dubbo.service.DubboMetadataServiceExporter; import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; import com.alibaba.cloud.dubbo.service.IntrospectiveDubboMetadataService; import com.alibaba.cloud.dubbo.util.JSONUtils; - import feign.Contract; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.spring.ServiceBean; @@ -48,7 +47,7 @@ import org.springframework.context.event.EventListener; import org.springframework.util.CollectionUtils; /** - * Spring Boot Auto-Configuration class for Dubbo Metadata + * Spring Boot Auto-Configuration class for Dubbo Metadata. * * @author Mercy */ @@ -66,9 +65,6 @@ public class DubboMetadataAutoConfiguration { @Autowired private DubboMetadataServiceExporter dubboMetadataConfigServiceExporter; - @Autowired - private DubboCloudProperties dubboCloudProperties; - @Bean @ConditionalOnMissingBean public MetadataResolver metadataJsonResolver(ObjectProvider contract) { @@ -79,8 +75,7 @@ public class DubboMetadataAutoConfiguration { @ConditionalOnMissingBean public MetadataServiceInstanceSelector metadataServiceInstanceSelector() { return serviceInstances -> CollectionUtils.isEmpty(serviceInstances) - ? Optional.empty() - : serviceInstances.stream().findAny(); + ? Optional.empty() : serviceInstances.stream().findAny(); } @Bean @@ -93,7 +88,7 @@ public class DubboMetadataAutoConfiguration { @ConditionalOnMissingBean public DubboMetadataServiceProxy dubboMetadataConfigServiceProxy( DubboGenericServiceFactory factory) { - return new DubboMetadataServiceProxy(factory, dubboCloudProperties); + return new DubboMetadataServiceProxy(factory); } // Event-Handling @@ -122,4 +117,5 @@ public class DubboMetadataAutoConfiguration { private void unExportDubboMetadataConfigService() { dubboMetadataConfigServiceExporter.unexport(); } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java similarity index 90% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java index 7429f561..e378e753 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; @@ -29,13 +30,13 @@ import org.springframework.core.env.Environment; import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME; /** - * Dubbo Feign Auto-{@link Configuration Configuration} + * Dubbo Feign Auto-{@link Configuration Configuration}. * * @author Mercy */ @ConditionalOnClass(name = { "feign.Feign", TARGETER_CLASS_NAME }) -@AutoConfigureAfter(name = { - "org.springframework.cloud.openfeign.FeignAutoConfiguration" }) +@AutoConfigureAfter( + name = { "org.springframework.cloud.openfeign.FeignAutoConfiguration" }) @Configuration public class DubboOpenFeignAutoConfiguration { @@ -53,4 +54,4 @@ public class DubboOpenFeignAutoConfiguration { dubboGenericServiceFactory, contextFactory); } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java index 08823ffd..1e9fe56f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import com.alibaba.cloud.dubbo.env.DubboCloudProperties; @@ -34,7 +35,7 @@ import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; /** - * Spring Boot Auto-Configuration class for Dubbo Service + * Spring Boot Auto-Configuration class for Dubbo Service. * * @author Mercy */ @@ -49,8 +50,7 @@ public class DubboServiceAutoConfiguration { } /** - * Build a primary {@link PropertyResolver} bean to {@link Autowired @Autowired} - * + * Build a primary {@link PropertyResolver} bean to {@link Autowired @Autowired}. * @param environment {@link Environment} * @return alias bean for {@link Environment} */ @@ -61,11 +61,13 @@ public class DubboServiceAutoConfiguration { } @Configuration - @Import(value = { DubboGenericServiceExecutionContextFactory.class, + @Import({ DubboGenericServiceExecutionContextFactory.class, RequestParamServiceParameterResolver.class, RequestBodyServiceParameterResolver.class, RequestHeaderServiceParameterResolver.class, PathVariableServiceParameterResolver.class }) static class ParameterResolversConfiguration { + } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java index 6d7a59f7..be9311ba 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import java.util.Collection; @@ -36,7 +37,6 @@ import com.alibaba.cloud.nacos.discovery.NacosWatch; import com.alibaba.nacos.api.exception.NacosException; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.listener.NamingEvent; - import com.netflix.discovery.CacheRefreshedEvent; import com.netflix.discovery.shared.Applications; import org.apache.curator.framework.CuratorFramework; @@ -82,12 +82,12 @@ import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceDiscoveryAutoCon import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceDiscoveryAutoConfiguration.NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME; import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceDiscoveryAutoConfiguration.ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME; import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME; -import static com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient.hostToServiceInstanceList; +import static com.alibaba.cloud.nacos.discovery.NacosServiceDiscovery.hostToServiceInstanceList; import static org.springframework.util.StringUtils.hasText; /** * Dubbo Service Discovery Auto {@link Configuration} (after - * {@link DubboServiceRegistrationAutoConfiguration}) + * {@link DubboServiceRegistrationAutoConfiguration}). * * @author Mercy * @see DubboServiceRegistrationAutoConfiguration @@ -97,11 +97,12 @@ import static org.springframework.util.StringUtils.hasText; @Configuration @ConditionalOnClass(name = "org.springframework.cloud.client.discovery.DiscoveryClient") @ConditionalOnProperty(name = "spring.cloud.discovery.enabled", matchIfMissing = true) -@AutoConfigureAfter(name = { EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME, - ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME, - CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME, - NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME }, value = { - DubboServiceRegistrationAutoConfiguration.class }) +@AutoConfigureAfter( + name = { EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME, + ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME, + CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME, + NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME }, + value = { DubboServiceRegistrationAutoConfiguration.class }) public class DubboServiceDiscoveryAutoConfiguration { /** @@ -117,7 +118,7 @@ public class DubboServiceDiscoveryAutoConfiguration { /** * NacosDiscoveryAutoConfiguration. */ - public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration"; + public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.discovery.NacosDiscoveryAutoConfiguration"; private final DubboServiceMetadataRepository dubboServiceMetadataRepository; @@ -146,8 +147,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Dispatch a {@link ServiceInstancesChangedEvent} - * + * Dispatch a {@link ServiceInstancesChangedEvent}. * @param serviceName the name of service * @param serviceInstances the {@link ServiceInstance instances} of some service * @see AbstractSpringCloudRegistry#registerServiceInstancesChangedEventListener(URL, @@ -217,7 +217,6 @@ public class DubboServiceDiscoveryAutoConfiguration { * implementation could declare a Spring Bean of {@link Predicate} of * {@link HeartbeatEvent} to override {@link #defaultHeartbeatEventChangePredicate() * default one}. - * * @param event the instance of {@link HeartbeatEvent} * @see HeartbeatEvent */ @@ -246,8 +245,7 @@ public class DubboServiceDiscoveryAutoConfiguration { * The default {@link Predicate} implementation of {@link HeartbeatEvent} based on the * comparison between previous and current {@link HeartbeatEvent#getValue() state * value}, the {@link DiscoveryClient} implementation may override current. - * - * @return {@link Predicate} + * @return {@link Predicate} {@link HeartbeatEvent} * @see EurekaConfiguration#heartbeatEventChangedPredicate() */ @Bean @@ -262,7 +260,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Eureka Customized Configuration + * Eureka Customized Configuration. */ @Configuration @ConditionalOnBean(name = EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME) @@ -275,6 +273,7 @@ public class DubboServiceDiscoveryAutoConfiguration { * {@link Applications} and current. * * @see Applications#getAppsHashCode() + * @return HeartbeatEvent Predicate */ @Bean public Predicate heartbeatEventChangedPredicate() { @@ -288,34 +287,36 @@ public class DubboServiceDiscoveryAutoConfiguration { && !Objects.equals(oldAppsHashCode, appsHashCode); }; } + } /** - * Zookeeper Customized Configuration + * Zookeeper Customized Configuration. */ @Configuration @ConditionalOnBean(name = ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME) @Aspect public class ZookeeperConfiguration implements ApplicationListener { + /** * The pointcut expression for - * {@link ZookeeperServiceWatch#childEvent(CuratorFramework, TreeCacheEvent)} + * {@link ZookeeperServiceWatch#childEvent(CuratorFramework, TreeCacheEvent)}. */ public static final String CHILD_EVENT_POINTCUT_EXPRESSION = "execution(void org.springframework.cloud.zookeeper.discovery.ZookeeperServiceWatch.childEvent(..)) && args(client,event)"; /** - * The path separator of Zookeeper node + * The path separator of Zookeeper node. */ public static final String NODE_PATH_SEPARATOR = "/"; /** - * The path variable name for the name of service + * The path variable name for the name of service. */ private static final String SERVICE_NAME_PATH_VARIABLE_NAME = "serviceName"; /** - * The path variable name for the id of {@link ServiceInstance service instance} + * The path variable name for the id of {@link ServiceInstance service instance}. */ private static final String SERVICE_INSTANCE_ID_PATH_VARIABLE_NAME = "serviceInstanceId"; @@ -329,7 +330,7 @@ public class DubboServiceDiscoveryAutoConfiguration { * Ant Path pattern for {@link ServiceInstance} : *

*

- * ${{@link #rootPath}}/{serviceName}/{serviceInstanceId} + * ${{@link #rootPath}}/{serviceName}/{serviceInstanceId}. * * @see #rootPath * @see #SERVICE_NAME_PATH_VARIABLE_NAME @@ -338,7 +339,7 @@ public class DubboServiceDiscoveryAutoConfiguration { private final String serviceInstancePathPattern; /** - * The {@link ThreadLocal} holds the processed service name + * The {@link ThreadLocal} holds the processed service name. */ private final ThreadLocal processedServiceNameThreadLocal; @@ -356,8 +357,7 @@ public class DubboServiceDiscoveryAutoConfiguration { /** * Zookeeper uses {@link TreeCacheEvent} to trigger * {@link #dispatchServiceInstancesChangedEvent(String, Collection)} , thus - * {@link HeartbeatEvent} handle is always ignored - * + * {@link HeartbeatEvent} handle is always ignored. * @return false forever */ @Bean @@ -367,8 +367,7 @@ public class DubboServiceDiscoveryAutoConfiguration { /** * Handle on {@link InstanceRegisteredEvent} after - * {@link ZookeeperServiceWatch#onApplicationEvent(InstanceRegisteredEvent)} - * + * {@link ZookeeperServiceWatch#onApplicationEvent(InstanceRegisteredEvent)}. * @param event {@link InstanceRegisteredEvent} * @see #reattachTreeCacheListeners() */ @@ -378,7 +377,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Re-attach the {@link TreeCacheListener TreeCacheListeners} + * Re-attach the {@link TreeCacheListener TreeCacheListeners}. */ private void reattachTreeCacheListeners() { @@ -389,7 +388,7 @@ public class DubboServiceDiscoveryAutoConfiguration { /** * All registered TreeCacheListeners except {@link ZookeeperServiceWatch}. * Usually, "otherListeners" will be empty because Spring Cloud Zookeeper only - * adds "zookeeperServiceWatch" bean as {@link TreeCacheListener} + * adds "zookeeperServiceWatch" bean as {@link TreeCacheListener}. */ List otherListeners = new LinkedList<>(); @@ -400,7 +399,7 @@ public class DubboServiceDiscoveryAutoConfiguration { * Even though "listener" is an instance of * {@link ZookeeperServiceWatch}, "zookeeperServiceWatch" bean that * was enhanced by AOP is different from the former, thus it's - * required to exclude "listener" + * required to exclude "listener". */ if (!(listener instanceof ZookeeperServiceWatch)) { otherListeners.add(listener); @@ -428,8 +427,7 @@ public class DubboServiceDiscoveryAutoConfiguration { * Try to {@link #dispatchServiceInstancesChangedEvent(String, Collection) * dispatch} {@link ServiceInstancesChangedEvent} before * {@link ZookeeperServiceWatch#childEvent(CuratorFramework, TreeCacheEvent)} - * execution if required - * + * execution if required. * @param client {@link CuratorFramework} * @param event {@link TreeCacheEvent} */ @@ -449,8 +447,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Resolve the name of service - * + * Resolve the name of service. * @param event {@link TreeCacheEvent} * @return If the Zookeeper's {@link ChildData#getPath() node path} that was * notified comes from {@link ServiceInstance the service instance}, return it's @@ -475,8 +472,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * The {@link TreeCacheEvent#getType() event type} is supported or not - * + * The {@link TreeCacheEvent#getType() event type} is supported or not. * @param event {@link TreeCacheEvent} * @return the rule is same as * {@link ZookeeperServiceWatch#childEvent(CuratorFramework, TreeCacheEvent)} @@ -488,10 +484,11 @@ public class DubboServiceDiscoveryAutoConfiguration { || eventType.equals(TreeCacheEvent.Type.NODE_REMOVED) || eventType.equals(TreeCacheEvent.Type.NODE_UPDATED); } + } /** - * Consul Customized Configuration + * Consul Customized Configuration. */ @Configuration @ConditionalOnBean(name = CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME) @@ -500,13 +497,14 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Nacos Customized Configuration + * Nacos Customized Configuration. */ @Configuration @ConditionalOnBean(name = NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME) class NacosConfiguration { private final NamingService namingService; + private final NacosDiscoveryProperties nacosDiscoveryProperties; /** @@ -521,10 +519,9 @@ public class DubboServiceDiscoveryAutoConfiguration { } /** - * Nacos uses {@link EventListener} to trigger + * Nacos uses {@link EventListener} to trigger. * {@link #dispatchServiceInstancesChangedEvent(String, Collection)} , thus * {@link HeartbeatEvent} handle is always ignored - * * @return false forever */ @Bean @@ -558,5 +555,7 @@ public class DubboServiceDiscoveryAutoConfiguration { } } } + } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java index 49cda2c2..855b4381 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import java.util.Collection; @@ -23,7 +24,6 @@ import com.alibaba.cloud.dubbo.autoconfigure.condition.MissingSpringCloudRegistr import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; import com.alibaba.cloud.dubbo.registry.DubboServiceRegistrationEventPublishingAspect; import com.alibaba.cloud.dubbo.registry.event.ServiceInstancePreRegisteredEvent; - import com.ecwid.consul.v1.agent.model.NewService; import com.netflix.appinfo.InstanceInfo; import org.apache.dubbo.config.RegistryConfig; @@ -60,25 +60,38 @@ import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOC import static org.springframework.util.ObjectUtils.isEmpty; /** - * Dubbo Service Registration Auto-{@link Configuration} + * Dubbo Service Registration Auto-{@link Configuration}. * * @author Mercy */ @Configuration @Import({ DubboServiceRegistrationEventPublishingAspect.class }) -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", + matchIfMissing = true) @AutoConfigureAfter(name = { EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME, CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME, - "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" }, value = { - DubboMetadataAutoConfiguration.class }) + "org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration" }, + value = { DubboMetadataAutoConfiguration.class }) public class DubboServiceRegistrationAutoConfiguration { + /** + * EurekaClientAutoConfiguration. + */ public static final String EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.netflix.eureka.EurekaClientAutoConfiguration"; + /** + * ConsulAutoServiceRegistrationAutoConfiguration. + */ public static final String CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.consul.serviceregistry.ConsulAutoServiceRegistrationAutoConfiguration"; + /** + * ConsulAutoRegistration. + */ public static final String CONSUL_AUTO_SERVICE_AUTO_REGISTRATION_CLASS_NAME = "org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration"; + /** + * ZookeeperAutoServiceRegistrationAutoConfiguration. + */ public static final String ZOOKEEPER_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.zookeeper.serviceregistry.ZookeeperAutoServiceRegistrationAutoConfiguration"; private static final Logger logger = LoggerFactory @@ -88,7 +101,7 @@ public class DubboServiceRegistrationAutoConfiguration { private DubboServiceMetadataRepository dubboServiceMetadataRepository; @Bean - @Conditional(value = { MissingSpringCloudRegistryConfigPropertyCondition.class }) + @Conditional({ MissingSpringCloudRegistryConfigPropertyCondition.class }) public RegistryConfig defaultSpringCloudRegistryConfig() { return new RegistryConfig(ADDRESS, PROTOCOL); } @@ -150,6 +163,7 @@ public class DubboServiceRegistrationAutoConfiguration { serviceBeans.forEach(ServiceBean::export); } } + } @Configuration @@ -158,8 +172,7 @@ public class DubboServiceRegistrationAutoConfiguration { class ConsulConfiguration { /** - * Handle the pre-registered event of {@link ServiceInstance} for Consul - * + * Handle the pre-registered event of {@link ServiceInstance} for Consul. * @param event {@link ServiceInstancePreRegisteredEvent} */ @EventListener(ServiceInstancePreRegisteredEvent.class) @@ -186,5 +199,7 @@ public class DubboServiceRegistrationAutoConfiguration { } } } + } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java index 40194719..9c411506 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import java.util.List; import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; import com.alibaba.cloud.dubbo.registry.event.ServiceInstancePreRegisteredEvent; - import com.ecwid.consul.v1.agent.model.NewService; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.spring.ServiceBean; @@ -47,13 +47,14 @@ import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAuto import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.ZOOKEEPER_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; /** - * Dubbo Service Registration Auto-{@link Configuration} for Non-Web application + * Dubbo Service Registration Auto-{@link Configuration} for Non-Web application. * * @author Mercy */ @Configuration @ConditionalOnNotWebApplication -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) +@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", + matchIfMissing = true) @AutoConfigureAfter(DubboServiceRegistrationAutoConfiguration.class) @Aspect public class DubboServiceRegistrationNonWebApplicationAutoConfiguration { @@ -134,6 +135,7 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration { // before register registration.getServiceInstance(); } + } @Configuration @@ -141,8 +143,7 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration { class ConsulConfiguration { /** - * Handle the pre-registered event of {@link ServiceInstance} for Consul - * + * Handle the pre-registered event of {@link ServiceInstance} for Consul. * @param event {@link ServiceInstancePreRegisteredEvent} */ @EventListener(ServiceInstancePreRegisteredEvent.class) @@ -154,8 +155,7 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration { } /** - * Set port on Non-Web Application - * + * Set port on Non-Web Application. * @param consulRegistration {@link ConsulRegistration} */ private void setPort(ConsulAutoRegistration consulRegistration) { @@ -165,6 +165,7 @@ public class DubboServiceRegistrationNonWebApplicationAutoConfiguration { newService.setPort(port); } } + } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java index 40c34046..0ea71581 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure.condition; import java.util.Map; @@ -28,10 +29,10 @@ import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.StringUtils; import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL; -import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; +import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getPrefixedProperties; /** - * Missing {@link SpringCloudRegistry} Property {@link Condition} + * Missing {@link SpringCloudRegistry} Property {@link Condition}. * * @author Mercy * @see SpringCloudRegistry @@ -60,8 +61,8 @@ public class MissingSpringCloudRegistryConfigPropertyCondition "'spring-cloud' protocol was found from 'dubbo.registry.address'"); } - Map properties = getSubProperties(environment, - "dubbo.registries."); + Map properties = getPrefixedProperties( + environment.getPropertySources(), "dubbo.registries."); boolean found = properties.entrySet().stream().anyMatch(entry -> { String key = entry.getKey(); @@ -76,4 +77,5 @@ public class MissingSpringCloudRegistryConfigPropertyCondition "'spring-cloud' protocol was found in 'dubbo.registries.*'") : ConditionOutcome.match(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java index 268bd665..87513d0b 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; @@ -25,7 +26,7 @@ import org.springframework.http.HttpStatus; import org.springframework.http.client.ClientHttpResponse; /** - * Dubbo {@link ClientHttpResponse} implementation + * Dubbo {@link ClientHttpResponse} implementation. * * @author Mercy * @see DubboTransporterInterceptor @@ -40,7 +41,7 @@ class DubboClientHttpResponse implements ClientHttpResponse { private final DubboHttpOutputMessage httpOutputMessage; - public DubboClientHttpResponse(DubboHttpOutputMessage httpOutputMessage, + DubboClientHttpResponse(DubboHttpOutputMessage httpOutputMessage, GenericException exception) { this.httpStatus = exception != null ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.OK; @@ -78,4 +79,5 @@ class DubboClientHttpResponse implements ClientHttpResponse { public HttpHeaders getHeaders() { return httpHeaders; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java index fa299200..110f388e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; @@ -22,7 +23,6 @@ import com.alibaba.cloud.dubbo.http.converter.HttpMessageConverterHolder; import com.alibaba.cloud.dubbo.http.util.HttpMessageConverterResolver; import com.alibaba.cloud.dubbo.metadata.RequestMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; - import org.apache.dubbo.rpc.service.GenericException; import org.springframework.http.MediaType; @@ -30,7 +30,7 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.converter.HttpMessageConverter; /** - * Dubbo {@link ClientHttpResponse} Factory + * Dubbo {@link ClientHttpResponse} Factory. * * @author Mercy */ @@ -38,7 +38,7 @@ class DubboClientHttpResponseFactory { private final HttpMessageConverterResolver httpMessageConverterResolver; - public DubboClientHttpResponseFactory(List> messageConverters, + DubboClientHttpResponseFactory(List> messageConverters, ClassLoader classLoader) { this.httpMessageConverterResolver = new HttpMessageConverterResolver( messageConverters, classLoader); @@ -65,4 +65,5 @@ class DubboClientHttpResponseFactory { return new DubboClientHttpResponse(httpOutputMessage, exception); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java index 38353a77..8c727e75 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; @@ -22,7 +23,7 @@ import org.springframework.http.HttpOutputMessage; import org.springframework.util.FastByteArrayOutputStream; /** - * Dubbo {@link HttpOutputMessage} implementation + * Dubbo {@link HttpOutputMessage} implementation. * * @author Mercy */ @@ -41,4 +42,5 @@ class DubboHttpOutputMessage implements HttpOutputMessage { public HttpHeaders getHeaders() { return httpHeaders; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java index 56e21263..f0424b65 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; @@ -27,7 +28,7 @@ import org.springframework.http.client.ClientHttpResponse; /** * Dubbo Metadata {@link ClientHttpRequestInterceptor} Initializing Interceptor executes - * intercept before {@link DubboTransporterInterceptor} + * intercept before {@link DubboTransporterInterceptor}. * * @author Mercy */ @@ -53,4 +54,5 @@ public class DubboMetadataInitializerInterceptor implements ClientHttpRequestInt // Execute next return execution.execute(request, body); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java similarity index 98% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java index d6dc608a..b6544f64 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; @@ -28,7 +29,6 @@ import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepositor import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContext; import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; - import org.apache.dubbo.rpc.service.GenericException; import org.apache.dubbo.rpc.service.GenericService; @@ -46,7 +46,7 @@ import org.springframework.web.util.UriComponents; import static org.springframework.web.util.UriComponentsBuilder.fromUri; /** - * Dubbo Transporter {@link ClientHttpRequestInterceptor} implementation + * Dubbo Transporter {@link ClientHttpRequestInterceptor} implementation. * * @author Mercy * @see LoadBalancerInterceptor @@ -149,4 +149,5 @@ public class DubboTransporterInterceptor implements ClientHttpRequestInterceptor requestMetadata.setHeaders(request.getHeaders()); return requestMetadata; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java index a2f07cef..873caea0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.context; import com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory; @@ -37,4 +38,5 @@ public class DubboServiceRegistrationApplicationContextInitializer // Register SpringCloudRegistryFactory.setApplicationContext(applicationContext); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java similarity index 74% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java index 4c39084d..80a0a072 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.env; import java.util.Collections; @@ -26,7 +27,7 @@ import static org.springframework.util.StringUtils.hasText; import static org.springframework.util.StringUtils.trimAllWhitespace; /** - * Dubbo Cloud {@link ConfigurationProperties Properties} + * Dubbo Cloud {@link ConfigurationProperties Properties}. * * @author Mercy */ @@ -34,7 +35,7 @@ import static org.springframework.util.StringUtils.trimAllWhitespace; public class DubboCloudProperties { /** - * All services of Dubbo + * All services of Dubbo. */ public static final String ALL_DUBBO_SERVICES = "*"; @@ -46,18 +47,6 @@ public class DubboCloudProperties { */ private String subscribedServices = ALL_DUBBO_SERVICES; - /** - * The Service Instance changed do not means Dubbo service ready, need retry - * mechanism. Retry count of Generic Invoke. - */ - private int retryCount = 5; - - /** - * The Service Instance changed do not means Dubbo service ready, need retry - * mechanism. Retry interval of Generic Invoke, milliseconds unit. - */ - private int interval = 10000; - public String getSubscribedServices() { return subscribedServices; } @@ -66,25 +55,8 @@ public class DubboCloudProperties { this.subscribedServices = subscribedServices; } - public int getRetryCount() { - return retryCount; - } - - public void setRetryCount(int retryCount) { - this.retryCount = retryCount; - } - - public int getInterval() { - return interval; - } - - public void setInterval(int interval) { - this.interval = interval; - } - /** * Get the subscribed services as a {@link Set} with configuration order. - * * @return non-null Read-only {@link Set} */ public Set subscribedServices() { @@ -106,4 +78,5 @@ public class DubboCloudProperties { return Collections.unmodifiableSet(subscribedServices); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java index 97df11b5..4de58946 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.env; import java.util.HashMap; @@ -34,11 +35,11 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; +import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getPrefixedProperties; /** * Dubbo {@link WebApplicationType#NONE Non-Web Application} - * {@link EnvironmentPostProcessor} + * {@link EnvironmentPostProcessor}. * * @author Mercy */ @@ -87,7 +88,7 @@ public class DubboNonWebApplicationEnvironmentPostProcessor WebApplicationType webApplicationType = application.getWebApplicationType(); if (!WebApplicationType.NONE.equals(webApplicationType)) { // Just works in - // Non-Web Application + // Non-Web Application if (logger.isDebugEnabled()) { logger.debug( "Current application is a Web Application, the process will be ignored."); @@ -111,10 +112,9 @@ public class DubboNonWebApplicationEnvironmentPostProcessor /** * Reset server port property if it's absent, whose value is configured by - * "dubbbo.protocol.port" or "dubbo.protcols.rest.port" - * - * @param environment - * @param defaultProperties + * "dubbbo.protocol.port" or "dubbo.protcols.rest.port". + * @param environment Spring Environment + * @param defaultProperties defaultProperties */ private void resetServerPort(ConfigurableEnvironment environment, Map defaultProperties) { @@ -141,8 +141,7 @@ public class DubboNonWebApplicationEnvironmentPostProcessor DEFAULT_PROTOCOL); return isRestProtocol(protocol) - ? environment.getProperty(PROTOCOL_PORT_PROPERTY_NAME) - : null; + ? environment.getProperty(PROTOCOL_PORT_PROPERTY_NAME) : null; } private String getRestPortFromProtocolsProperties( @@ -150,8 +149,8 @@ public class DubboNonWebApplicationEnvironmentPostProcessor String restPort = null; - Map subProperties = getSubProperties(environment, - PROTOCOLS_PROPERTY_NAME_PREFIX); + Map subProperties = getPrefixedProperties( + environment.getPropertySources(), PROTOCOLS_PROPERTY_NAME_PREFIX); Properties properties = new Properties(); @@ -159,8 +158,8 @@ public class DubboNonWebApplicationEnvironmentPostProcessor for (String propertyName : properties.stringPropertyNames()) { if (propertyName.endsWith(PROTOCOL_NAME_PROPERTY_NAME_SUFFIX)) { // protocol - // name - // property + // name + // property String protocol = properties.getProperty(propertyName); if (isRestProtocol(protocol)) { String beanName = resolveBeanName(propertyName); @@ -192,8 +191,7 @@ public class DubboNonWebApplicationEnvironmentPostProcessor } /** - * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map) - * + * Copy from BusEnvironmentPostProcessor#addOrReplace(MutablePropertySources, Map). * @param propertySources {@link MutablePropertySources} * @param map Default Dubbo Properties */ @@ -223,4 +221,5 @@ public class DubboNonWebApplicationEnvironmentPostProcessor public int getOrder() { // Keep LOWEST_PRECEDENCE return LOWEST_PRECEDENCE; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java similarity index 85% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java index a36666df..f431b849 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http; import java.io.IOException; @@ -24,7 +25,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpInputMessage; /** - * Byte array {@link HttpInputMessage} implementation + * Byte array {@link HttpInputMessage} implementation. * * @author Mercy */ @@ -34,11 +35,11 @@ class ByteArrayHttpInputMessage implements HttpInputMessage { private final InputStream inputStream; - public ByteArrayHttpInputMessage(byte[] body) { + ByteArrayHttpInputMessage(byte[] body) { this(new HttpHeaders(), body); } - public ByteArrayHttpInputMessage(HttpHeaders httpHeaders, byte[] body) { + ByteArrayHttpInputMessage(HttpHeaders httpHeaders, byte[] body) { this.httpHeaders = httpHeaders; this.inputStream = new UnsafeByteArrayInputStream(body); } @@ -52,4 +53,5 @@ class ByteArrayHttpInputMessage implements HttpInputMessage { public HttpHeaders getHeaders() { return httpHeaders; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java index 0c75cea2..714f296e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http; import java.net.URI; @@ -29,7 +30,7 @@ import org.springframework.web.util.UriComponentsBuilder; import static org.springframework.web.util.UriComponentsBuilder.fromPath; /** - * Default {@link HttpRequest} implementation + * Default {@link HttpRequest} implementation. * * @author Mercy */ @@ -79,7 +80,7 @@ public class DefaultHttpRequest implements HttpRequest { } /** - * {@link HttpRequest} Builder + * {@link HttpRequest} Builder. */ public static class Builder { @@ -124,6 +125,7 @@ public class DefaultHttpRequest implements HttpRequest { public HttpRequest build() { return new DefaultHttpRequest(method, path, params, headers); } + } } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java similarity index 85% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java index 32b67efb..9ec78d50 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http; import org.springframework.http.HttpInputMessage; @@ -20,21 +21,21 @@ import org.springframework.http.HttpRequest; import org.springframework.util.MultiValueMap; /** - * HTTP Server Request + * HTTP Server Request. * * @author Mercy */ public interface HttpServerRequest extends HttpRequest, HttpInputMessage { /** - * Return a path of current HTTP request - * - * @return + * Return a path of current HTTP request. + * @return the path */ String getPath(); /** * Return a map with parsed and decoded query parameter values. + * @return the query params */ MultiValueMap getQueryParams(); diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java index efc7bb77..89fc25a0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http; import java.io.IOException; @@ -29,7 +30,7 @@ import org.springframework.util.MultiValueMap; import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; /** - * Mutable {@link HttpServerRequest} implementation + * Mutable {@link HttpServerRequest} implementation. * * @author Mercy */ @@ -96,4 +97,5 @@ public class MutableHttpServerRequest implements HttpServerRequest { public MultiValueMap getQueryParams() { return queryParams; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java index a4076b25..a8747961 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.converter; import org.springframework.http.MediaType; @@ -42,4 +43,5 @@ public class HttpMessageConverterHolder { public HttpMessageConverter getConverter() { return converter; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java index cc4994d0..a2d3ea75 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Collection; import java.util.Iterator; /** - * Abstract {@link HttpRequestMatcher} implementation + * Abstract {@link HttpRequestMatcher} implementation. * * @author Rossen Stoyanchev * @author Mercy @@ -30,7 +31,6 @@ public abstract class AbstractHttpRequestMatcher implements HttpRequestMatcher { * Return the discrete items a request condition is composed of. *

* For example URL patterns, HTTP request methods, param expressions, etc. - * * @return a collection of objects, never {@code null} */ protected abstract Collection getContent(); @@ -72,4 +72,5 @@ public abstract class AbstractHttpRequestMatcher implements HttpRequestMatcher { builder.append("]"); return builder.toString(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java index 67b75957..b7a7ccf7 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.MediaType; /** * The some source code is scratched from - * org.springframework.web.servlet.mvc.condition.AbstractMediaTypeExpression + * org.springframework.web.servlet.mvc.condition.AbstractMediaTypeExpression. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -91,4 +92,5 @@ public class AbstractMediaTypeExpression builder.append(this.mediaType.toString()); return builder.toString(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java index e34aa953..611cd22d 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.HttpRequest; @@ -23,7 +24,7 @@ import static org.springframework.util.StringUtils.trimWhitespace; /** * The some source code is scratched from - * org.springframework.web.servlet.mvc.condition.AbstractNameValueExpression + * org.springframework.web.servlet.mvc.condition.AbstractNameValueExpression. * * @author Rossen Stoyanchev * @author Arjen Poutsma @@ -63,9 +64,8 @@ abstract class AbstractNameValueExpression implements NameValueExpression /** * Exclude the pattern value Expression: "{value}", subclass could override this * method. - * - * @param valueExpression - * @return + * @param valueExpression expression of value + * @return exclude or not */ protected boolean isExcludedValue(String valueExpression) { return StringUtils.hasText(valueExpression) && valueExpression.startsWith("{") diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java index 1ad2fa89..b10b6317 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Arrays; @@ -23,7 +24,7 @@ import java.util.List; import org.springframework.http.HttpRequest; /** - * Composite {@link HttpRequestMatcher} implementation + * Composite {@link HttpRequestMatcher} implementation. * * @author Mercy */ @@ -69,4 +70,5 @@ public abstract class CompositeHttpRequestMatcher extends AbstractHttpRequestMat protected String getToStringInfix() { return " && "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java index b63ea2ed..08f5cf31 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.MediaType; @@ -21,7 +22,7 @@ import org.springframework.http.MediaType; * Parses and matches a single media type expression to a request's 'Content-Type' header. *

* The source code is scratched from - * org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression + * org.springframework.web.servlet.mvc.condition.ConsumesRequestCondition.ConsumeMediaTypeExpression. * * @author Rossen Stoyanchev * @author Arjen Poutsma @@ -40,4 +41,5 @@ class ConsumeMediaTypeExpression extends AbstractMediaTypeExpression { boolean match = getMediaType().includes(contentType); return (!isNegated() ? match : !match); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java index ce00f66e..277a2591 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.HttpHeaders; @@ -23,7 +24,7 @@ import org.springframework.util.ObjectUtils; * Parses and matches a single header expression to a request. *

* The some source code is scratched from - * org.springframework.web.servlet.mvc.condition.HeadersRequestCondition.HeaderExpression + * org.springframework.web.servlet.mvc.condition.HeadersRequestCondition.HeaderExpression. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -57,4 +58,5 @@ class HeaderExpression extends AbstractNameValueExpression { String headerValue = httpHeaders.getFirst(this.name); return ObjectUtils.nullSafeEquals(this.value, headerValue); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java index c97b4c24..e97f2559 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.ArrayList; @@ -27,7 +28,7 @@ import org.springframework.http.HttpRequest; import org.springframework.http.MediaType; /** - * {@link HttpRequest} 'Content-Type' header {@link HttpRequestMatcher matcher} + * {@link HttpRequest} 'Content-Type' header {@link HttpRequestMatcher matcher}. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -39,9 +40,8 @@ public class HttpRequestConsumersMatcher extends AbstractHttpRequestMatcher { /** * Creates a new instance from 0 or more "consumes" expressions. - * * @param consumes consumes expressions if 0 expressions are provided, the condition - * will match to every request + * will match to every request */ public HttpRequestConsumersMatcher(String... consumes) { this(consumes, null); @@ -52,7 +52,6 @@ public class HttpRequestConsumersMatcher extends AbstractHttpRequestMatcher { * expressions where the header name is not 'Content-Type' or have no header value * defined are ignored. If 0 expressions are provided in total, the condition will * match to every request - * * @param consumes consumes expressions * @param headers headers expressions */ @@ -122,4 +121,5 @@ public class HttpRequestConsumersMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " || "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java index 34ca0419..af0dbafa 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Collection; @@ -23,7 +24,7 @@ import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; /** - * {@link HttpRequest} headers {@link HttpRequestMatcher matcher} + * {@link HttpRequest} headers {@link HttpRequestMatcher matcher}. * * @author Mercy */ @@ -67,4 +68,5 @@ public class HttpRequestHeadersMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " && "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java similarity index 83% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java index 65ef03de..3d485513 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,22 +13,23 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.HttpRequest; /** - * {@link HttpRequest} Matcher + * {@link HttpRequest} Matcher. * * @author Mercy */ public interface HttpRequestMatcher { /** - * Match {@link HttpRequest} or not - * - * @param request The {@link HttpRequest} instance + * Match {@link HttpRequest} or not. + * @param request The {@link HttpRequest} instance. * @return if matched, return true, or false. */ boolean match(HttpRequest request); + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java index 5500d4c6..3a9f0ed6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Collection; @@ -26,7 +27,7 @@ import org.springframework.util.StringUtils; import static org.springframework.http.HttpMethod.resolve; /** - * {@link HttpRequest} {@link HttpMethod methods} {@link HttpRequestMatcher matcher} + * {@link HttpRequest} {@link HttpMethod methods} {@link HttpRequestMatcher matcher}. * * @author Mercy */ @@ -78,4 +79,5 @@ public class HttpRequestMethodsMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " || "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java index 81c9c685..159c8746 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Collection; @@ -23,7 +24,7 @@ import org.springframework.http.HttpRequest; import org.springframework.util.CollectionUtils; /** - * {@link HttpRequest} parameters {@link HttpRequestMatcher matcher} + * {@link HttpRequest} parameters {@link HttpRequestMatcher matcher}. * * @author Mercy */ @@ -33,10 +34,10 @@ public class HttpRequestParamsMatcher extends AbstractHttpRequestMatcher { /** * @param params The pattern of params : - *

    - *
  • name=value
  • - *
  • name
  • - *
+ *
    + *
  • name=value
  • + *
  • name
  • + *
*/ public HttpRequestParamsMatcher(String... params) { this.expressions = parseExpressions(params); @@ -72,4 +73,5 @@ public class HttpRequestParamsMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " && "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java similarity index 98% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java index 9d92654f..0ce2e74a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.net.URI; @@ -29,7 +30,7 @@ import org.springframework.util.PathMatcher; import org.springframework.util.StringUtils; /** - * {@link HttpRequest} {@link URI} {@link HttpRequestMatcher matcher} + * {@link HttpRequest} {@link URI} {@link HttpRequestMatcher matcher}. * * @author Mercy */ @@ -113,4 +114,5 @@ public class HttpRequestPathMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " || "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java index d35445f4..a5d93e16 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.ArrayList; @@ -27,7 +28,7 @@ import org.springframework.http.HttpRequest; import org.springframework.http.MediaType; /** - * {@link HttpRequest} 'Accept' header {@link HttpRequestMatcher matcher} + * {@link HttpRequest} 'Accept' header {@link HttpRequestMatcher matcher}. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -40,7 +41,6 @@ public class HttpRequestProducesMatcher extends AbstractHttpRequestMatcher { /** * Creates a new instance from "produces" expressions. If 0 expressions are provided * in total, this condition will match to any request. - * * @param produces produces expressions */ public HttpRequestProducesMatcher(String... produces) { @@ -52,7 +52,6 @@ public class HttpRequestProducesMatcher extends AbstractHttpRequestMatcher { * expressions where the header name is not 'Accept' or have no header value defined * are ignored. If 0 expressions are provided in total, this condition will match to * any request. - * * @param produces produces expressions * @param headers headers expressions */ @@ -119,4 +118,5 @@ public class HttpRequestProducesMatcher extends AbstractHttpRequestMatcher { protected String getToStringInfix() { return " || "; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java index 5638614a..34078a1a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.MediaType; diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java index 644c4939..066c662b 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; /** @@ -20,7 +21,7 @@ package com.alibaba.cloud.dubbo.http.matcher; * parameters and request header in HTTP request *

* The some source code is scratched from - * org.springframework.web.servlet.mvc.condition.NameValueExpression + * org.springframework.web.servlet.mvc.condition.NameValueExpression. * * @param the value type * @author Rossen Stoyanchev diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java index de7d97a4..d98c0f57 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.springframework.http.HttpRequest; @@ -25,7 +26,7 @@ import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; * Parses and matches a single param expression to a request. *

* The some source code is scratched from - * org.springframework.web.servlet.mvc.condition.ParamsRequestCondition.ParamExpression + * org.springframework.web.servlet.mvc.condition.ParamsRequestCondition.ParamExpression. * * @author Arjen Poutsma * @author Rossen Stoyanchev @@ -59,4 +60,5 @@ class ParamExpression extends AbstractNameValueExpression { String parameterValue = parametersMap.getFirst(this.name); return ObjectUtils.nullSafeEquals(this.value, parameterValue); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java index 79b08fd2..4abb97e8 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.List; @@ -23,7 +24,7 @@ import org.springframework.http.MediaType; * Parses and matches a single media type expression to a request's 'Accept' header. *

* The source code is scratched from - * org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression + * org.springframework.web.servlet.mvc.condition.ProducesRequestCondition.ProduceMediaTypeExpression. * * @author Rossen Stoyanchev * @author Arjen Poutsma @@ -51,4 +52,5 @@ class ProduceMediaTypeExpression extends AbstractMediaTypeExpression { } return false; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java index a0a62483..644e74b7 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import com.alibaba.cloud.dubbo.metadata.RequestMetadata; @@ -20,7 +21,7 @@ import com.alibaba.cloud.dubbo.metadata.RequestMetadata; import static com.alibaba.cloud.dubbo.http.util.HttpUtils.toNameAndValues; /** - * {@link RequestMetadata} {@link HttpRequestMatcher} implementation + * {@link RequestMetadata} {@link HttpRequestMatcher} implementation. * * @author Mercy */ @@ -43,4 +44,5 @@ public class RequestMetadataMatcher extends CompositeHttpRequestMatcher { new HttpRequestProducesMatcher( metadata.getProduces().toArray(new String[0]))); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java index 374ec949..5798ffc2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.util; import java.util.ArrayList; @@ -25,21 +26,18 @@ import com.alibaba.cloud.dubbo.http.converter.HttpMessageConverterHolder; import com.alibaba.cloud.dubbo.metadata.RequestMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; -import org.springframework.core.MethodParameter; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpRequest; import org.springframework.http.MediaType; import org.springframework.http.converter.GenericHttpMessageConverter; import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.server.ServletServerHttpRequest; -import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; import static java.util.Collections.unmodifiableList; /** - * {@link HttpMessageConverter} Resolver + * {@link HttpMessageConverter} Resolver. * * @author Mercy */ @@ -96,11 +94,10 @@ public class HttpMessageConverterResolver { } /** - * Resolve the most match {@link HttpMessageConverter} from {@link RequestMetadata} - * + * Resolve the most match {@link HttpMessageConverter} from {@link RequestMetadata}. * @param requestMetadata {@link RequestMetadata} * @param restMethodMetadata {@link RestMethodMetadata} - * @return + * @return instance of {@link HttpMessageConverterHolder} */ public HttpMessageConverterHolder resolve(RequestMetadata requestMetadata, RestMethodMetadata restMethodMetadata) { @@ -110,7 +107,7 @@ public class HttpMessageConverterResolver { Class returnValueClass = resolveReturnValueClass(restMethodMetadata); /** - * @see AbstractMessageConverterMethodProcessor#writeWithMessageConverters(Object, + * @see AbstractMessageConverterMethodProcessor#writeWithMessageConverters(T, * MethodParameter, ServletServerHttpRequest, ServletServerHttpResponse) */ List requestedMediaTypes = getAcceptableMediaTypes(requestMetadata); @@ -172,8 +169,7 @@ public class HttpMessageConverterResolver { } /** - * Resolve the {@link MediaType media-types} - * + * Resolve the {@link MediaType media-types}. * @param requestMetadata {@link RequestMetadata} from client side * @return non-null {@link List} */ @@ -187,9 +183,8 @@ public class HttpMessageConverterResolver { *

  • The producible media types specified in the request mappings, or *
  • Media types of configured converters that can write the specific return value, * or - *
  • {@link MediaType#ALL} + *
  • {@link MediaType#ALL}. * - * * @param restMethodMetadata {@link RestMethodMetadata} from server side * @param returnValueClass the class of return value * @return non-null {@link List} @@ -218,9 +213,8 @@ public class HttpMessageConverterResolver { /** * Return the media types supported by all provided message converters sorted by * specificity via {@link MediaType#sortBySpecificity(List)}. - * - * @param messageConverters - * @return + * @param messageConverters list of converters + * @return list of MediaTypes */ private List getAllSupportedMediaTypes( List> messageConverters) { @@ -243,4 +237,5 @@ public class HttpMessageConverterResolver { return (MediaType.SPECIFICITY_COMPARATOR.compare(acceptType, produceTypeToUse) <= 0 ? acceptType : produceTypeToUse); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java index 337993cf..28c32921 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.util; import java.io.UnsupportedEncodingException; @@ -35,24 +36,39 @@ import static org.springframework.util.StringUtils.hasText; import static org.springframework.util.StringUtils.trimAllWhitespace; /** - * Http Utilities class + * Http Utilities class. * * @author Mercy */ public abstract class HttpUtils { + /** + * Charset value for Http. + */ private static final String UTF_8 = "UTF-8"; + /** + * Equal operator for Http. + */ private static final String EQUAL = "="; + /** + * And operator for Http. + */ private static final String AND = "&"; + /** + * Semicolon operator for Http. + */ private static final String SEMICOLON = ";"; + /** + * Question Mark operation for Http. + */ private static final String QUESTION_MASK = "?"; /** - * The empty value + * The empty value. */ private static final String EMPTY_VALUE = ""; @@ -60,9 +76,8 @@ public abstract class HttpUtils { * Normalize path: *
      *
    1. To remove query string if presents
    2. - *
    3. To remove duplicated slash("/") if exists
    4. + *
    5. To remove duplicated slash("/") if exists.
    6. *
    - * * @param path path to be normalized * @return a normalized path if required */ @@ -79,10 +94,9 @@ public abstract class HttpUtils { } /** - * Get Parameters from the specified {@link HttpRequest request} - * + * Get Parameters from the specified {@link HttpRequest request}. * @param request the specified {@link HttpRequest request} - * @return + * @return map of parameters */ public static MultiValueMap getParameters(HttpRequest request) { URI uri = request.getURI(); @@ -92,7 +106,6 @@ public abstract class HttpUtils { /** * Get Parameters from the specified query string. *

    - * * @param queryString The query string * @return The query parameters */ @@ -103,7 +116,6 @@ public abstract class HttpUtils { /** * Get Parameters from the specified pairs of name-value. *

    - * * @param pairs The pairs of name-value * @return The query parameters */ @@ -124,7 +136,6 @@ public abstract class HttpUtils { /** * Get Parameters from the specified pairs of name-value. *

    - * * @param pairs The pairs of name-value * @return The query parameters */ @@ -163,8 +174,7 @@ public abstract class HttpUtils { // } /** - * To the name and value line sets - * + * To the name and value line sets. * @param nameAndValuesMap {@link MultiValueMap} the map of name and values * @return non-null */ @@ -187,8 +197,8 @@ public abstract class HttpUtils { } /** - * Generate a string of query string from the specified request parameters {@link Map} - * + * Generate a string of query string from the specified request parameters + * {@link Map}. * @param params the specified request parameters {@link Map} * @return non-null */ @@ -201,8 +211,7 @@ public abstract class HttpUtils { } /** - * Decode value - * + * Decode value. * @param value the value requires to decode * @return the decoded value */ @@ -220,8 +229,7 @@ public abstract class HttpUtils { } /** - * encode value - * + * encode value. * @param value the value requires to encode * @return the encoded value */ @@ -243,4 +251,5 @@ public abstract class HttpUtils { } paramsMap.add(trimAllWhitespace(name), paramValue); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java index bc093720..1dfb8e73 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.util.Collection; @@ -27,7 +28,7 @@ import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL import static org.springframework.util.CollectionUtils.isEmpty; /** - * Dubbo's {@link ProtocolConfig} {@link Supplier} + * Dubbo's {@link ProtocolConfig} {@link Supplier}. * * @author Mercy */ @@ -69,4 +70,5 @@ public class DubboProtocolConfigSupplier implements Supplier { return protocolConfig; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java index b4d6b618..4671a547 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.util.Objects; /** - * Dubbo Rest Service Metadata + * Dubbo Rest Service Metadata. * * @author Mercy */ @@ -59,4 +60,5 @@ public class DubboRestServiceMetadata { public int hashCode() { return Objects.hash(serviceRestMetadata, restMethodMetadata); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java index 98ccbc53..935f287b 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.lang.reflect.Method; @@ -23,7 +24,7 @@ import java.util.Objects; import com.alibaba.cloud.dubbo.annotation.DubboTransported; /** - * {@link MethodMetadata} annotated {@link DubboTransported @DubboTransported} + * {@link MethodMetadata} annotated {@link DubboTransported @DubboTransported}. * * @author Mercy */ @@ -91,4 +92,5 @@ public class DubboTransportedMethodMetadata { public int hashCode() { return Objects.hash(methodMetadata, attributes); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java index 69dbd524..f4536a63 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.lang.reflect.Method; @@ -28,7 +29,7 @@ import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; /** - * {@link Method} Metadata + * {@link Method} Metadata. * * @author Mercy */ @@ -132,4 +133,5 @@ public class MethodMetadata { return "MethodMetadata{" + "name='" + name + '\'' + ", returnType='" + returnType + '\'' + ", params=" + params + ", method=" + method + '}'; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java index 1e26c28e..959ca854 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.lang.reflect.Method; @@ -21,7 +22,7 @@ import java.util.Objects; import com.fasterxml.jackson.annotation.JsonInclude; /** - * {@link Method} Parameter Metadata + * {@link Method} Parameter Metadata. * * @author Mercy */ @@ -81,4 +82,5 @@ public class MethodParameterMetadata { return "MethodParameterMetadata{" + "index=" + index + ", name='" + name + '\'' + ", type='" + type + '\'' + '}'; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java similarity index 98% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java index 1d847d18..eb648580 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.util.ArrayList; @@ -41,7 +42,7 @@ import static com.alibaba.cloud.dubbo.http.util.HttpUtils.normalizePath; import static org.springframework.http.MediaType.parseMediaTypes; /** - * Request Metadata + * Request Metadata. * * @author Mercy */ @@ -268,4 +269,5 @@ public class RequestMetadata { + ", params=" + params + ", headers=" + headers + ", consumes=" + consumes + ", produces=" + produces + '}'; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java similarity index 99% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java index 3846b629..71a4d45c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.lang.reflect.Type; @@ -229,4 +230,5 @@ public class RestMethodMetadata { + ", indexToName=" + indexToName + ", formParams=" + formParams + ", indexToEncoded=" + indexToEncoded + '}'; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java index 963edb09..2f5e6a04 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.util.Objects; @@ -65,4 +66,5 @@ public class ServiceRestMetadata { public int hashCode() { return Objects.hash(url, meta); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java index f8f04c97..abd27b7f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.repository; import java.util.Collections; @@ -37,7 +38,6 @@ import com.alibaba.cloud.dubbo.service.DubboMetadataService; import com.alibaba.cloud.dubbo.service.DubboMetadataServiceExporter; import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; import com.alibaba.cloud.dubbo.util.JSONUtils; - import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.type.TypeFactory; import org.apache.dubbo.common.URL; @@ -73,7 +73,7 @@ import static org.springframework.util.CollectionUtils.isEmpty; import static org.springframework.util.StringUtils.hasText; /** - * Dubbo Service Metadata {@link Repository} + * Dubbo Service Metadata {@link Repository}. * * @author Mercy */ @@ -82,7 +82,7 @@ public class DubboServiceMetadataRepository implements SmartInitializingSingleton, ApplicationEventPublisherAware { /** - * The prefix of {@link DubboMetadataService} : "dubbo.metadata-service." + * The prefix of {@link DubboMetadataService} : "dubbo.metadata-service.". */ public static final String DUBBO_METADATA_SERVICE_PREFIX = "dubbo.metadata-service."; @@ -139,6 +139,7 @@ public class DubboServiceMetadataRepository * from the annotated methods. */ private final Set serviceRestMetadata = new LinkedHashSet<>(); + private ApplicationEventPublisher applicationEventPublisher; // ==================================================================================== @@ -296,12 +297,15 @@ public class DubboServiceMetadataRepository } /** - * Remove the metadata of Dubbo Services if no there is no service instance. + * Remove the metadata and initialized service of Dubbo Services if no there is no + * service instance. * @param serviceName the service name */ - public void removeInitializedService(String serviceName) { + public void removeMetadataAndInitializedService(String serviceName) { synchronized (monitor) { initializedServices.remove(serviceName); + dubboRestServiceMetadataRepository.remove(serviceName); + subscribedDubboMetadataServiceURLs.remove(serviceName); } } @@ -389,11 +393,9 @@ public class DubboServiceMetadataRepository return emptyList(); } - return hasText(protocol) - ? urls.stream() - .filter(url -> url.getProtocol().equalsIgnoreCase(protocol)) - .collect(Collectors.toList()) - : unmodifiableList(urls); + return hasText(protocol) ? urls.stream() + .filter(url -> url.getProtocol().equalsIgnoreCase(protocol)) + .collect(Collectors.toList()) : unmodifiableList(urls); } /** @@ -645,11 +647,6 @@ public class DubboServiceMetadataRepository dubboMetadataConfigServiceProxy.initProxy(serviceName, version); } - public void removeMetadata(String serviceName) { - dubboRestServiceMetadataRepository.remove(serviceName); - subscribedDubboMetadataServiceURLs.remove(serviceName); - } - @Override public void setApplicationEventPublisher( ApplicationEventPublisher applicationEventPublisher) { diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java similarity index 99% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java index 1ba6fb44..821e3043 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java @@ -35,4 +35,4 @@ public interface MetadataServiceInstanceSelector { */ Optional choose(List serviceInstances); -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java index dfb1b97c..9613e99c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.resolver; import java.lang.reflect.Method; @@ -28,7 +29,6 @@ import java.util.stream.Stream; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; - import feign.Contract; import feign.Feign; import feign.MethodMetadata; @@ -141,7 +141,7 @@ public class DubboServiceBeanMetadataResolver Class targetType) { List methodMetadataList = Collections.emptyList(); try { - methodMetadataList = contract.parseAndValidatateMetadata(targetType); + methodMetadataList = contract.parseAndValidateMetadata(targetType); } catch (Throwable ignored) { // ignore @@ -153,7 +153,7 @@ public class DubboServiceBeanMetadataResolver * Select feign contract methods *

    * extract some code from - * {@link Contract.BaseContract#parseAndValidatateMetadata(java.lang.Class)}. + * {@link Contract.BaseContract#parseAndValidateMetadata(Class)}. * @param targetType class of type * @return non-null */ @@ -199,4 +199,4 @@ public class DubboServiceBeanMetadataResolver this.classLoader = classLoader; } -} \ No newline at end of file +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java index 40569b31..c060ee3f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.resolver; import java.util.LinkedHashMap; @@ -25,7 +26,7 @@ import org.springframework.core.env.PropertyResolver; import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; /** - * {@link DubboTransported} annotation attributes resolver + * {@link DubboTransported} annotation attributes resolver. * * @author Mercy */ @@ -53,4 +54,5 @@ public class DubboTransportedAttributesResolver { } return resolvedAttributes; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java index 16004926..2dc19461 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.resolver; import java.lang.reflect.Method; @@ -25,7 +26,6 @@ import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.metadata.DubboTransportedMethodMetadata; import com.alibaba.cloud.dubbo.metadata.MethodMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; - import feign.Contract; import org.springframework.core.annotation.AnnotationUtils; @@ -90,7 +90,7 @@ public class DubboTransportedMethodMetadataResolver { private Map resolveRestRequestMetadataMap( Class targetType) { - return contract.parseAndValidatateMetadata(targetType).stream().collect(Collectors + return contract.parseAndValidateMetadata(targetType).stream().collect(Collectors .toMap(feign.MethodMetadata::configKey, this::restMethodMetadata)); } @@ -115,4 +115,5 @@ public class DubboTransportedMethodMetadataResolver { } return dubboTransported; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java index 114b7a1f..b71d1778 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.resolver; import java.util.Set; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; - import org.apache.dubbo.config.spring.ServiceBean; /** diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java index c4d6c0ea..27917763 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.openfeign; import java.lang.reflect.InvocationHandler; @@ -22,7 +23,6 @@ import java.util.Map; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContext; import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; - import org.apache.dubbo.rpc.service.GenericService; import org.springframework.util.ClassUtils; @@ -30,7 +30,7 @@ import org.springframework.util.ClassUtils; import static org.apache.dubbo.common.utils.PojoUtils.realize; /** - * Dubbo {@link GenericService} for {@link InvocationHandler} + * Dubbo {@link GenericService} for {@link InvocationHandler}. * * @author Mercy */ @@ -88,4 +88,5 @@ public class DubboInvocationHandler implements InvocationHandler { String returnType = dubboRestMethodMetadata.getReturnType(); return ClassUtils.resolveClassName(returnType, classLoader); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java index 6c3a957b..8fb561b1 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,16 +13,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.openfeign; import java.lang.reflect.Method; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; - import org.apache.dubbo.rpc.service.GenericService; /** - * Feign {@link Method} Metadata + * Feign {@link Method} Metadata. * * @author Mercy */ @@ -53,4 +53,5 @@ class FeignMethodMetadata { RestMethodMetadata getFeignMethodMetadata() { return feignMethodMetadata; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java index da173a07..fdb1f288 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.openfeign; import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; @@ -31,7 +32,7 @@ import static org.springframework.util.ClassUtils.isPresent; import static org.springframework.util.ClassUtils.resolveClassName; /** - * org.springframework.cloud.openfeign.Targeter {@link BeanPostProcessor} + * org.springframework.cloud.openfeign.Targeter {@link BeanPostProcessor}. * * @author Mercy */ @@ -84,4 +85,5 @@ public class TargeterBeanPostProcessor public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java index 3e99ac77..a4247440 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.openfeign; import java.lang.reflect.InvocationHandler; @@ -31,7 +32,6 @@ import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepositor import com.alibaba.cloud.dubbo.metadata.resolver.DubboTransportedMethodMetadataResolver; import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; - import feign.Contract; import feign.Target; import org.apache.dubbo.rpc.service.GenericService; @@ -44,7 +44,7 @@ import org.springframework.core.env.Environment; import static java.lang.reflect.Proxy.newProxyInstance; /** - * org.springframework.cloud.openfeign.Targeter {@link InvocationHandler} + * org.springframework.cloud.openfeign.Targeter {@link InvocationHandler}. * * @author Mercy */ @@ -84,7 +84,7 @@ class TargeterInvocationHandler implements InvocationHandler { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { /** * args[0]: FeignClientFactoryBean factory args[1]: Feign.Builder feign args[2]: - * FeignContext context args[3]: Target.HardCodedTarget target + * FeignContext context args[3]: Target.HardCodedTarget<T> target */ FeignContext feignContext = cast(args[2]); Target.HardCodedTarget target = cast(args[3]); @@ -183,4 +183,5 @@ class TargeterInvocationHandler implements InvocationHandler { return feignMethodMetadataMap; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java index 1299980a..ce69c823 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -222,11 +222,17 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { Collection serviceInstances = serviceInstancesFunction .apply(serviceName); + // issue : ReStarting a consumer and then starting a provider does not + // automatically discover the registration + // fix https://github.com/alibaba/spring-cloud-alibaba/issues/753 + // Re-obtain the latest list of available metadata address here, ip or port may + // change. + // by https://github.com/wangzihaogithub + dubboMetadataConfigServiceProxy.removeProxy(serviceName); + repository.removeMetadataAndInitializedService(serviceName); + dubboGenericServiceFactory.destroy(serviceName); + repository.initializeMetadata(serviceName); if (CollectionUtils.isEmpty(serviceInstances)) { - dubboMetadataConfigServiceProxy.removeProxy(serviceName); - repository.removeInitializedService(serviceName); - repository.removeMetadata(serviceName); - dubboGenericServiceFactory.destroy(serviceName); if (logger.isWarnEnabled()) { logger.warn( "There is no instance from service[name : {}], and then Dubbo Service[key : {}] will not be " @@ -247,18 +253,6 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { DubboMetadataService dubboMetadataService = dubboMetadataConfigServiceProxy .getProxy(serviceName); - - if (dubboMetadataService == null) { // If not found, try to initialize - if (logger.isInfoEnabled()) { - logger.info( - "The metadata of Dubbo service[key : {}] can't be found when the subscribed service[name : {}], " - + "and then try to initialize it", - url.getServiceKey(), serviceName); - } - repository.initializeMetadata(serviceName); - dubboMetadataService = dubboMetadataConfigServiceProxy.getProxy(serviceName); - } - if (dubboMetadataService == null) { // It makes sure not-found, return immediately if (logger.isWarnEnabled()) { logger.warn( @@ -270,7 +264,6 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { } List exportedURLs = getExportedURLs(dubboMetadataService, url); - for (URL exportedURL : exportedURLs) { String protocol = exportedURL.getProtocol(); List subscribedURLs = new LinkedList<>(); diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java index f08f7df9..1af716f3 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry; import java.net.URI; diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java index 3131f229..43e679f5 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,11 +13,11 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry; import com.alibaba.cloud.dubbo.registry.event.ServiceInstancePreRegisteredEvent; import com.alibaba.cloud.dubbo.registry.event.ServiceInstanceRegisteredEvent; - import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @@ -28,7 +28,7 @@ import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; /** - * Dubbo Service Registration Event-Publishing Aspect + * Dubbo Service Registration Event-Publishing Aspect. * * @author Mercy * @see ServiceInstancePreRegisteredEvent @@ -39,7 +39,7 @@ public class DubboServiceRegistrationEventPublishingAspect implements ApplicationEventPublisherAware { /** - * The pointcut expression for {@link ServiceRegistry#register(Registration)} + * The pointcut expression for {@link ServiceRegistry#register(Registration)}. */ public static final String REGISTER_POINTCUT_EXPRESSION = "execution(* org.springframework.cloud.client.serviceregistry.ServiceRegistry.register(*)) && args(registration)"; @@ -62,4 +62,5 @@ public class DubboServiceRegistrationEventPublishingAspect ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java index fe732dab..3e4a1a5c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java similarity index 98% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java index c3a9fe89..be13cb91 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java index fee5a742..4733fef6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry.event; import org.springframework.cloud.client.ServiceInstance; @@ -22,7 +23,7 @@ import org.springframework.context.ApplicationEvent; /** * The before-{@link ServiceRegistry#register(Registration) register} event for - * {@link ServiceInstance} + * {@link ServiceInstance}. * * @author Mercy */ @@ -36,4 +37,5 @@ public class ServiceInstancePreRegisteredEvent extends ApplicationEvent { public Registration getSource() { return (Registration) super.getSource(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java index 7c6c0742..81b4e2b6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry.event; import org.springframework.cloud.client.serviceregistry.Registration; @@ -21,7 +22,7 @@ import org.springframework.context.ApplicationEvent; /** * The after-{@link ServiceRegistry#register(Registration) register} event for - * {@link Registration} + * {@link Registration}. * * @author Mercy */ @@ -35,4 +36,5 @@ public class ServiceInstanceRegisteredEvent extends ApplicationEvent { public Registration getSource() { return (Registration) super.getSource(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java index 2f997ef0..f69954b3 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry.event; import java.util.Collection; @@ -64,25 +65,25 @@ public class ServiceInstancesChangedEvent extends ApplicationEvent { } /** - * @return all {@link ServiceInstance service instances} + * @return all {@link ServiceInstance service instances}. */ public Collection getServiceInstances() { return serviceInstances; } /** - * Mark current event being processed + * Mark current event being processed. */ public void processed() { processed = true; } /** - * Current event has been processed or not - * + * Current event has been processed or not. * @return if processed, return true, or false */ public boolean isProcessed() { return processed; } -} \ No newline at end of file + +} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java index 9ad31d16..df8168c0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry.event; import java.util.LinkedHashSet; @@ -22,7 +23,7 @@ import java.util.Set; import org.springframework.context.ApplicationEvent; /** - * {@link ApplicationEvent Event} raised when the subscribed services are changed + * {@link ApplicationEvent Event} raised when the subscribed services are changed. *

    * * @author Mercy @@ -61,4 +62,5 @@ public class SubscribedServicesChangedEvent extends ApplicationEvent { public boolean isChanged() { return changed; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java index 8be35973..5e9d4877 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import org.apache.dubbo.rpc.service.GenericService; /** - * Dubbo {@link GenericService} execution context + * Dubbo {@link GenericService} execution context. * * @author Mercy */ @@ -48,4 +49,5 @@ public class DubboGenericServiceExecutionContext { public Object[] getParameters() { return parameters; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java index da94b258..29017ce4 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Collections; @@ -32,7 +33,7 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.AnnotationAwareOrderComparator; /** - * {@link DubboGenericServiceExecutionContext} Factory + * {@link DubboGenericServiceExecutionContext} Factory. * * @author Mercy * @see DubboGenericServiceParameterResolver @@ -154,4 +155,5 @@ public class DubboGenericServiceExecutionContextFactory { return parameters; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java similarity index 99% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java index 2acffbd2..9ddee6b3 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java similarity index 84% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java index 6c766c59..a6cb949e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.List; @@ -20,7 +21,6 @@ import java.util.Map; import java.util.Set; import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; - import org.apache.dubbo.common.URL; import org.apache.dubbo.config.annotation.Service; @@ -29,49 +29,46 @@ import org.apache.dubbo.config.annotation.Service; * stable of structure in every evolution , makes sure all subscribers' compatibility. *

    * The interface contract's version must be {@link #VERSION} constant and group must be - * current Dubbo application name + * current Dubbo application name. * * @author Mercy */ public interface DubboMetadataService { /** - * Current version of the interface contract + * Current version of the interface contract. */ String VERSION = "1.0.0"; /** - * Get the json content of {@link ServiceRestMetadata} {@link Set} - * + * Get the json content of {@link ServiceRestMetadata} {@link Set}. * @return null if present */ String getServiceRestMetadata(); /** - * Get all exported {@link URL#getServiceKey() service keys} - * + * Get all exported {@link URL#getServiceKey() service keys}. * @return non-null read-only {@link Set} */ Set getAllServiceKeys(); /** * Get all exported Dubbo's {@link URL URLs} {@link Map} whose key is the return value - * of {@link URL#getServiceKey()} method and value is the json content of List of - * {@link URL URLs} - * + * of {@link URL#getServiceKey()} method and value is the json content of + * List<URL> of {@link URL URLs}. * @return non-null read-only {@link Map} */ Map getAllExportedURLs(); /** - * Get the json content of an exported List of {@link URL URLs} by the - * serviceInterface , group and version - * + * Get the json content of an exported List of {@link URL URLs} by the + * serviceInterface, group and version. * @param serviceInterface The class name of service interface * @param group {@link Service#group() the service group} (optional) - * @param version {@link Service#version() the service version} (optional) + * @param version {@link Service#version() the service version} (optional)~ * @return non-null read-only {@link List} * @see URL */ String getExportedURLs(String serviceInterface, String group, String version); + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java index 87654159..e4b0bb55 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.List; @@ -33,7 +34,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; /** - * {@link DubboMetadataService} exporter + * {@link DubboMetadataService} exporter. * * @author Mercy */ @@ -60,8 +61,7 @@ public class DubboMetadataServiceExporter { private ServiceConfig serviceConfig; /** - * export {@link DubboMetadataService} as Dubbo service - * + * export {@link DubboMetadataService} as Dubbo service. * @return the exported {@link URL URLs} */ public List export() { @@ -91,7 +91,7 @@ public class DubboMetadataServiceExporter { } /** - * unexport {@link DubboMetadataService} + * unexport {@link DubboMetadataService}. */ @PreDestroy public void unexport() { @@ -107,4 +107,5 @@ public class DubboMetadataServiceExporter { serviceConfig.toString()); } } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java similarity index 71% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java index f908e8f7..ca90a608 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,14 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.stream.Stream; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; - import org.apache.dubbo.rpc.service.GenericService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,12 +35,8 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler { private final GenericService genericService; - private final DubboCloudProperties dubboCloudProperties; - DubboMetadataServiceInvocationHandler(String serviceName, String version, - DubboGenericServiceFactory dubboGenericServiceFactory, - DubboCloudProperties dubboCloudProperties) { - this.dubboCloudProperties = dubboCloudProperties; + DubboGenericServiceFactory dubboGenericServiceFactory) { this.genericService = dubboGenericServiceFactory.create(serviceName, DubboMetadataService.class, version); } @@ -49,16 +44,13 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object returnValue = null; - for (int i = 1; i <= dubboCloudProperties.getRetryCount(); i++) { - try { - returnValue = genericService.$invoke(method.getName(), - getParameterTypes(method), args); - } - catch (Throwable e) { - if (logger.isErrorEnabled()) { - logger.error("[failed " + i + " times] " + e.getMessage(), e); - } - Thread.sleep(dubboCloudProperties.getInterval() * i); + try { + returnValue = genericService.$invoke(method.getName(), + getParameterTypes(method), args); + } + catch (Throwable e) { + if (logger.isErrorEnabled()) { + logger.error(e.getMessage(), e); } } return returnValue; diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java similarity index 88% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java index 5a86b9d9..359ee5e0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,12 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; - import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.DisposableBean; @@ -34,17 +33,13 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab private final DubboGenericServiceFactory dubboGenericServiceFactory; - private final DubboCloudProperties dubboCloudProperties; - private final Map dubboMetadataServiceCache = new ConcurrentHashMap<>(); private ClassLoader classLoader; public DubboMetadataServiceProxy( - DubboGenericServiceFactory dubboGenericServiceFactory, - DubboCloudProperties dubboCloudProperties) { + DubboGenericServiceFactory dubboGenericServiceFactory) { this.dubboGenericServiceFactory = dubboGenericServiceFactory; - this.dubboCloudProperties = dubboCloudProperties; } /** @@ -97,7 +92,7 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab return (DubboMetadataService) newProxyInstance(classLoader, new Class[] { DubboMetadataService.class }, new DubboMetadataServiceInvocationHandler(serviceName, version, - dubboGenericServiceFactory, dubboCloudProperties)); + dubboGenericServiceFactory)); } } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java index 3b167f80..e30062d6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service; import java.util.Collections; @@ -24,7 +25,6 @@ import java.util.Set; import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; import com.alibaba.cloud.dubbo.util.JSONUtils; - import org.apache.dubbo.common.URL; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -36,7 +36,7 @@ import static java.util.Collections.unmodifiableMap; import static org.springframework.util.CollectionUtils.isEmpty; /** - * Introspective {@link DubboMetadataService} implementation + * Introspective {@link DubboMetadataService} implementation. * * @author Mercy */ @@ -95,4 +95,5 @@ public class IntrospectiveDubboMetadataService implements DubboMetadataService { private DubboServiceMetadataRepository getRepository() { return dubboServiceMetadataRepository.getIfAvailable(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java index 8f677895..d7c71993 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import org.springframework.beans.factory.BeanClassLoaderAware; @@ -25,7 +26,7 @@ import static org.springframework.context.ConfigurableApplicationContext.CONVERS import static org.springframework.util.ClassUtils.resolveClassName; /** - * Abstract {@link DubboGenericServiceParameterResolver} implementation + * Abstract {@link DubboGenericServiceParameterResolver} implementation. * * @author Mercy */ @@ -78,4 +79,5 @@ public abstract class AbstractDubboGenericServiceParameterResolver protected Object resolveValue(Object parameterValue, Class parameterType) { return conversionService.convert(parameterValue, parameterType); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java similarity index 94% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java index 179d78e5..2fa4511f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import java.util.Collection; @@ -30,7 +31,7 @@ import static org.springframework.util.ObjectUtils.isEmpty; /** * Abstract HTTP Names Value {@link DubboGenericServiceParameterResolver Dubbo - * GenericService Parameter Resolver} + * GenericService Parameter Resolver}. * * @author Mercy */ @@ -38,10 +39,9 @@ public abstract class AbstractNamedValueServiceParameterResolver extends AbstractDubboGenericServiceParameterResolver { /** - * Get the {@link MultiValueMap} of names and values - * - * @param request - * @return + * Get the {@link MultiValueMap} of names and values. + * @param request Http server request + * @return map of name and values */ protected abstract MultiValueMap getNameAndValuesMap( HttpServerRequest request); diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java index 3805ee9e..a3a58313 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,18 +13,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import com.alibaba.cloud.dubbo.http.HttpServerRequest; import com.alibaba.cloud.dubbo.metadata.MethodParameterMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; - import org.apache.dubbo.rpc.service.GenericService; import org.springframework.core.Ordered; /** - * Dubbo {@link GenericService} Parameter Resolver + * Dubbo {@link GenericService} Parameter Resolver. * * @author Mercy */ @@ -43,4 +43,5 @@ public interface DubboGenericServiceParameterResolver extends Ordered { Object resolve(RestMethodMetadata restMethodMetadata, MethodParameterMetadata methodParameterMetadata, RestMethodMetadata clientRestMethodMetadata, Object[] arguments); + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java similarity index 90% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java index bda4f044..047e569c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import com.alibaba.cloud.dubbo.http.HttpServerRequest; @@ -21,13 +22,16 @@ import org.springframework.util.MultiValueMap; /** * HTTP Request Path Variable {@link DubboGenericServiceParameterResolver Dubbo - * GenericService Parameter Resolver} + * GenericService Parameter Resolver}. * * @author Mercy */ public class PathVariableServiceParameterResolver extends AbstractNamedValueServiceParameterResolver { + /** + * default order. + */ public static final int DEFAULT_ORDER = 3; public PathVariableServiceParameterResolver() { @@ -40,4 +44,5 @@ public class PathVariableServiceParameterResolver HttpServerRequest request) { return request.getQueryParams(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java index eb35ac28..2969b5d6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import java.io.IOException; @@ -34,13 +35,16 @@ import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.HttpMessageNotReadableException; /** - * HTTP Request Body {@link DubboGenericServiceParameterResolver} + * HTTP Request Body {@link DubboGenericServiceParameterResolver}. * * @author Mercy */ public class RequestBodyServiceParameterResolver extends AbstractDubboGenericServiceParameterResolver { + /** + * Default order of RequestBodyServiceParameterResolver. + */ public static final int DEFAULT_ORDER = 7; @Autowired @@ -123,4 +127,5 @@ public class RequestBodyServiceParameterResolver Integer clientBodyIndex = clientRestMethodMetadata.getBodyIndex(); return arguments[clientBodyIndex]; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java index 62b44eb6..86a531b8 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import com.alibaba.cloud.dubbo.http.HttpServerRequest; @@ -21,13 +22,16 @@ import org.springframework.util.MultiValueMap; /** * HTTP Request Header {@link DubboGenericServiceParameterResolver Dubbo GenericService - * Parameter Resolver} + * Parameter Resolver}. * * @author Mercy */ public class RequestHeaderServiceParameterResolver extends AbstractNamedValueServiceParameterResolver { + /** + * default order. + */ public static final int DEFAULT_ORDER = 9; public RequestHeaderServiceParameterResolver() { @@ -40,4 +44,5 @@ public class RequestHeaderServiceParameterResolver HttpServerRequest request) { return request.getHeaders(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java index 3524ae2c..e1d0b72d 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.service.parameter; import com.alibaba.cloud.dubbo.http.HttpServerRequest; @@ -21,13 +22,16 @@ import org.springframework.util.MultiValueMap; /** * HTTP Request Parameter {@link DubboGenericServiceParameterResolver Dubbo GenericService - * Parameter Resolver} + * Parameter Resolver}. * * @author Mercy */ public class RequestParamServiceParameterResolver extends AbstractNamedValueServiceParameterResolver { + /** + * Default order. + */ public static final int DEFAULT_ORDER = 1; public RequestParamServiceParameterResolver() { @@ -40,4 +44,5 @@ public class RequestParamServiceParameterResolver HttpServerRequest request) { return request.getQueryParams(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java index 4ec45392..7aa2ee4c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.util; import java.io.IOException; @@ -33,7 +34,7 @@ import org.slf4j.LoggerFactory; import org.springframework.util.StringUtils; /** - * JSON Utilities class + * JSON Utilities class. * * @author Mercy */ @@ -84,4 +85,5 @@ public class JSONUtils { } return list; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.registry.RegistryFactory b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.registry.RegistryFactory similarity index 100% rename from spring-cloud-alibaba-dubbo/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.registry.RegistryFactory rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/dubbo/com.alibaba.dubbo.registry.RegistryFactory diff --git a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties similarity index 96% rename from spring-cloud-alibaba-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties index 4c9e0c57..19c4bb44 100644 --- a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/dubbo/default/actuator-endpoints.properties @@ -4,4 +4,4 @@ management.endpoint.dubborestmetadata.enabled = true # "management.endpoints.web.base-path" should not be configured in this file # Re-defines path-mapping of Dubbo Web Endpoints -management.endpoints.web.path-mapping.dubborestmetadata = dubbo/rest/metadata \ No newline at end of file +management.endpoints.web.path-mapping.dubborestmetadata = dubbo/rest/metadata diff --git a/spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-alibaba-dubbo/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java similarity index 87% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java index 2ee01446..0fac7ac2 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,15 +13,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import org.springframework.boot.test.context.SpringBootTest; /** - * {@link DubboServiceRegistrationAutoConfiguration} Test + * {@link DubboServiceRegistrationAutoConfiguration} Test. * * @author Mercy */ @SpringBootTest public class DubboServiceRegistrationAutoConfigurationTest { + } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java similarity index 90% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java index 3a13282e..d93aa587 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,12 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Test; /** - * {@link AbstractHttpRequestMatcher} Test + * {@link AbstractHttpRequestMatcher} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java index 34e0ccad..c38b5ba6 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.lang.reflect.Constructor; @@ -25,7 +26,7 @@ import org.springframework.core.ResolvableType; import org.springframework.http.MediaType; /** - * {@link AbstractMediaTypeExpression} Test + * {@link AbstractMediaTypeExpression} Test. * * @author Mercy */ @@ -72,4 +73,5 @@ public abstract class AbstractMediaTypeExpressionTestMercy */ @@ -79,4 +80,5 @@ public abstract class AbstractNameValueExpressionTestMercy */ @@ -32,15 +33,16 @@ public class ConsumeMediaTypeExpressionTest public void testMatch() { ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.APPLICATION_JSON_VALUE + ";q=0.7"); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON)); expression = createExpression(MediaType.TEXT_HTML_VALUE); - Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON_UTF8)); + Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON)); } + } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java index 54bcefd6..ec59b639 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Assert; @@ -23,7 +24,7 @@ import org.springframework.http.HttpRequest; import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; /** - * {@link HeaderExpression} Test + * {@link HeaderExpression} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java index 4f11e8c2..4a43effe 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Arrays; @@ -23,7 +24,7 @@ import org.junit.Assert; import org.springframework.http.HttpMethod; /** - * {@link HttpRequestMethodsMatcher} Test + * {@link HttpRequestMethodsMatcher} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java similarity index 96% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java index bbc20182..c27059a0 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.net.URI; @@ -23,7 +24,7 @@ import org.junit.Test; import org.springframework.mock.http.client.MockClientHttpRequest; /** - * {@link HttpRequestParamsMatcher} Test + * {@link HttpRequestParamsMatcher} Test. * * @author Mercy */ @@ -93,4 +94,5 @@ public class HttpRequestParamsMatcherTest { request.setURI(URI.create("http://dummy/?d=1")); Assert.assertFalse(matcher.match(request)); } + } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java similarity index 95% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java index 2351748b..2d1a67e0 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Assert; @@ -23,7 +24,7 @@ import org.springframework.http.HttpRequest; import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; /** - * {@link ParamExpression} Test + * {@link ParamExpression} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java index 274a2933..1e4e70ad 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.matcher; import java.util.Arrays; @@ -23,7 +24,7 @@ import org.junit.Test; import org.springframework.http.MediaType; /** - * {@link ProduceMediaTypeExpression} Test + * {@link ProduceMediaTypeExpression} Test. * * @author Mercy */ @@ -40,4 +41,5 @@ public class ProduceMediaTypeExpressionTest expression = createExpression(MediaType.APPLICATION_JSON_VALUE); Assert.assertFalse(expression.match(Arrays.asList(MediaType.APPLICATION_XML))); } + } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java similarity index 92% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java index ef2f8669..c7165428 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.http.util; import org.junit.Assert; import org.junit.Test; /** - * {@link HttpUtils} Test + * {@link HttpUtils} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java similarity index 97% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java index c0741e3a..f19339f6 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata; import java.util.Arrays; @@ -23,7 +24,7 @@ import org.junit.Assert; import org.junit.Test; /** - * {@link RequestMetadata} Test + * {@link RequestMetadata} Test. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java similarity index 93% rename from spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java index 95699a2d..8254f1b8 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -13,13 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.metadata.resolver; import java.util.Set; import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.metadata.DubboTransportedMethodMetadata; - import org.junit.Assert; import org.junit.Before; import org.junit.Test; @@ -28,7 +28,7 @@ import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.mock.env.MockEnvironment; /** - * {@link DubboTransportedMethodMetadataResolver} Test + * {@link DubboTransportedMethodMetadataResolver} Test. * * @author Mercy */ @@ -58,4 +58,5 @@ public class DubboTransportedMethodMetadataResolverTest { String test(String message); } + } diff --git a/spring-cloud-alibaba-dubbo/src/test/resources/application.yaml b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/resources/application.yaml similarity index 100% rename from spring-cloud-alibaba-dubbo/src/test/resources/application.yaml rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/resources/application.yaml diff --git a/spring-cloud-alibaba-dubbo/src/test/resources/bootstrap.yaml b/spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/resources/bootstrap.yaml similarity index 100% rename from spring-cloud-alibaba-dubbo/src/test/resources/bootstrap.yaml rename to spring-cloud-alibaba-starters/spring-cloud-starter-dubbo/src/test/resources/bootstrap.yaml diff --git a/spring-cloud-stream-binder-rocketmq/pom.xml b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/pom.xml similarity index 91% rename from spring-cloud-stream-binder-rocketmq/pom.xml rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/pom.xml index 28de8d3c..f16a0aae 100644 --- a/spring-cloud-stream-binder-rocketmq/pom.xml +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/pom.xml @@ -1,20 +1,19 @@ + 4.0.0 com.alibaba.cloud - spring-cloud-alibaba + spring-cloud-alibaba-starters 2.0.1.RELEASE ../pom.xml - 4.0.0 - spring-cloud-stream-binder-rocketmq - Spring Cloud Alibaba RocketMQ Binder + spring-cloud-starter-stream-rocketmq + Spring Cloud Starter Stream RocketMQ - org.springframework.cloud spring-cloud-stream @@ -60,8 +59,6 @@ spring-boot-starter-test test - - diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java similarity index 52% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java index e2a527dd..47e4b9e7 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -22,23 +22,30 @@ import static org.apache.rocketmq.spring.support.RocketMQHeaders.PREFIX; * @author Jim * @author Xiejiashuai */ -public interface RocketMQBinderConstants { +public final class RocketMQBinderConstants { /** - * Header key + * Header key for RocketMQ Transactional Args. */ - String ROCKET_TRANSACTIONAL_ARG = "TRANSACTIONAL_ARG"; + public static final String ROCKET_TRANSACTIONAL_ARG = "TRANSACTIONAL_ARG"; /** - * Default value + * Default NameServer value. */ - String DEFAULT_NAME_SERVER = "127.0.0.1:9876"; - - String DEFAULT_GROUP = PREFIX + "binder_default_group_name"; + public static final String DEFAULT_NAME_SERVER = "127.0.0.1:9876"; /** - * RocketMQ re-consume times + * Default group for SCS RocketMQ Binder. */ - String ROCKETMQ_RECONSUME_TIMES = PREFIX + "RECONSUME_TIMES"; + public static final String DEFAULT_GROUP = PREFIX + "binder_default_group_name"; + + /** + * RocketMQ re-consume times. + */ + public static final String ROCKETMQ_RECONSUME_TIMES = PREFIX + "RECONSUME_TIMES"; + + private RocketMQBinderConstants() { + throw new AssertionError("Must not instantiate constant utility class"); + } } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java similarity index 81% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java index db982da6..c7daff0e 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +16,23 @@ package com.alibaba.cloud.stream.binder.rocketmq; -import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; +import java.util.Arrays; +import java.util.List; +import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; /** * @author Jim */ -public class RocketMQBinderUtils { +public final class RocketMQBinderUtils { + + private RocketMQBinderUtils() { + + } public static RocketMQBinderConfigurationProperties mergeProperties( RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties, @@ -35,7 +42,8 @@ public class RocketMQBinderUtils { result.setNameServer(rocketBinderConfigurationProperties.getNameServer()); } else { - result.setNameServer(rocketMQProperties.getNameServer()); + result.setNameServer( + Arrays.asList(rocketMQProperties.getNameServer().split(";"))); } if (rocketMQProperties.getProducer() == null || StringUtils.isEmpty(rocketMQProperties.getProducer().getAccessKey())) { @@ -71,4 +79,11 @@ public class RocketMQBinderUtils { return result; } + public static String getNameServerStr(List nameServerList) { + if (CollectionUtils.isEmpty(nameServerList)) { + return null; + } + return String.join(";", nameServerList); + } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java similarity index 86% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java index 41958556..b46acc9c 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -35,7 +35,6 @@ import com.alibaba.cloud.stream.binder.rocketmq.provisioning.RocketMQTopicProvis import com.alibaba.cloud.stream.binder.rocketmq.provisioning.selector.PartitionMessageQueueSelector; import com.alibaba.cloud.stream.binder.rocketmq.support.JacksonRocketMQHeaderMapper; import com.alibaba.cloud.stream.binder.rocketmq.support.RocketMQHeaderMapper; - import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.rocketmq.acl.common.AclClientRPCHook; import org.apache.rocketmq.acl.common.SessionCredentials; @@ -47,15 +46,18 @@ import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.apache.rocketmq.spring.support.RocketMQUtil; import org.springframework.cloud.stream.binder.AbstractMessageChannelBinder; +import org.springframework.cloud.stream.binder.BinderSpecificPropertiesProvider; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedProducerProperties; import org.springframework.cloud.stream.binder.ExtendedPropertiesBinder; +import org.springframework.cloud.stream.binding.MessageConverterConfigurer; import org.springframework.cloud.stream.provisioning.ConsumerDestination; import org.springframework.cloud.stream.provisioning.ProducerDestination; +import org.springframework.integration.StaticMessageHeaderAccessor; +import org.springframework.integration.acks.AcknowledgmentCallback; +import org.springframework.integration.acks.AcknowledgmentCallback.Status; +import org.springframework.integration.channel.AbstractMessageChannel; import org.springframework.integration.core.MessageProducer; -import org.springframework.integration.support.AcknowledgmentCallback; -import org.springframework.integration.support.AcknowledgmentCallback.Status; -import org.springframework.integration.support.StaticMessageHeaderAccessor; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; @@ -69,9 +71,12 @@ public class RocketMQMessageChannelBinder extends implements ExtendedPropertiesBinder { - private final RocketMQExtendedBindingProperties extendedBindingProperties; + private RocketMQExtendedBindingProperties extendedBindingProperties = new RocketMQExtendedBindingProperties(); + private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties; + private final RocketMQProperties rocketMQProperties; + private final InstrumentationManager instrumentationManager; private Map topicInUse = new HashMap<>(); @@ -82,23 +87,22 @@ public class RocketMQMessageChannelBinder extends RocketMQProperties rocketMQProperties, InstrumentationManager instrumentationManager) { super(null, provisioningProvider); + this.extendedBindingProperties = extendedBindingProperties; this.rocketBinderConfigurationProperties = rocketBinderConfigurationProperties; this.rocketMQProperties = rocketMQProperties; this.instrumentationManager = instrumentationManager; - this.extendedBindingProperties = extendedBindingProperties; } @Override protected MessageHandler createProducerMessageHandler(ProducerDestination destination, ExtendedProducerProperties producerProperties, - MessageChannel errorChannel) throws Exception { + MessageChannel channel, MessageChannel errorChannel) throws Exception { if (producerProperties.getExtension().getEnabled()) { // if producerGroup is empty, using destination String extendedProducerGroup = producerProperties.getExtension().getGroup(); String producerGroup = StringUtils.isEmpty(extendedProducerGroup) - ? destination.getName() - : extendedProducerGroup; + ? destination.getName() : extendedProducerGroup; RocketMQBinderConfigurationProperties mergedProperties = RocketMQBinderUtils .mergeProperties(rocketBinderConfigurationProperties, @@ -140,7 +144,8 @@ public class RocketMQMessageChannelBinder extends producer.setVipChannelEnabled( producerProperties.getExtension().getVipChannelEnabled()); } - producer.setNamesrvAddr(mergedProperties.getNameServer()); + producer.setNamesrvAddr(RocketMQBinderUtils + .getNameServerStr(mergedProperties.getNameServer())); producer.setSendMsgTimeout( producerProperties.getExtension().getSendMessageTimeout()); producer.setRetryTimesWhenSendFailed( @@ -163,7 +168,11 @@ public class RocketMQMessageChannelBinder extends RocketMQMessageHandler messageHandler = new RocketMQMessageHandler( rocketMQTemplate, destination.getName(), producerGroup, producerProperties.getExtension().getTransactional(), - instrumentationManager, producerProperties); + instrumentationManager, producerProperties, + ((AbstractMessageChannel) channel).getChannelInterceptors().stream() + .filter(channelInterceptor -> channelInterceptor instanceof MessageConverterConfigurer.PartitioningInterceptor) + .map(channelInterceptor -> ((MessageConverterConfigurer.PartitioningInterceptor) channelInterceptor)) + .findFirst().orElse(null)); messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory()); messageHandler.setSync(producerProperties.getExtension().getSync()); messageHandler.setHeaderMapper(createHeaderMapper(producerProperties)); @@ -178,6 +187,14 @@ public class RocketMQMessageChannelBinder extends } } + @Override + protected MessageHandler createProducerMessageHandler(ProducerDestination destination, + ExtendedProducerProperties producerProperties, + MessageChannel errorChannel) throws Exception { + throw new UnsupportedOperationException( + "The abstract binder should not call this method"); + } + @Override protected MessageProducer createConsumerEndpoint(ConsumerDestination destination, String group, @@ -269,6 +286,21 @@ public class RocketMQMessageChannelBinder extends return topicInUse; } + @Override + public String getDefaultsPrefix() { + return extendedBindingProperties.getDefaultsPrefix(); + } + + @Override + public Class getExtendedPropertiesEntryClass() { + return extendedBindingProperties.getExtendedPropertiesEntryClass(); + } + + public void setExtendedBindingProperties( + RocketMQExtendedBindingProperties extendedBindingProperties) { + this.extendedBindingProperties = extendedBindingProperties; + } + private RocketMQHeaderMapper createHeaderMapper( final ExtendedConsumerProperties extendedConsumerProperties) { Set trustedPackages = extendedConsumerProperties.getExtension() diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java similarity index 94% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java index 8c550459..1c49359e 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -50,4 +50,5 @@ public class RocketMQBinderHealthIndicator extends AbstractHealthIndicator { .forEach(instrumentation1 -> builder .withException(instrumentation1.getStartException())); } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java similarity index 94% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java index 1addfec0..1d8a5416 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,7 +21,6 @@ import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQExtendedBindingProperties; import com.alibaba.cloud.stream.binder.rocketmq.provisioning.RocketMQTopicProvisioner; - import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration; import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; @@ -70,6 +69,7 @@ public class RocketMQBinderAutoConfiguration { provisioningProvider, extendedBindingProperties, rocketBinderConfigurationProperties, rocketMQProperties, instrumentationManager); + binder.setExtendedBindingProperties(extendedBindingProperties); return binder; } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java similarity index 82% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java index c435b512..ab789f51 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,6 +18,7 @@ package com.alibaba.cloud.stream.binder.rocketmq.config; import com.alibaba.cloud.stream.binder.rocketmq.actuator.RocketMQBinderHealthIndicator; +import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; @@ -31,6 +32,7 @@ import org.springframework.context.annotation.Configuration; public class RocketMQBinderHealthIndicatorAutoConfiguration { @Bean + @ConditionalOnEnabledHealthIndicator("rocketmq") public RocketMQBinderHealthIndicator rocketBinderHealthIndicator() { return new RocketMQBinderHealthIndicator(); } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java similarity index 97% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java index 318c98d8..4e17ecce 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -17,7 +17,6 @@ package com.alibaba.cloud.stream.binder.rocketmq.config; import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; - import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.rocketmq.acl.common.AclClientRPCHook; import org.apache.rocketmq.acl.common.SessionCredentials; diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java similarity index 96% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java index 05ee68df..fb167c69 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,11 +19,11 @@ package com.alibaba.cloud.stream.binder.rocketmq.consuming; import java.util.List; import java.util.Objects; +import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderUtils; import com.alibaba.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; import com.alibaba.cloud.stream.binder.rocketmq.support.RocketMQHeaderMapper; - import org.apache.rocketmq.acl.common.AclClientRPCHook; import org.apache.rocketmq.acl.common.SessionCredentials; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; @@ -84,7 +84,7 @@ public class RocketMQListenerBindingContainer */ private int delayLevelWhenNextConsume = 0; - private String nameServer; + private List nameServer; private String consumerGroup; @@ -125,8 +125,7 @@ public class RocketMQListenerBindingContainer this.rocketBinderConfigurationProperties = rocketBinderConfigurationProperties; this.rocketMQMessageChannelBinder = rocketMQMessageChannelBinder; this.consumeMode = rocketMQConsumerProperties.getExtension().getOrderly() - ? ConsumeMode.ORDERLY - : ConsumeMode.CONCURRENTLY; + ? ConsumeMode.ORDERLY : ConsumeMode.CONCURRENTLY; if (StringUtils.isEmpty(rocketMQConsumerProperties.getExtension().getSql())) { this.selectorType = SelectorType.TAG; this.selectorExpression = rocketMQConsumerProperties.getExtension().getTags(); @@ -136,8 +135,7 @@ public class RocketMQListenerBindingContainer this.selectorExpression = rocketMQConsumerProperties.getExtension().getSql(); } this.messageModel = rocketMQConsumerProperties.getExtension().getBroadcasting() - ? MessageModel.BROADCASTING - : MessageModel.CLUSTERING; + ? MessageModel.BROADCASTING : MessageModel.CLUSTERING; } @Override @@ -236,7 +234,7 @@ public class RocketMQListenerBindingContainer rocketBinderConfigurationProperties.getCustomizedTraceTopic()); } - consumer.setNamesrvAddr(nameServer); + consumer.setNamesrvAddr(RocketMQBinderUtils.getNameServerStr(nameServer)); consumer.setConsumeThreadMax(rocketMQConsumerProperties.getConcurrency()); consumer.setConsumeThreadMin(rocketMQConsumerProperties.getConcurrency()); @@ -307,11 +305,11 @@ public class RocketMQListenerBindingContainer this.delayLevelWhenNextConsume = delayLevelWhenNextConsume; } - public String getNameServer() { + public List getNameServer() { return nameServer; } - public void setNameServer(String nameServer) { + public void setNameServer(List nameServer) { this.nameServer = nameServer; } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java similarity index 96% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java index 62724827..94855592 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQMessageQueueChooser.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -58,4 +58,5 @@ public class RocketMQMessageQueueChooser { public List getMessageQueues() { return messageQueues; } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java similarity index 98% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java index bb1327d8..a3b68041 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -20,7 +20,6 @@ import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindin import com.alibaba.cloud.stream.binder.rocketmq.metrics.Instrumentation; import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; - import org.apache.rocketmq.spring.core.RocketMQListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -171,6 +170,7 @@ public class RocketMQInboundChannelAdapter extends MessageProducerSupport { RetryCallback callback, Throwable throwable) { } + } } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java similarity index 94% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java index 8ed0d417..2bf3fa62 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -25,7 +25,6 @@ import com.alibaba.cloud.stream.binder.rocketmq.metrics.Instrumentation; import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQProducerProperties; import com.alibaba.cloud.stream.binder.rocketmq.support.RocketMQHeaderMapper; - import org.apache.rocketmq.client.exception.MQClientException; import org.apache.rocketmq.client.producer.SendCallback; import org.apache.rocketmq.client.producer.SendResult; @@ -39,6 +38,7 @@ import org.slf4j.LoggerFactory; import org.springframework.cloud.stream.binder.BinderHeaders; import org.springframework.cloud.stream.binder.ExtendedProducerProperties; +import org.springframework.cloud.stream.binding.MessageConverterConfigurer; import org.springframework.context.Lifecycle; import org.springframework.integration.handler.AbstractMessageHandler; import org.springframework.integration.support.DefaultErrorMessageStrategy; @@ -81,16 +81,20 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li private ExtendedProducerProperties producerProperties; + private MessageConverterConfigurer.PartitioningInterceptor partitioningInterceptor; + public RocketMQMessageHandler(RocketMQTemplate rocketMQTemplate, String destination, String groupName, Boolean transactional, InstrumentationManager instrumentationManager, - ExtendedProducerProperties producerProperties) { + ExtendedProducerProperties producerProperties, + MessageConverterConfigurer.PartitioningInterceptor partitioningInterceptor) { this.rocketMQTemplate = rocketMQTemplate; this.destination = destination; this.groupName = groupName; this.transactional = transactional; this.instrumentationManager = instrumentationManager; this.producerProperties = producerProperties; + this.partitioningInterceptor = partitioningInterceptor; } @Override @@ -122,6 +126,8 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li destination, producerProperties.getPartitionCount(), messageQueues.size())); producerProperties.setPartitionCount(messageQueues.size()); + partitioningInterceptor + .setPartitionCount(producerProperties.getPartitionCount()); } } catch (MQClientException e) { @@ -145,8 +151,8 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li } @Override - protected void handleMessageInternal(org.springframework.messaging.Message message) - throws Exception { + protected void handleMessageInternal( + org.springframework.messaging.Message message) { try { // issue 737 fix Map jsonHeaders = headerMapper @@ -292,4 +298,5 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li public void setHeaderMapper(RocketMQHeaderMapper headerMapper) { this.headerMapper = headerMapper; } -} \ No newline at end of file + +} diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java similarity index 96% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java index 1506a689..dd95864e 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java @@ -1,5 +1,5 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,10 +19,10 @@ package com.alibaba.cloud.stream.binder.rocketmq.integration; import java.util.List; import java.util.Set; +import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderUtils; import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQMessageQueueChooser; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; - import org.apache.rocketmq.client.consumer.DefaultMQPullConsumer; import org.apache.rocketmq.client.consumer.MessageQueueListener; import org.apache.rocketmq.client.consumer.MessageSelector; @@ -40,9 +40,9 @@ import org.springframework.beans.factory.DisposableBean; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.context.Lifecycle; import org.springframework.integration.IntegrationMessageHeaderAccessor; +import org.springframework.integration.acks.AcknowledgmentCallback; +import org.springframework.integration.acks.AcknowledgmentCallbackFactory; import org.springframework.integration.endpoint.AbstractMessageSource; -import org.springframework.integration.support.AcknowledgmentCallback; -import org.springframework.integration.support.AcknowledgmentCallbackFactory; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.Message; import org.springframework.util.Assert; @@ -104,8 +104,8 @@ public class RocketMQMessageSource extends AbstractMessageSource } try { consumer = new DefaultMQPullConsumer(group); - consumer.setNamesrvAddr( - rocketMQBinderConfigurationProperties.getNameServer()); + consumer.setNamesrvAddr(RocketMQBinderUtils.getNameServerStr( + rocketMQBinderConfigurationProperties.getNameServer())); consumer.setConsumerPullTimeoutMillis( rocketMQConsumerProperties.getExtension().getPullTimeout()); consumer.setMessageModel(MessageModel.CLUSTERING); @@ -237,11 +237,6 @@ public class RocketMQMessageSource extends AbstractMessageSource } } - @Override - public void destroy() throws Exception { - - } - public static class RocketMQCallbackFactory implements AcknowledgmentCallbackFactory { @@ -330,6 +325,7 @@ public class RocketMQMessageSource extends AbstractMessageSource return "RocketMQAckCallback{" + "ackInfo=" + ackInfo + ", acknowledged=" + acknowledged + ", autoAckEnabled=" + autoAckEnabled + '}'; } + } public class RocketMQAckInfo { @@ -380,6 +376,7 @@ public class RocketMQMessageSource extends AbstractMessageSource + pullResult + ", consumer=" + consumer + ", oldOffset=" + oldOffset + '}'; } + } } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java similarity index 93% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java index f62b018e..080bebf9 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/Instrumentation.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -23,8 +23,11 @@ import java.util.concurrent.atomic.AtomicBoolean; * @author Jim */ public class Instrumentation { + private final String name; + protected final AtomicBoolean started = new AtomicBoolean(false); + protected Exception startException = null; public Instrumentation(String name) { @@ -63,4 +66,5 @@ public class Instrumentation { public Exception getStartException() { return startException; } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java similarity index 93% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java index 1152bf54..8b493958 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/metrics/InstrumentationManager.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java similarity index 84% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java index 8bfc1c93..3a9dcb40 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,8 +16,10 @@ package com.alibaba.cloud.stream.binder.rocketmq.properties; -import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; +import java.util.Arrays; +import java.util.List; +import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; import org.apache.rocketmq.common.MixAll; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -30,9 +32,10 @@ import org.springframework.boot.context.properties.ConfigurationProperties; public class RocketMQBinderConfigurationProperties { /** - * The name server for rocketMQ, formats: `host:port;host:port`. + * The name server list for rocketMQ. */ - private String nameServer = RocketMQBinderConstants.DEFAULT_NAME_SERVER; + private List nameServer = Arrays + .asList(RocketMQBinderConstants.DEFAULT_NAME_SERVER); /** * The property of "access-key". @@ -55,11 +58,11 @@ public class RocketMQBinderConfigurationProperties { */ private String customizedTraceTopic = MixAll.RMQ_SYS_TRACE_TOPIC; - public String getNameServer() { + public List getNameServer() { return nameServer; } - public void setNameServer(String nameServer) { + public void setNameServer(List nameServer) { this.nameServer = nameServer; } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java similarity index 79% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java index f22d7b83..814ae101 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBindingProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -16,16 +16,19 @@ package com.alibaba.cloud.stream.binder.rocketmq.properties; +import org.springframework.cloud.stream.binder.BinderSpecificPropertiesProvider; + /** * @author Timur Valiev * @author Jim */ -public class RocketMQBindingProperties { +public class RocketMQBindingProperties implements BinderSpecificPropertiesProvider { private RocketMQConsumerProperties consumer = new RocketMQConsumerProperties(); private RocketMQProducerProperties producer = new RocketMQProducerProperties(); + @Override public RocketMQConsumerProperties getConsumer() { return consumer; } @@ -34,6 +37,7 @@ public class RocketMQBindingProperties { this.consumer = consumer; } + @Override public RocketMQProducerProperties getProducer() { return producer; } @@ -41,4 +45,5 @@ public class RocketMQBindingProperties { public void setProducer(RocketMQProducerProperties producer) { this.producer = producer; } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java similarity index 92% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java index 854c4f47..9c059ec5 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -19,7 +19,6 @@ package com.alibaba.cloud.stream.binder.rocketmq.properties; import java.util.Set; import com.alibaba.cloud.stream.binder.rocketmq.support.JacksonRocketMQHeaderMapper; - import org.apache.rocketmq.client.consumer.MQPushConsumer; import org.apache.rocketmq.client.consumer.MessageSelector; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext; @@ -34,43 +33,43 @@ import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; public class RocketMQConsumerProperties { /** - * using '||' to split tag {@link MQPushConsumer#subscribe(String, String)} + * using '||' to split tag {@link MQPushConsumer#subscribe(String, String)}. */ private String tags; /** * {@link MQPushConsumer#subscribe(String, MessageSelector)} - * {@link MessageSelector#bySql(String)} + * {@link MessageSelector#bySql(String)}. */ private String sql; /** - * {@link MessageModel#BROADCASTING} + * {@link MessageModel#BROADCASTING}. */ private Boolean broadcasting = false; /** * if orderly is true, using {@link MessageListenerOrderly} else if orderly if false, - * using {@link MessageListenerConcurrently} + * using {@link MessageListenerConcurrently}. */ private Boolean orderly = false; /** * for concurrently listener. message consume retry strategy. see * {@link ConsumeConcurrentlyContext#delayLevelWhenNextConsume}. -1 means dlq(or - * discard, see {@link this#shouldRequeue}), others means requeue + * discard, see {@link this#shouldRequeue}), others means requeue. */ private int delayLevelWhenNextConsume = 0; /** - * for orderly listener. next retry delay time + * for orderly listener. next retry delay time. */ private long suspendCurrentQueueTimeMillis = 1000; private Boolean enabled = true; /** - * {@link JacksonRocketMQHeaderMapper#addTrustedPackages(String...)} + * {@link JacksonRocketMQHeaderMapper#addTrustedPackages(String...)}. */ private Set trustedPackages; @@ -165,4 +164,5 @@ public class RocketMQConsumerProperties { public void setTrustedPackages(Set trustedPackages) { this.trustedPackages = trustedPackages; } + } diff --git a/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java new file mode 100644 index 00000000..890d2250 --- /dev/null +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java @@ -0,0 +1,43 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.alibaba.cloud.stream.binder.rocketmq.properties; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.cloud.stream.binder.AbstractExtendedBindingProperties; +import org.springframework.cloud.stream.binder.BinderSpecificPropertiesProvider; + +/** + * @author Timur Valiev + * @author Jim + */ +@ConfigurationProperties("spring.cloud.stream.rocketmq") +public class RocketMQExtendedBindingProperties extends + AbstractExtendedBindingProperties { + + private static final String DEFAULTS_PREFIX = "spring.cloud.stream.rocketmq.default"; + + @Override + public String getDefaultsPrefix() { + return DEFAULTS_PREFIX; + } + + @Override + public Class getExtendedPropertiesEntryClass() { + return RocketMQBindingProperties.class; + } + +} diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java similarity index 97% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java index 2d4d197e..ab2a92a3 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQProducerProperties.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -163,4 +163,4 @@ public class RocketMQProducerProperties { this.retryNextServer = retryNextServer; } -} \ No newline at end of file +} diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java similarity index 96% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java index c77867e2..2b8fd198 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2018 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,7 +18,6 @@ package com.alibaba.cloud.stream.binder.rocketmq.provisioning; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQProducerProperties; - import org.apache.rocketmq.client.Validators; import org.apache.rocketmq.client.exception.MQClientException; diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java similarity index 100% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java similarity index 94% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java index a2b0c013..cb510f12 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -31,6 +31,7 @@ import org.springframework.util.Assert; * @since 2.0.1.RELEASE */ public abstract class AbstractRocketMQHeaderMapper implements RocketMQHeaderMapper { + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; private Charset charset; @@ -61,4 +62,5 @@ public abstract class AbstractRocketMQHeaderMapper implements RocketMQHeaderMapp Assert.notNull(charset, "'charset' cannot be null"); this.charset = charset; } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java similarity index 98% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java index 9be2a4d6..9d593a47 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -58,6 +58,7 @@ public class JacksonRocketMQHeaderMapper extends AbstractRocketMQHeaderMapper { public static final String JSON_TYPES = "spring_json_header_types"; private final ObjectMapper objectMapper; + private final Set trustedPackages = new LinkedHashSet<>( DEFAULT_TRUSTED_PACKAGES); diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java similarity index 89% rename from spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java index c833dd1a..46264821 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java +++ b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java @@ -1,11 +1,11 @@ /* - * Copyright (C) 2019 the original author or authors. + * Copyright 2013-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -21,12 +21,13 @@ import java.util.Map; import org.springframework.messaging.MessageHeaders; /** - * header value mapper for RocketMQ + * header value mapper for RocketMQ. * * @author caotc * @since 2.0.1.RELEASE */ public interface RocketMQHeaderMapper { + /** * Map from the given {@link MessageHeaders} to the specified target message. * @param headers the abstracted MessageHeaders. @@ -40,4 +41,5 @@ public interface RocketMQHeaderMapper { * @return the target headers. */ MessageHeaders toHeaders(Map source); + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/resources/META-INF/spring.binders b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/resources/META-INF/spring.binders similarity index 100% rename from spring-cloud-stream-binder-rocketmq/src/main/resources/META-INF/spring.binders rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/resources/META-INF/spring.binders diff --git a/spring-cloud-stream-binder-rocketmq/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/resources/META-INF/spring.factories similarity index 100% rename from spring-cloud-stream-binder-rocketmq/src/main/resources/META-INF/spring.factories rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/main/resources/META-INF/spring.factories diff --git a/spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java b/spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java similarity index 100% rename from spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java rename to spring-cloud-alibaba-starters/spring-cloud-starter-stream-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java diff --git a/spring-cloud-alicloud-acm/pom.xml b/spring-cloud-alicloud-acm/pom.xml deleted file mode 100644 index ec1087c7..00000000 --- a/spring-cloud-alicloud-acm/pom.xml +++ /dev/null @@ -1,87 +0,0 @@ - - - 4.0.0 - - - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - - spring-cloud-alicloud-acm - Spring Cloud Alibaba Cloud ACM - - - - - com.alibaba.cloud - spring-cloud-alicloud-context - - - - com.aliyun - aliyun-java-sdk-core - - - - com.aliyun - aliyun-java-sdk-edas - - - - com.alibaba.edas.acm - acm-sdk - - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-starter-actuator - provided - true - - - - - org.springframework.cloud - spring-cloud-context - - - org.springframework.cloud - spring-cloud-commons - - - org.springframework.boot - spring-boot-configuration-processor - true - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.powermock - powermock-module-junit4 - 2.0.0 - test - - - org.powermock - powermock-api-mockito2 - 2.0.0 - test - - - - - - diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java deleted file mode 100644 index a069add5..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -import com.alibaba.alicloud.acm.refresh.AcmContextRefresher; -import com.alibaba.alicloud.acm.refresh.AcmRefreshHistory; -import com.alibaba.alicloud.context.acm.AcmIntegrationProperties; - -import com.taobao.diamond.client.Diamond; - -import org.springframework.beans.BeansException; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * Created on 01/10/2017. - * - * @author juven.xuxb - */ -@Configuration -@ConditionalOnClass({ Diamond.class }) -@ConditionalOnProperty(name = "spring.cloud.alicloud.acm.enabled", matchIfMissing = true) -public class AcmAutoConfiguration implements ApplicationContextAware { - - private ApplicationContext applicationContext; - - @Bean - public AcmPropertySourceRepository acmPropertySourceRepository() { - return new AcmPropertySourceRepository(applicationContext); - } - - @Bean - public AcmRefreshHistory acmRefreshHistory() { - return new AcmRefreshHistory(); - } - - @Bean - public AcmContextRefresher acmContextRefresher( - AcmIntegrationProperties acmIntegrationProperties, - ContextRefresher contextRefresher, AcmRefreshHistory refreshHistory, - AcmPropertySourceRepository propertySourceRepository) { - return new AcmContextRefresher(contextRefresher, acmIntegrationProperties, - refreshHistory, propertySourceRepository); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - this.applicationContext = applicationContext; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmPropertySourceRepository.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmPropertySourceRepository.java deleted file mode 100644 index def27cf6..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/AcmPropertySourceRepository.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.alicloud.acm.bootstrap.AcmPropertySource; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.PropertySource; - -/** - * @author juven.xuxb, 5/17/16. - */ -public class AcmPropertySourceRepository { - - private final ApplicationContext applicationContext; - - public AcmPropertySourceRepository(ApplicationContext applicationContext) { - this.applicationContext = applicationContext; - } - - /** - * get all acm properties from application context - * @return - */ - public List getAll() { - List result = new ArrayList<>(); - ConfigurableApplicationContext ctx = (ConfigurableApplicationContext) applicationContext; - for (PropertySource p : ctx.getEnvironment().getPropertySources()) { - if (p instanceof AcmPropertySource) { - result.add((AcmPropertySource) p); - } - else if (p instanceof CompositePropertySource) { - collectAcmPropertySources((CompositePropertySource) p, result); - } - } - return result; - } - - private void collectAcmPropertySources(CompositePropertySource composite, - List result) { - for (PropertySource p : composite.getPropertySources()) { - if (p instanceof AcmPropertySource) { - result.add((AcmPropertySource) p); - } - else if (p instanceof CompositePropertySource) { - collectAcmPropertySources((CompositePropertySource) p, result); - } - } - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySource.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySource.java deleted file mode 100644 index caf7e62a..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySource.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.bootstrap; - -import java.util.Date; -import java.util.Map; - -import org.springframework.core.env.MapPropertySource; - -/** - * @author juven.xuxb - * @author xiaolongzuo - */ -public class AcmPropertySource extends MapPropertySource { - - private final String dataId; - - private final Date timestamp; - - private final boolean groupLevel; - - AcmPropertySource(String dataId, Map source, Date timestamp, - boolean groupLevel) { - super(dataId, source); - this.dataId = dataId; - this.timestamp = timestamp; - this.groupLevel = groupLevel; - } - - public String getDataId() { - return dataId; - } - - public Date getTimestamp() { - return timestamp; - } - - public boolean isGroupLevel() { - return groupLevel; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java deleted file mode 100644 index 75a1a514..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceBuilder.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.bootstrap; - -import java.io.StringReader; -import java.util.Date; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; -import java.util.Properties; - -import com.alibaba.edas.acm.ConfigService; -import com.alibaba.edas.acm.exception.ConfigException; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; -import org.springframework.core.io.ByteArrayResource; -import org.springframework.util.StringUtils; - -/** - * @author juven.xuxb - * @author xiaolongzuo - */ -class AcmPropertySourceBuilder { - - private Logger log = LoggerFactory.getLogger(AcmPropertySourceBuilder.class); - - /** - * 传入 ACM 的 DataId 和 groupID,获取到解析后的 AcmProperty 对象 - * - * @param dataId - * @param diamondGroup - * @param groupLevel - * @return - */ - AcmPropertySource build(String dataId, String diamondGroup, boolean groupLevel) { - Properties properties = loadDiamondData(dataId, diamondGroup); - if (properties == null) { - return null; - } - return new AcmPropertySource(dataId, toMap(properties), new Date(), groupLevel); - } - - private Properties loadDiamondData(String dataId, String diamondGroup) { - try { - String data = ConfigService.getConfig(dataId, diamondGroup, 3000L); - if (StringUtils.isEmpty(data)) { - return null; - } - if (dataId.endsWith(".properties")) { - Properties properties = new Properties(); - log.info(String.format("Loading acm data, dataId: '%s', group: '%s'", - dataId, diamondGroup)); - properties.load(new StringReader(data)); - return properties; - } - else if (dataId.endsWith(".yaml") || dataId.endsWith(".yml")) { - YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); - yamlFactory.setResources(new ByteArrayResource(data.getBytes())); - return yamlFactory.getObject(); - } - } - catch (Exception e) { - if (e instanceof ConfigException) { - log.error("DIAMOND-100500:" + dataId + ", " + e.toString(), e); - } - else { - log.error("DIAMOND-100500:" + dataId, e); - } - } - return null; - } - - @SuppressWarnings("unchecked") - private Map toMap(Properties properties) { - Map result = new HashMap<>(); - Enumeration keys = (Enumeration) properties.propertyNames(); - while (keys.hasMoreElements()) { - String key = keys.nextElement(); - Object value = properties.getProperty(key); - if (value != null) { - result.put(key, ((String) value).trim()); - } - else { - result.put(key, null); - } - } - return result; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceLocator.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceLocator.java deleted file mode 100644 index a0c9fed6..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/bootstrap/AcmPropertySourceLocator.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.bootstrap; - -import com.alibaba.alicloud.context.acm.AcmIntegrationProperties; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.cloud.bootstrap.config.PropertySourceLocator; -import org.springframework.core.env.CompositePropertySource; -import org.springframework.core.env.Environment; -import org.springframework.core.env.PropertySource; - -/** - * @author juven.xuxb - * @author xiaolongzuo - */ -@ConditionalOnProperty(name = "spring.cloud.alicloud.acm.enabled", matchIfMissing = true) -public class AcmPropertySourceLocator implements PropertySourceLocator { - - private static final String DIAMOND_PROPERTY_SOURCE_NAME = "diamond"; - - private AcmPropertySourceBuilder acmPropertySourceBuilder = new AcmPropertySourceBuilder(); - - @Autowired - private AcmIntegrationProperties acmIntegrationProperties; - - @Override - public PropertySource locate(Environment environment) { - - CompositePropertySource compositePropertySource = new CompositePropertySource( - DIAMOND_PROPERTY_SOURCE_NAME); - - acmIntegrationProperties.setActiveProfiles(environment.getActiveProfiles()); - - for (String dataId : acmIntegrationProperties.getGroupConfigurationDataIds()) { - loadDiamondDataIfPresent(compositePropertySource, dataId, - acmIntegrationProperties.getAcmProperties().getGroup(), true); - } - - for (String dataId : acmIntegrationProperties - .getApplicationConfigurationDataIds()) { - loadDiamondDataIfPresent(compositePropertySource, dataId, - acmIntegrationProperties.getAcmProperties().getGroup(), false); - } - - return compositePropertySource; - } - - private void loadDiamondDataIfPresent(final CompositePropertySource composite, - final String dataId, final String diamondGroup, final boolean groupLevel) { - AcmPropertySource ps = acmPropertySourceBuilder.build(dataId, diamondGroup, - groupLevel); - if (ps != null) { - composite.addFirstPropertySource(ps); - } - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpoint.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpoint.java deleted file mode 100644 index ce6ea784..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpoint.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.endpoint; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.acm.bootstrap.AcmPropertySource; -import com.alibaba.alicloud.acm.refresh.AcmRefreshHistory; -import com.alibaba.alicloud.context.acm.AcmProperties; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -/** - * Created on 01/10/2017. - * - * @author juven.xuxb - */ -@Endpoint(id = "acm") -public class AcmEndpoint { - - private final AcmProperties properties; - - private final AcmRefreshHistory refreshHistory; - - private final AcmPropertySourceRepository propertySourceRepository; - - private ThreadLocal dateFormat = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; - - public AcmEndpoint(AcmProperties properties, AcmRefreshHistory refreshHistory, - AcmPropertySourceRepository propertySourceRepository) { - this.properties = properties; - this.refreshHistory = refreshHistory; - this.propertySourceRepository = propertySourceRepository; - } - - @ReadOperation - public Map invoke() { - Map result = new HashMap<>(); - result.put("config", properties); - - Map runtime = new HashMap<>(); - List all = propertySourceRepository.getAll(); - - List> sources = new ArrayList<>(); - for (AcmPropertySource ps : all) { - Map source = new HashMap<>(); - source.put("dataId", ps.getDataId()); - source.put("lastSynced", dateFormat.get().format(ps.getTimestamp())); - sources.add(source); - } - runtime.put("sources", sources); - runtime.put("refreshHistory", refreshHistory.getRecords()); - - result.put("runtime", runtime); - return result; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointAutoConfiguration.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointAutoConfiguration.java deleted file mode 100644 index ab92119c..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointAutoConfiguration.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.endpoint; - -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.acm.refresh.AcmRefreshHistory; -import com.alibaba.alicloud.context.acm.AcmProperties; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; - -/** - * @author xiaojing - */ -@ConditionalOnWebApplication -@ConditionalOnClass(name = "org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration") -@ConditionalOnProperty(name = "spring.cloud.alicloud.acm.enabled", matchIfMissing = true) -public class AcmEndpointAutoConfiguration { - - @Autowired - private AcmProperties acmProperties; - - @Autowired - private AcmRefreshHistory acmRefreshHistory; - - @Autowired - private AcmPropertySourceRepository acmPropertySourceRepository; - - @ConditionalOnMissingBean - @ConditionalOnEnabledEndpoint - @Bean - public AcmEndpoint acmEndpoint() { - return new AcmEndpoint(acmProperties, acmRefreshHistory, - acmPropertySourceRepository); - } - - @Bean - @ConditionalOnMissingBean - public AcmHealthIndicator acmHealthIndicator(AcmProperties acmProperties, - AcmPropertySourceRepository acmPropertySourceRepository) { - return new AcmHealthIndicator(acmProperties, acmPropertySourceRepository); - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmHealthIndicator.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmHealthIndicator.java deleted file mode 100644 index 2c4095a8..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/endpoint/AcmHealthIndicator.java +++ /dev/null @@ -1,73 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.endpoint; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.acm.bootstrap.AcmPropertySource; -import com.alibaba.alicloud.context.acm.AcmProperties; -import com.alibaba.edas.acm.ConfigService; - -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.util.StringUtils; - -/** - * @author leijuan - * @author juven - */ -public class AcmHealthIndicator extends AbstractHealthIndicator { - - private final AcmProperties acmProperties; - - private final AcmPropertySourceRepository acmPropertySourceRepository; - - private final List dataIds; - - public AcmHealthIndicator(AcmProperties acmProperties, - AcmPropertySourceRepository acmPropertySourceRepository) { - this.acmProperties = acmProperties; - this.acmPropertySourceRepository = acmPropertySourceRepository; - - this.dataIds = new ArrayList<>(); - for (AcmPropertySource acmPropertySource : this.acmPropertySourceRepository - .getAll()) { - this.dataIds.add(acmPropertySource.getDataId()); - } - } - - @Override - protected void doHealthCheck(Health.Builder builder) throws Exception { - for (String dataId : dataIds) { - try { - String config = ConfigService.getConfig(dataId, acmProperties.getGroup(), - acmProperties.getTimeout()); - if (StringUtils.isEmpty(config)) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, acmProperties.getGroup()), "config is empty"); - } - } - catch (Exception e) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, acmProperties.getGroup()), e.getMessage()); - } - } - builder.up().withDetail("dataIds", dataIds); - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmContextRefresher.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmContextRefresher.java deleted file mode 100644 index 846992ce..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmContextRefresher.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.refresh; - -import java.io.UnsupportedEncodingException; -import java.math.BigInteger; -import java.security.MessageDigest; -import java.security.NoSuchAlgorithmException; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.context.acm.AcmIntegrationProperties; -import com.alibaba.edas.acm.ConfigService; -import com.alibaba.edas.acm.listener.ConfigChangeListener; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.BeansException; -import org.springframework.boot.context.event.ApplicationReadyEvent; -import org.springframework.cloud.context.refresh.ContextRefresher; -import org.springframework.cloud.endpoint.event.RefreshEvent; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.context.ApplicationListener; -import org.springframework.util.StringUtils; - -/** - * On application start up, AcmContextRefresher add diamond listeners to all application - * level dataIds, when there is a change in the data, listeners will refresh - * configurations. - * - * @author juven.xuxb, 5/13/16. - */ -public class AcmContextRefresher - implements ApplicationListener, ApplicationContextAware { - - private Logger log = LoggerFactory.getLogger(AcmContextRefresher.class); - - private final ContextRefresher contextRefresher; - - private final AcmIntegrationProperties acmIntegrationProperties; - - private final AcmRefreshHistory refreshHistory; - - private ApplicationContext applicationContext; - - private final AcmPropertySourceRepository acmPropertySourceRepository; - - private Map listenerMap = new ConcurrentHashMap<>(16); - - public AcmContextRefresher(ContextRefresher contextRefresher, - AcmIntegrationProperties acmIntegrationProperties, - AcmRefreshHistory refreshHistory, - AcmPropertySourceRepository acmPropertySourceRepository) { - this.contextRefresher = contextRefresher; - this.acmIntegrationProperties = acmIntegrationProperties; - this.refreshHistory = refreshHistory; - this.acmPropertySourceRepository = acmPropertySourceRepository; - } - - @Override - public void onApplicationEvent(ApplicationReadyEvent event) { - this.registerDiamondListenersForApplications(); - } - - private void registerDiamondListenersForApplications() { - if (acmIntegrationProperties.getAcmProperties().isRefreshEnabled()) { - for (String dataId : acmIntegrationProperties - .getApplicationConfigurationDataIds()) { - registerDiamondListener(dataId); - } - } - } - - private void registerDiamondListener(final String dataId) { - - ConfigChangeListener listener = listenerMap.computeIfAbsent(dataId, - i -> new ConfigChangeListener() { - @Override - public void receiveConfigInfo(String configInfo) { - String md5 = ""; - if (!StringUtils.isEmpty(configInfo)) { - try { - MessageDigest md = MessageDigest.getInstance("MD5"); - md5 = new BigInteger(1, - md.digest(configInfo.getBytes("UTF-8"))) - .toString(16); - } - catch (NoSuchAlgorithmException - | UnsupportedEncodingException e) { - log.warn("unable to get md5 for dataId: " + dataId, e); - } - } - refreshHistory.add(dataId, md5); - applicationContext.publishEvent(new RefreshEvent(this, md5, - "ACM Refresh, dataId=" + dataId)); - } - }); - ConfigService.addListener(dataId, - acmIntegrationProperties.getAcmProperties().getGroup(), listener); - } - - @Override - public void setApplicationContext(ApplicationContext applicationContext) - throws BeansException { - this.applicationContext = applicationContext; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmRefreshHistory.java b/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmRefreshHistory.java deleted file mode 100644 index f974dd65..00000000 --- a/spring-cloud-alicloud-acm/src/main/java/com/alibaba/alicloud/acm/refresh/AcmRefreshHistory.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.refresh; - -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.LinkedList; - -/** - * @author juven.xuxb, 5/16/16. - */ -public class AcmRefreshHistory { - - private static final int MAX_SIZE = 20; - - private LinkedList records = new LinkedList<>(); - - private ThreadLocal dateFormat = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; - - public void add(String dataId, String md5) { - records.addFirst(new Record(dateFormat.get().format(new Date()), dataId, md5)); - if (records.size() > MAX_SIZE) { - records.removeLast(); - } - } - - public LinkedList getRecords() { - return records; - } -} - -class Record { - - private final String timestamp; - - private final String dataId; - - private final String md5; - - public Record(String timestamp, String dataId, String md5) { - this.timestamp = timestamp; - this.dataId = dataId; - this.md5 = md5; - } - - public String getTimestamp() { - return timestamp; - } - - public String getDataId() { - return dataId; - } - - public String getMd5() { - return md5; - } -} diff --git a/spring-cloud-alicloud-acm/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alicloud-acm/src/main/resources/META-INF/additional-spring-configuration-metadata.json deleted file mode 100644 index 34d3e4f9..00000000 --- a/spring-cloud-alicloud-acm/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "properties": [ - { - "name": "spring.application.group", - "type": "java.lang.String", - "description": "spring application group." - }, - { - "name": "spring.cloud.alicloud.acm.enabled", - "type": "java.lang.Boolean", - "defaultValue": true, - "description": "enable acm or not." - } - ] -} \ No newline at end of file diff --git a/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 0ed3fa01..00000000 --- a/spring-cloud-alicloud-acm/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,6 +0,0 @@ -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ -com.alibaba.alicloud.acm.bootstrap.AcmPropertySourceLocator - -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.alibaba.alicloud.acm.AcmAutoConfiguration,\ -com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmConfigurationTests.java b/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmConfigurationTests.java deleted file mode 100644 index db9cc369..00000000 --- a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmConfigurationTests.java +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.alibaba.alicloud.acm.bootstrap.AcmPropertySourceLocator; -import com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.alicloud.context.acm.AcmIntegrationProperties; -import com.alibaba.alicloud.context.acm.AcmProperties; -import com.alibaba.edas.acm.ConfigService; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.MethodProxy; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - -/** - * @author xiaojing - */ - -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(SpringRunner.class) -@PrepareForTest({ ConfigService.class }) -@SpringBootTest(classes = AcmConfigurationTests.TestConfig.class, properties = { - "spring.application.name=test-name", "spring.profiles.active=dev,test", - "spring.cloud.alicloud.acm.server-list=127.0.0.1", - "spring.cloud.alicloud.acm.server-port=8848", - "spring.cloud.alicloud.acm.endpoint=test-endpoint", - "spring.cloud.alicloud.acm.namespace=test-namespace", - "spring.cloud.alicloud.acm.timeout=1000", - "spring.cloud.alicloud.acm.group=test-group", - "spring.cloud.alicloud.acm.refresh-enabled=false", - "spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE) -public class AcmConfigurationTests { - - static { - - try { - - Method method = PowerMockito.method(ConfigService.class, "getConfig", - String.class, String.class, long.class); - MethodProxy.proxy(method, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - - if ("test-name.properties".equals(args[0]) - && "test-group".equals(args[1])) { - return "user.name=hello\nuser.age=12"; - } - - if ("test-name-dev.properties".equals(args[0]) - && "test-group".equals(args[1])) { - return "user.name=dev"; - } - return ""; - } - }); - - } - catch (Exception ignore) { - ignore.printStackTrace(); - - } - } - - @Autowired - private Environment environment; - - @Autowired - private AcmPropertySourceLocator locator; - - @Autowired - private AcmIntegrationProperties integrationProperties; - - @Autowired - private AcmProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AcmPropertySourceLocator was not created", locator); - assertNotNull("AcmProperties was not created", properties); - assertNotNull("AcmIntegrationProperties was not created", integrationProperties); - - checkoutAcmServerAddr(); - checkoutAcmServerPort(); - checkoutAcmEndpoint(); - checkoutAcmNamespace(); - checkoutAcmGroup(); - checkoutAcmFileExtension(); - checkoutAcmTimeout(); - checkoutAcmProfiles(); - checkoutAcmRefreshEnabled(); - checkoutDataLoad(); - checkoutProfileDataLoad(); - } - - private void checkoutAcmServerAddr() { - assertEquals("AcmProperties server address is wrong", "127.0.0.1", - properties.getServerList()); - - } - - private void checkoutAcmServerPort() { - assertEquals("AcmProperties server port is wrong", "8848", - properties.getServerPort()); - - } - - private void checkoutAcmEndpoint() { - assertEquals("AcmProperties endpoint is wrong", "test-endpoint", - properties.getEndpoint()); - - } - - private void checkoutAcmNamespace() { - assertEquals("AcmProperties namespace is wrong", "test-namespace", - properties.getNamespace()); - - } - - private void checkoutAcmGroup() { - assertEquals("AcmProperties' group is wrong", "test-group", - properties.getGroup()); - } - - private void checkoutAcmFileExtension() { - assertEquals("AcmProperties' file extension is wrong", "properties", - properties.getFileExtension()); - } - - private void checkoutAcmTimeout() { - assertEquals("AcmProperties' timeout is wrong", 1000, properties.getTimeout()); - } - - private void checkoutAcmRefreshEnabled() { - assertEquals("AcmProperties' refresh enabled is wrong", false, - properties.isRefreshEnabled()); - } - - private void checkoutAcmProfiles() { - assertArrayEquals("AcmProperties' profiles is wrong", - new String[] { "dev", "test" }, - integrationProperties.getActiveProfiles()); - } - - private void checkoutDataLoad() { - Assert.assertEquals(environment.getProperty("user.age"), "12"); - } - - private void checkoutProfileDataLoad() { - Assert.assertEquals(environment.getProperty("user.name"), "dev"); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, - AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmFileExtensionTest.java b/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmFileExtensionTest.java deleted file mode 100644 index e3469efb..00000000 --- a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmFileExtensionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.edas.acm.ConfigService; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.MethodProxy; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - -/** - * @author xiaojing - */ - -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(SpringRunner.class) -@PrepareForTest({ ConfigService.class }) -@SpringBootTest(classes = AcmFileExtensionTest.TestConfig.class, properties = { - "spring.application.name=test-name", - "spring.cloud.alicloud.acm.server-list=127.0.0.1", - "spring.cloud.alicloud.acm.server-port=8080", - "spring.cloud.alicloud.acm.file-extension=yaml" }, webEnvironment = NONE) -public class AcmFileExtensionTest { - - static { - - try { - Method method = PowerMockito.method(ConfigService.class, "getConfig", - String.class, String.class, long.class); - MethodProxy.proxy(method, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - if ("test-name.yaml".equals(args[0]) - && "DEFAULT_GROUP".equals(args[1])) { - return "user:\n name: hello\n age: 12"; - } - return ""; - } - }); - - } - catch (Exception ignore) { - ignore.printStackTrace(); - - } - } - - @Autowired - private Environment environment; - - @Test - public void contextLoads() throws Exception { - - Assert.assertEquals(environment.getProperty("user.name"), "hello"); - Assert.assertEquals(environment.getProperty("user.age"), "12"); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, - AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmGroupConfigurationTest.java b/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmGroupConfigurationTest.java deleted file mode 100644 index b6629dfa..00000000 --- a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/AcmGroupConfigurationTest.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; - -import com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.edas.acm.ConfigService; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.MethodProxy; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - -/** - * @author xiaojing - */ - -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(SpringRunner.class) -@PrepareForTest({ ConfigService.class }) -@SpringBootTest(classes = AcmGroupConfigurationTest.TestConfig.class, properties = { - "spring.application.name=test-name", "spring.application.group=com.test.hello", - "spring.cloud.alicloud.acm.server-list=127.0.0.1", - "spring.cloud.alicloud.acm.server-port=8080", - "spring.cloud.alicloud.acm.timeout=1000", - "spring.cloud.alicloud.acm.group=test-group" }, webEnvironment = NONE) -public class AcmGroupConfigurationTest { - - static { - - try { - Method method = PowerMockito.method(ConfigService.class, "getConfig", - String.class, String.class, long.class); - MethodProxy.proxy(method, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - if ("com.test:application.properties".equals(args[0]) - && "test-group".equals(args[1])) { - return "com.test.value=com.test\ntest.priority=1"; - } - if ("com.test.hello:application.properties".equals(args[0]) - && "test-group".equals(args[1])) { - return "com.test.hello.value=com.test.hello\ntest.priority=2"; - } - return ""; - } - }); - - } - catch (Exception ignore) { - ignore.printStackTrace(); - - } - } - - @Autowired - private Environment environment; - - @Test - public void contextLoads() throws Exception { - - Assert.assertEquals(environment.getProperty("com.test.value"), "com.test"); - Assert.assertEquals(environment.getProperty("test.priority"), "2"); - Assert.assertEquals(environment.getProperty("com.test.hello.value"), - "com.test.hello"); - - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, - AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointTests.java b/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointTests.java deleted file mode 100644 index 0263c9a7..00000000 --- a/spring-cloud-alicloud-acm/src/test/java/com/alibaba/alicloud/acm/endpoint/AcmEndpointTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm.endpoint; - -import java.lang.reflect.InvocationHandler; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.alibaba.alicloud.acm.AcmAutoConfiguration; -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.acm.refresh.AcmRefreshHistory; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.alicloud.context.acm.AcmProperties; -import com.alibaba.edas.acm.ConfigService; - -import org.junit.Assert; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.api.support.MethodProxy; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.health.Health.Builder; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - -/** - * @author xiaojing - */ - -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(SpringRunner.class) -@PrepareForTest({ ConfigService.class }) -@SpringBootTest(classes = AcmEndpointTests.TestConfig.class, properties = { - "spring.application.name=test-name", - "spring.cloud.alicloud.acm.server-list=127.0.0.1", - "spring.cloud.alicloud.acm.server-port=8848", - "spring.cloud.alicloud.acm.file-extension=properties" }, webEnvironment = NONE) -public class AcmEndpointTests { - - static { - - try { - - Method method = PowerMockito.method(ConfigService.class, "getConfig", - String.class, String.class, long.class); - MethodProxy.proxy(method, new InvocationHandler() { - @Override - public Object invoke(Object proxy, Method method, Object[] args) - throws Throwable { - - if ("test-name.properties".equals(args[0]) - && "DEFAULT_GROUP".equals(args[1])) { - return "user.name=hello\nuser.age=12"; - } - return ""; - } - }); - - } - catch (Exception ignore) { - ignore.printStackTrace(); - - } - } - - @Autowired - private AcmProperties properties; - - @Autowired - private AcmRefreshHistory refreshHistory; - - @Autowired - private AcmPropertySourceRepository propertySourceRepository; - - @Autowired - private AcmPropertySourceRepository acmPropertySourceRepository; - - @Test - public void contextLoads() throws Exception { - - checkoutEndpoint(); - checkoutAcmHealthIndicator(); - - } - - private void checkoutAcmHealthIndicator() { - try { - Builder builder = new Builder(); - - AcmHealthIndicator healthIndicator = new AcmHealthIndicator(properties, - acmPropertySourceRepository); - healthIndicator.doHealthCheck(builder); - - Builder builder1 = new Builder(); - List dataIds = new ArrayList<>(); - dataIds.add("test-name.properties"); - builder1.up().withDetail("dataIds", dataIds); - - Assert.assertTrue(builder.build().equals(builder1.build())); - - } - catch (Exception ignoreE) { - - } - - } - - private void checkoutEndpoint() throws Exception { - AcmEndpoint acmEndpoint = new AcmEndpoint(properties, refreshHistory, - propertySourceRepository); - Map map = acmEndpoint.invoke(); - assertEquals(map.get("config"), properties); - assertEquals(((Map) map.get("runtime")).get("refreshHistory"), - refreshHistory.getRecords()); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AcmEndpointAutoConfiguration.class, - AcmAutoConfiguration.class, AcmContextBootstrapConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/pom.xml b/spring-cloud-alicloud-ans/pom.xml deleted file mode 100644 index e0cfc3c8..00000000 --- a/spring-cloud-alicloud-ans/pom.xml +++ /dev/null @@ -1,120 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - 4.0.0 - - spring-cloud-alicloud-ans - Spring Cloud Alibaba Cloud ANS - - - - - com.alibaba.ans - ans-sdk - - - - com.aliyun - aliyun-java-sdk-core - - - - com.aliyun - aliyun-java-sdk-edas - - - - com.alibaba.cloud - spring-cloud-alicloud-context - - - - org.springframework - spring-context - - - org.springframework.cloud - spring-cloud-commons - - - - org.slf4j - slf4j-api - - - - org.springframework.cloud - spring-cloud-starter-netflix-ribbon - - - org.springframework.boot - spring-boot-starter - - - - - - org.springframework.boot - spring-boot-actuator - true - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-starter-web - test - - - org.springframework.boot - spring-boot-starter-actuator - test - - - org.springframework.boot - spring-boot-starter-test - test - - - org.springframework.cloud - spring-cloud-test-support - test - - - org.powermock - powermock-module-junit4 - 2.0.0 - test - - - org.powermock - powermock-api-mockito2 - 2.0.0 - test - - - - - \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java deleted file mode 100644 index f3933722..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsAutoConfiguration.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import com.alibaba.alicloud.ans.registry.AnsAutoServiceRegistration; -import com.alibaba.alicloud.ans.registry.AnsRegistration; -import com.alibaba.alicloud.ans.registry.AnsServiceRegistry; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationAutoConfiguration; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; -import org.springframework.context.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnClass(name = "org.springframework.boot.web.context.WebServerInitializedEvent") -@ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) -@ConditionalOnAnsEnabled -@AutoConfigureAfter({ AutoServiceRegistrationConfiguration.class, - AutoServiceRegistrationAutoConfiguration.class }) -public class AnsAutoConfiguration { - - @Bean - public AnsServiceRegistry ansServiceRegistry() { - return new AnsServiceRegistry(); - } - - @Bean - @ConditionalOnBean(AutoServiceRegistrationProperties.class) - @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) - public AnsRegistration ansRegistration(AnsProperties ansProperties, - ApplicationContext applicationContext) { - return new AnsRegistration(ansProperties, applicationContext); - } - - @Bean - @ConditionalOnBean(AutoServiceRegistrationProperties.class) - @ConditionalOnProperty(value = "spring.cloud.service-registry.auto-registration.enabled", matchIfMissing = true) - public AnsAutoServiceRegistration ansAutoServiceRegistration( - AnsServiceRegistry registry, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - AnsRegistration registration) { - return new AnsAutoServiceRegistration(registry, autoServiceRegistrationProperties, - registration); - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClient.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClient.java deleted file mode 100644 index f0c7e09d..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClient.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; - -/** - * @author xiaolongzuo - * @author pbting - */ -public class AnsDiscoveryClient implements DiscoveryClient { - - public static final String DESCRIPTION = "Spring Cloud ANS Discovery Client"; - - @Override - public String description() { - return DESCRIPTION; - } - - @Override - public List getInstances(String serviceId) { - try { - List hosts = NamingService.getHosts(serviceId); - return hostToServiceInstanceList(hosts, serviceId); - } - catch (Exception e) { - throw new RuntimeException( - "Can not get hosts from ans server. serviceId: " + serviceId, e); - } - } - - private static ServiceInstance hostToServiceInstance(Host host, String serviceId) { - AnsServiceInstance ansServiceInstance = new AnsServiceInstance(); - ansServiceInstance.setHost(host.getIp()); - ansServiceInstance.setPort(host.getPort()); - ansServiceInstance.setServiceId(serviceId); - Map metadata = new HashMap(5); - metadata.put("appUseType", host.getAppUseType()); - metadata.put("site", host.getSite()); - metadata.put("unit", host.getUnit()); - metadata.put("doubleWeight", "" + host.getDoubleWeight()); - metadata.put("weight", "" + host.getWeight()); - ansServiceInstance.setMetadata(metadata); - - return ansServiceInstance; - } - - private static List hostToServiceInstanceList(List hosts, - String serviceId) { - List result = new ArrayList(hosts.size()); - for (Host host : hosts) { - result.add(hostToServiceInstance(host, serviceId)); - } - return result; - } - - @Override - public List getServices() { - Set publishers = NamingService.getPublishes(); - Set doms = NamingService.getDomsSubscribed(); - doms.addAll(publishers); - List result = new LinkedList<>(); - for (String service : doms) { - result.add(service); - } - return result; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java deleted file mode 100644 index 6cb09207..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsDiscoveryClientAutoConfiguration.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import org.springframework.boot.autoconfigure.AutoConfigureBefore; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAutoConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - * @author pbting - */ -@Configuration -@ConditionalOnMissingBean(DiscoveryClient.class) -@EnableConfigurationProperties -@AutoConfigureBefore(SimpleDiscoveryClientAutoConfiguration.class) -public class AnsDiscoveryClientAutoConfiguration { - - @Bean - public DiscoveryClient ansDiscoveryClient() { - return new AnsDiscoveryClient(); - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsServiceInstance.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsServiceInstance.java deleted file mode 100644 index 2c7bc37c..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/AnsServiceInstance.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import java.net.URI; -import java.util.Map; - -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.ServiceInstance; - -/** - * @author xiaolongzuo - */ -public class AnsServiceInstance implements ServiceInstance { - - private String serviceId; - - private String host; - - private int port; - - private boolean secure; - - private Map metadata; - - @Override - public String getServiceId() { - return serviceId; - } - - @Override - public String getHost() { - return host; - } - - @Override - public int getPort() { - return port; - } - - @Override - public boolean isSecure() { - return secure; - } - - @Override - public URI getUri() { - return DefaultServiceInstance.getUri(this); - } - - @Override - public Map getMetadata() { - return metadata; - } - - public void setServiceId(String serviceId) { - this.serviceId = serviceId; - } - - public void setHost(String host) { - this.host = host; - } - - public void setPort(int port) { - this.port = port; - } - - public void setSecure(boolean secure) { - this.secure = secure; - } - - public void setMetadata(Map metadata) { - this.metadata = metadata; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ConditionalOnAnsEnabled.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ConditionalOnAnsEnabled.java deleted file mode 100644 index 98926d59..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ConditionalOnAnsEnabled.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - -/** - * @author xiaolongzuo - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD }) -@ConditionalOnProperty(value = "spring.cloud.ans.enabled", matchIfMissing = true) -public @interface ConditionalOnAnsEnabled { -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpoint.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpoint.java deleted file mode 100644 index d3fab935..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpoint.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.endpoint; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.alibaba.alicloud.context.ans.AnsProperties; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -/** - * @author xiaolongzuo - * @author pbting - */ -@Endpoint(id = "ans") -public class AnsEndpoint { - - private static final Logger log = LoggerFactory.getLogger(AnsEndpoint.class); - - private AnsProperties ansProperties; - - public AnsEndpoint(AnsProperties ansProperties) { - this.ansProperties = ansProperties; - } - - /** - * @return ans endpoint - */ - @ReadOperation - public Map invoke() { - Map ansEndpoint = new HashMap<>(); - log.info("ANS endpoint invoke, ansProperties is " + ansProperties); - ansEndpoint.put("ansProperties", ansProperties); - - Map subscribes = new HashMap<>(); - Set subscribeServices = NamingService.getDomsSubscribed(); - for (String service : subscribeServices) { - try { - List hosts = NamingService.getHosts(service); - subscribes.put(service, hosts); - } - catch (Exception ignoreException) { - - } - } - ansEndpoint.put("subscribes", subscribes); - log.info("ANS endpoint invoke, subscribes is " + subscribes); - return ansEndpoint; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpointAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpointAutoConfiguration.java deleted file mode 100644 index 26e16205..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/endpoint/AnsEndpointAutoConfiguration.java +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.endpoint; - -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; - -/** - * @author xiaolongzuo - */ -@ConditionalOnWebApplication -@ConditionalOnClass(Endpoint.class) -public class AnsEndpointAutoConfiguration { - - @Bean - public AnsEndpoint ansEndpoint(AnsProperties ansProperties) { - return new AnsEndpoint(ansProperties); - } -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistration.java deleted file mode 100644 index 1c0d71a3..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistration.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.cloud.client.serviceregistry.AbstractAutoServiceRegistration; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationProperties; -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * @author xiaolongzuo - * @author pbting - */ -public class AnsAutoServiceRegistration - extends AbstractAutoServiceRegistration { - private static final Logger log = LoggerFactory - .getLogger(AnsAutoServiceRegistration.class); - - private AnsRegistration registration; - - public AnsAutoServiceRegistration(ServiceRegistry serviceRegistry, - AutoServiceRegistrationProperties autoServiceRegistrationProperties, - AnsRegistration registration) { - super(serviceRegistry, autoServiceRegistrationProperties); - this.registration = registration; - } - - @Deprecated - public void setPort(int port) { - getPort().set(port); - } - - @Override - protected AnsRegistration getRegistration() { - if (this.registration.getPort() < 0 && this.getPort().get() > 0) { - this.registration.setPort(this.getPort().get()); - } - Assert.isTrue(this.registration.getPort() > 0, "service.port has not been set"); - return this.registration; - } - - @Override - protected AnsRegistration getManagementRegistration() { - return null; - } - - @Override - protected void register() { - if (!this.registration.getAnsProperties().isRegisterEnabled()) { - log.debug("Registration disabled."); - return; - } - if (this.registration.getPort() < 0) { - this.registration.setPort(getPort().get()); - } - super.register(); - } - - @Override - protected void registerManagement() { - if (!this.registration.getAnsProperties().isRegisterEnabled()) { - return; - } - super.registerManagement(); - - } - - @Override - protected Object getConfiguration() { - return this.registration.getAnsProperties(); - } - - @Override - protected boolean isEnabled() { - return this.registration.getAnsProperties().isRegisterEnabled(); - } - - @Override - @SuppressWarnings("deprecation") - protected String getAppName() { - String appName = registration.getServiceId(); - return StringUtils.isEmpty(appName) ? super.getAppName() : appName; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsRegistration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsRegistration.java deleted file mode 100644 index f4f51193..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsRegistration.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import java.net.URI; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.springframework.cloud.client.DefaultServiceInstance; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.ManagementServerPortUtils; -import org.springframework.cloud.client.serviceregistry.Registration; -import org.springframework.context.ApplicationContext; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; - -/** - * @author xiaolongzuo - */ -public class AnsRegistration implements Registration, ServiceInstance { - - static final String MANAGEMENT_PORT = "management.port"; - static final String MANAGEMENT_CONTEXT_PATH = "management.context-path"; - static final String MANAGEMENT_ADDRESS = "management.address"; - static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path"; - - private AnsProperties ansProperties; - private ApplicationContext context; - - public AnsRegistration(AnsProperties ansProperties, ApplicationContext context) { - this.ansProperties = ansProperties; - this.context = context; - } - - @PostConstruct - public void init() { - - Map metadata = ansProperties.getClientMetadata(); - Environment env = context.getEnvironment(); - - String endpointBasePath = env.getProperty(MANAGEMENT_ENDPOINT_BASE_PATH); - if (!StringUtils.isEmpty(endpointBasePath)) { - metadata.put(MANAGEMENT_ENDPOINT_BASE_PATH, endpointBasePath); - } - - Integer managementPort = ManagementServerPortUtils.getPort(context); - if (null != managementPort) { - metadata.put(MANAGEMENT_PORT, managementPort.toString()); - String contextPath = env - .getProperty("management.server.servlet.context-path"); - String address = env.getProperty("management.server.address"); - if (!StringUtils.isEmpty(contextPath)) { - metadata.put(MANAGEMENT_CONTEXT_PATH, contextPath); - } - if (!StringUtils.isEmpty(address)) { - metadata.put(MANAGEMENT_ADDRESS, address); - } - } - } - - @Override - public String getServiceId() { - return ansProperties.getClientDomains(); - } - - @Override - public String getHost() { - return ansProperties.getClientIp(); - } - - @Override - public int getPort() { - return ansProperties.getClientPort(); - } - - public void setPort(int port) { - // if spring.cloud.ans.port is not set,use the port detected from context - if (ansProperties.getClientPort() < 0) { - this.ansProperties.setClientPort(port); - } - } - - @Override - public boolean isSecure() { - return ansProperties.isSecure(); - } - - @Override - public URI getUri() { - return DefaultServiceInstance.getUri(this); - } - - @Override - public Map getMetadata() { - return ansProperties.getClientMetadata(); - } - - public boolean isRegisterEnabled() { - return ansProperties.isRegisterEnabled(); - } - - public String getCluster() { - return ansProperties.getClientCluster(); - } - - public float getRegisterWeight(String dom) { - if (null != ansProperties.getClientWeights().get(dom) - && ansProperties.getClientWeights().get(dom) > 0) { - return ansProperties.getClientWeights().get(dom); - } - return ansProperties.getClientWeight(); - } - - public AnsProperties getAnsProperties() { - return ansProperties; - } - - @Override - public String toString() { - return "AnsRegistration{" + "ansProperties=" + ansProperties + '}'; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsServiceRegistry.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsServiceRegistry.java deleted file mode 100644 index 647ea12b..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/registry/AnsServiceRegistry.java +++ /dev/null @@ -1,115 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor; - -import org.apache.commons.lang.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.cloud.client.serviceregistry.ServiceRegistry; - -/** - * @author xiaolongzuo - */ -public class AnsServiceRegistry implements ServiceRegistry { - - private static final Logger log = LoggerFactory.getLogger(AnsServiceRegistry.class); - - private static final String SEPARATOR = ","; - - @Override - public void register(AnsRegistration registration) { - - if (!registration.isRegisterEnabled()) { - log.warn("Registration is disabled..."); - return; - } - if (StringUtils.isEmpty(registration.getServiceId())) { - log.warn("No service to register for client..."); - return; - } - - List tags = new ArrayList<>(); - for (Map.Entry entry : registration.getAnsProperties().getTags() - .entrySet()) { - NodeReactor.Tag tag = new NodeReactor.Tag(); - tag.setName(entry.getKey()); - tag.setValue(entry.getValue()); - tags.add(tag); - } - - for (String dom : registration.getServiceId().split(SEPARATOR)) { - try { - NamingService.regDom(dom, registration.getHost(), registration.getPort(), - registration.getRegisterWeight(dom), registration.getCluster(), - tags); - log.info("INFO_ANS_REGISTER, {} {}:{} register finished", dom, - registration.getAnsProperties().getClientIp(), - registration.getAnsProperties().getClientPort()); - } - catch (Exception e) { - log.error("ERR_ANS_REGISTER, {} register failed...{},", dom, - registration.toString(), e); - } - } - } - - @Override - public void deregister(AnsRegistration registration) { - - log.info("De-registering from ANSServer now..."); - - if (StringUtils.isEmpty(registration.getServiceId())) { - log.warn("No dom to de-register for client..."); - return; - } - - try { - NamingService.deRegDom(registration.getServiceId(), registration.getHost(), - registration.getPort(), registration.getCluster()); - } - catch (Exception e) { - log.error("ERR_ANS_DEREGISTER, de-register failed...{},", - registration.toString(), e); - } - - log.info("De-registration finished."); - } - - @Override - public void close() { - - } - - @Override - public void setStatus(AnsRegistration registration, String status) { - - } - - @Override - public T getStatus(AnsRegistration registration) { - return null; - } - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java deleted file mode 100644 index afde04b6..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ServerList; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - * @author pbting - */ -@Configuration -public class AnsRibbonClientConfiguration { - - @Bean - @ConditionalOnMissingBean - public ServerList ansRibbonServerList(IClientConfig config) { - AnsServerList serverList = new AnsServerList(config.getClientName()); - return serverList; - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServer.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServer.java deleted file mode 100644 index 5d36f51c..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServer.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import java.util.Collections; -import java.util.Map; - -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import com.netflix.loadbalancer.Server; - -/** - * @author xiaolongzuo - */ -public class AnsServer extends Server { - - private final MetaInfo metaInfo; - private final Host host; - private final Map metadata; - - public AnsServer(final Host host, final String dom) { - super(host.getIp(), host.getPort()); - this.host = host; - this.metadata = Collections.emptyMap(); - metaInfo = new MetaInfo() { - @Override - public String getAppName() { - return dom; - } - - @Override - public String getServerGroup() { - return getMetadata().get("group"); - } - - @Override - public String getServiceIdForDiscovery() { - return dom; - } - - @Override - public String getInstanceId() { - return AnsServer.this.host.getIp() + ":" + dom + ":" - + AnsServer.this.host.getPort(); - } - }; - } - - @Override - public MetaInfo getMetaInfo() { - return metaInfo; - } - - public Host getHealthService() { - return this.host; - } - - public Map getMetadata() { - return metadata; - } - - @Override - public String toString() { - return "AnsServer{" + "metaInfo=" + metaInfo + ", host=" + host + ", metadata=" - + metadata + '}'; - } -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServerList.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServerList.java deleted file mode 100644 index b3f749f4..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/AnsServerList.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.AbstractServerList; - -/** - * @author xiaolongzuo - */ -public class AnsServerList extends AbstractServerList { - - private String dom; - - public AnsServerList(String dom) { - this.dom = dom; - } - - @Override - public List getInitialListOfServers() { - try { - List hosts = NamingService.getHosts(getDom()); - return hostsToServerList(hosts); - } - catch (Exception e) { - throw new IllegalStateException("Can not get ans hosts, dom=" + getDom(), e); - } - } - - @Override - public List getUpdatedListOfServers() { - return getInitialListOfServers(); - } - - private AnsServer hostToServer(Host host) { - AnsServer server = new AnsServer(host, getDom()); - return server; - } - - private List hostsToServerList(List hosts) { - List result = new ArrayList(hosts.size()); - for (Host host : hosts) { - if (host.isValid()) { - result.add(hostToServer(host)); - } - } - - return result; - } - - public String getDom() { - return dom; - } - - @Override - public void initWithNiwsConfig(IClientConfig iClientConfig) { - this.dom = iClientConfig.getClientName(); - } -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/ConditionalOnRibbonAns.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/ConditionalOnRibbonAns.java deleted file mode 100644 index 7094d43b..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/ConditionalOnRibbonAns.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import java.lang.annotation.ElementType; -import java.lang.annotation.Retention; -import java.lang.annotation.RetentionPolicy; -import java.lang.annotation.Target; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; - -/** - * @author xiaolongzuo - */ -@Retention(RetentionPolicy.RUNTIME) -@Target({ ElementType.TYPE, ElementType.METHOD }) -@ConditionalOnProperty(value = "ribbon.ans.enabled", matchIfMissing = true) -public @interface ConditionalOnRibbonAns { - -} diff --git a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java b/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java deleted file mode 100644 index e73052d5..00000000 --- a/spring-cloud-alicloud-ans/src/main/java/com/alibaba/alicloud/ans/ribbon/RibbonAnsAutoConfiguration.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import com.alibaba.alicloud.ans.ConditionalOnAnsEnabled; - -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.netflix.ribbon.RibbonAutoConfiguration; -import org.springframework.cloud.netflix.ribbon.RibbonClients; -import org.springframework.cloud.netflix.ribbon.SpringClientFactory; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnAnsEnabled -@ConditionalOnBean(SpringClientFactory.class) -@ConditionalOnRibbonAns -@AutoConfigureAfter(RibbonAutoConfiguration.class) -@RibbonClients(defaultConfiguration = AnsRibbonClientConfiguration.class) -public class RibbonAnsAutoConfiguration { -} diff --git a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories deleted file mode 100644 index c297fef7..00000000 --- a/spring-cloud-alicloud-ans/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,5 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.alibaba.alicloud.ans.endpoint.AnsEndpointAutoConfiguration,\ - com.alibaba.alicloud.ans.ribbon.RibbonAnsAutoConfiguration,\ - com.alibaba.alicloud.ans.AnsAutoConfiguration,\ - com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/AnsDiscoveryClientTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/AnsDiscoveryClientTests.java deleted file mode 100644 index b18d8fa1..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/AnsDiscoveryClientTests.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import com.alibaba.alicloud.ans.test.AnsMockTest; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import org.springframework.cloud.client.ServiceInstance; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - -/** - * @author xiaojing - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest(NamingService.class) -public class AnsDiscoveryClientTests { - - private String host = "123.123.123.123"; - private int port = 8888; - private String serviceName = "test-service"; - - @Test - public void testGetServers() throws Exception { - - ArrayList hosts = new ArrayList<>(); - - HashMap map = new HashMap<>(); - map.put("test-key", "test-value"); - map.put("secure", "true"); - - hosts.add(AnsMockTest.hostInstance(serviceName, false, host, port, map)); - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getHosts(eq(serviceName))).thenReturn(hosts); - - AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(); - - List serviceInstances = discoveryClient - .getInstances(serviceName); - - assertThat(serviceInstances.size()).isEqualTo(1); - - ServiceInstance serviceInstance = serviceInstances.get(0); - - assertThat(serviceInstance.getServiceId()).isEqualTo(serviceName); - assertThat(serviceInstance.getHost()).isEqualTo(host); - assertThat(serviceInstance.getPort()).isEqualTo(port); - // assertThat(serviceInstance.isSecure()).isEqualTo(true); - // ans doesn't support metadata - assertThat(serviceInstance.getUri().toString()) - .isEqualTo(getUri(serviceInstance)); - // assertThat(serviceInstance.getMetadata().get("test-key")).isEqualTo("test-value"); - // ans doesn't support metadata - - } - - @Test - public void testGetAllService() throws Exception { - - Set subscribedServices = new HashSet<>(); - - subscribedServices.add(serviceName + "1"); - subscribedServices.add(serviceName + "2"); - subscribedServices.add(serviceName + "3"); - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getDomsSubscribed()).thenReturn(subscribedServices); - - AnsDiscoveryClient discoveryClient = new AnsDiscoveryClient(); - List services = discoveryClient.getServices(); - - assertThat(services.size()).isEqualTo(3); - assertThat(services.contains(serviceName + "1")); - assertThat(services.contains(serviceName + "2")); - assertThat(services.contains(serviceName + "3")); - - } - - private String getUri(ServiceInstance instance) { - - if (instance.isSecure()) { - return "https://" + host + ":" + port; - } - - return "http://" + host + ":" + port; - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java deleted file mode 100644 index 8ebd43e8..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationEnabledTests.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationEnabledTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080", - "spring.cloud.alicloud.ans.register-enabled=false" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationEnabledTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @Autowired - private AnsProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkEnabled(); - - } - - private void checkEnabled() { - assertFalse("Ans Auto Registration should not start", - ansAutoServiceRegistration.isEnabled()); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java deleted file mode 100644 index 4211aec8..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpNetworkInterfaceTests.java +++ /dev/null @@ -1,149 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.util.Enumeration; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationIpNetworkInterfaceTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationIpNetworkInterfaceTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @Autowired - private AnsProperties properties; - - @Autowired - private InetUtils inetUtils; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkoutAnsDiscoveryServiceIP(); - - } - - private void checkoutAnsDiscoveryServiceIP() { - assertEquals("AnsProperties service IP was wrong", - getIPFromNetworkInterface(TestConfig.netWorkInterfaceName), - registration.getHost()); - - } - - private String getIPFromNetworkInterface(String networkInterface) { - - if (!TestConfig.hasValidNetworkInterface) { - return inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); - } - - try { - NetworkInterface netInterface = NetworkInterface.getByName(networkInterface); - - Enumeration inetAddress = netInterface.getInetAddresses(); - while (inetAddress.hasMoreElements()) { - InetAddress currentAddress = inetAddress.nextElement(); - if (currentAddress instanceof Inet4Address - && !currentAddress.isLoopbackAddress()) { - return currentAddress.getHostAddress(); - } - } - return networkInterface; - } - catch (Exception e) { - return networkInterface; - } - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - - static boolean hasValidNetworkInterface = false; - static String netWorkInterfaceName; - - static { - - try { - Enumeration enumeration = NetworkInterface - .getNetworkInterfaces(); - while (enumeration.hasMoreElements() && !hasValidNetworkInterface) { - NetworkInterface networkInterface = enumeration.nextElement(); - Enumeration inetAddress = networkInterface - .getInetAddresses(); - while (inetAddress.hasMoreElements()) { - InetAddress currentAddress = inetAddress.nextElement(); - if (currentAddress instanceof Inet4Address - && !currentAddress.isLoopbackAddress()) { - hasValidNetworkInterface = true; - netWorkInterfaceName = networkInterface.getName(); - System.setProperty( - "spring.cloud.alicloud.ans.client-interface-name", - networkInterface.getName()); - break; - } - } - } - - } - catch (Exception e) { - - } - } - } - -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java deleted file mode 100644 index 7386fbb8..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationIpTests.java +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationIpTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.client-domains=myTestService2", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.client-weight=2", - "spring.cloud.alicloud.ans.server-port=8080", - "spring.cloud.alicloud.ans.client-ip=123.123.123.123" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationIpTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @Autowired - private AnsProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkoutAnsDiscoveryServiceIP(); - checkoutAnsDiscoveryServiceName(); - checkoutAnsDiscoveryWeight(); - } - - private void checkoutAnsDiscoveryServiceIP() { - assertEquals("AnsProperties service IP was wrong", "123.123.123.123", - registration.getHost()); - } - - private void checkoutAnsDiscoveryServiceName() { - assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService2", - properties.getClientDomains()); - } - - private void checkoutAnsDiscoveryWeight() { - assertEquals(2L, properties.getClientWeight(), 0); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java deleted file mode 100644 index 7f959fd8..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationManagementPortTests.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static com.alibaba.alicloud.ans.registry.AnsRegistration.MANAGEMENT_CONTEXT_PATH; -import static com.alibaba.alicloud.ans.registry.AnsRegistration.MANAGEMENT_PORT; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationManagementPortTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", "management.server.port=8888", - "management.server.servlet.context-path=/test-context-path", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationManagementPortTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @Autowired - private AnsProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkoutNacosDiscoveryManagementData(); - - } - - private void checkoutNacosDiscoveryManagementData() { - assertEquals("AnsProperties management port was wrong", "8888", - properties.getClientMetadata().get(MANAGEMENT_PORT)); - - assertEquals("AnsProperties management context path was wrong", - "/test-context-path", - properties.getClientMetadata().get(MANAGEMENT_CONTEXT_PATH)); - - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java deleted file mode 100644 index 4d3fa817..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationPortTests.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationPortTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080", - "spring.cloud.alicloud.ans.client-port=8888" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationPortTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @Autowired - private AnsProperties properties; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsDiscoveryProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkoutAnsDiscoveryServicePort(); - - } - - private void checkoutAnsDiscoveryServicePort() { - assertEquals("AnsDiscoveryProperties service Port was wrong", 8888, - registration.getPort()); - - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java deleted file mode 100644 index c22eb988..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/registry/AnsAutoServiceRegistrationTests.java +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.registry; - -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.ans.endpoint.AnsEndpoint; -import com.alibaba.alicloud.context.ans.AnsProperties; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ - -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsAutoServiceRegistrationTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080", - "spring.cloud.alicloud.ans.secure=true", - "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) -public class AnsAutoServiceRegistrationTests { - - @Autowired - private AnsRegistration registration; - - @Autowired - private AnsAutoServiceRegistration ansAutoServiceRegistration; - - @LocalServerPort - private int port; - - @Autowired - private AnsProperties properties; - - @Autowired - private InetUtils inetUtils; - - @Test - public void contextLoads() throws Exception { - - assertNotNull("AnsRegistration was not created", registration); - assertNotNull("AnsProperties was not created", properties); - assertNotNull("AnsAutoServiceRegistration was not created", - ansAutoServiceRegistration); - - checkoutAnsDiscoveryServerList(); - checkoutAnsDiscoveryServerPort(); - - checkoutAnsDiscoveryServiceName(); - checkoutAnsDiscoveryServiceIP(); - checkoutAnsDiscoveryServicePort(); - checkoutAnsDiscoverySecure(); - - checkAutoRegister(); - - checkoutEndpoint(); - - } - - private void checkAutoRegister() { - assertTrue("Ans Auto Registration was not start", - ansAutoServiceRegistration.isRunning()); - } - - private void checkoutAnsDiscoveryServerList() { - assertEquals("AnsDiscoveryProperties server list was wrong", "127.0.0.1", - properties.getServerList()); - } - - private void checkoutAnsDiscoveryServerPort() { - assertEquals("AnsDiscoveryProperties server port was wrong", "8080", - properties.getServerPort()); - } - - private void checkoutAnsDiscoveryServiceName() { - assertEquals("AnsDiscoveryProperties service name was wrong", "myTestService1", - properties.getClientDomains()); - } - - private void checkoutAnsDiscoveryServiceIP() { - assertEquals("AnsDiscoveryProperties service IP was wrong", - inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(), - registration.getHost()); - } - - private void checkoutAnsDiscoveryServicePort() { - assertEquals("AnsDiscoveryProperties service Port was wrong", port, - registration.getPort()); - } - - private void checkoutAnsDiscoverySecure() { - assertTrue("AnsDiscoveryProperties secure should be true", properties.isSecure()); - - } - - private void checkoutEndpoint() throws Exception { - AnsEndpoint ansEndpoint = new AnsEndpoint(properties); - Map map = ansEndpoint.invoke(); - assertEquals(map.get("ansProperties"), properties); - - Map subscribes = new HashMap<>(); - Set subscribeServices = NamingService.getDomsSubscribed(); - for (String service : subscribeServices) { - try { - List hosts = NamingService.getHosts(service); - subscribes.put(service, hosts); - } - catch (Exception ignoreException) { - - } - } - - assertEquals(map.get("subscribes"), subscribes); - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class }) - public static class TestConfig { - } -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java deleted file mode 100644 index b1470c00..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsRibbonClientConfigurationTests.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; - -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; -import org.junit.Test; -import org.junit.runner.RunWith; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.EnableAutoConfiguration; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationConfiguration; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.web.client.RestTemplate; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - -/** - * @author xiaojing - */ -@RunWith(SpringRunner.class) -@SpringBootTest(classes = AnsRibbonClientConfigurationTests.TestConfig.class, properties = { - "spring.application.name=myTestService1", - "spring.cloud.alicloud.ans.server-list=127.0.0.1", - "spring.cloud.alicloud.ans.server-port=8080", - "spring.cloud.alicloud.ans.endpoint=test-endpoint" }, webEnvironment = RANDOM_PORT) -public class AnsRibbonClientConfigurationTests { - - @Autowired - private AnsServerList serverList; - - @Test - public void contextLoads() throws Exception { - assertThat(serverList.getDom()).isEqualTo("myapp"); - } - - @Configuration - public static class AnsRibbonTestConfiguration { - - @Bean - IClientConfig iClientConfig() { - DefaultClientConfigImpl config = new DefaultClientConfigImpl(); - config.setClientName("myapp"); - return config; - } - - @Bean - @LoadBalanced - RestTemplate restTemplate() { - return new RestTemplate(); - } - - } - - @Configuration - @EnableAutoConfiguration - @ImportAutoConfiguration({ AutoServiceRegistrationConfiguration.class, - AnsDiscoveryClientAutoConfiguration.class, AnsAutoConfiguration.class, - AnsRibbonTestConfiguration.class, RibbonAnsAutoConfiguration.class, - AnsRibbonClientConfiguration.class }) - public static class TestConfig { - } - -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServerListTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServerListTests.java deleted file mode 100644 index 956062fa..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServerListTests.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.stream.Collectors; - -import com.alibaba.alicloud.ans.test.AnsMockTest; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import com.netflix.client.config.IClientConfig; -import org.assertj.core.api.Assertions; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.anyString; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -/** - * @author xiaojing - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ NamingService.class, AnsServer.class }) -public class AnsServerListTests { - - @Test - @SuppressWarnings("unchecked") - public void testEmptyInstancesReturnsEmptyList() throws Exception { - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getHosts(anyString())).thenReturn(Collections.EMPTY_LIST); - - IClientConfig clientConfig = mock(IClientConfig.class); - when(clientConfig.getClientName()).thenReturn("test-service"); - AnsServerList serverList = new AnsServerList("test-service"); - serverList.initWithNiwsConfig(clientConfig); - List servers = serverList.getInitialListOfServers(); - Assertions.assertThat(servers).isEmpty(); - } - - @Test - @SuppressWarnings("unchecked") - public void testGetServers() throws Exception { - - ArrayList hosts = new ArrayList<>(); - hosts.add(AnsMockTest.hostInstance("test-service", true, Collections.emptyMap())); - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getHosts(anyString())).thenReturn(hosts); - - IClientConfig clientConfig = mock(IClientConfig.class); - when(clientConfig.getClientName()).thenReturn("test-service"); - AnsServerList serverList = new AnsServerList("test-service"); - serverList.initWithNiwsConfig(clientConfig); - List servers = serverList.getInitialListOfServers(); - Assertions.assertThat(servers).hasSize(1); - - servers = serverList.getUpdatedListOfServers(); - Assertions.assertThat(servers).hasSize(1); - } - - @Test - @SuppressWarnings("unchecked") - public void testGetServersWithInstanceStatus() throws Exception { - ArrayList hosts = new ArrayList<>(); - - HashMap map1 = new HashMap<>(); - map1.put("instanceNum", "1"); - HashMap map2 = new HashMap<>(); - map2.put("instanceNum", "2"); - hosts.add(AnsMockTest.hostInstance("test-service", false, map1)); - hosts.add(AnsMockTest.hostInstance("test-service", true, map2)); - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getHosts(eq("test-service"))).thenReturn( - hosts.stream().filter(Host::isValid).collect(Collectors.toList())); - - IClientConfig clientConfig = mock(IClientConfig.class); - when(clientConfig.getClientName()).thenReturn("test-service"); - AnsServerList serverList = new AnsServerList("test-service"); - serverList.initWithNiwsConfig(clientConfig); - List servers = serverList.getInitialListOfServers(); - Assertions.assertThat(servers).hasSize(1); - - AnsServer ansServer = servers.get(0); - Host host = ansServer.getHealthService(); - - assertThat(ansServer.getMetaInfo().getInstanceId()).isEqualTo( - host.getIp() + ":" + host.getHostname() + ":" + host.getPort()); - assertThat(ansServer.getHealthService().isValid()).isEqualTo(true); - assertThat(ansServer.getHealthService().getHostname()).isEqualTo("test-service"); - - } - - @Test - public void testUpdateServers() throws Exception { - ArrayList hosts = new ArrayList<>(); - - HashMap map = new HashMap<>(); - map.put("instanceNum", "1"); - hosts.add(AnsMockTest.hostInstance("test-service", true, map)); - - PowerMockito.mockStatic(NamingService.class); - when(NamingService.getHosts(eq("test-service"))).thenReturn( - hosts.stream().filter(Host::isValid).collect(Collectors.toList())); - - IClientConfig clientConfig = mock(IClientConfig.class); - when(clientConfig.getClientName()).thenReturn("test-service"); - AnsServerList serverList = new AnsServerList("test-service"); - serverList.initWithNiwsConfig(clientConfig); - - List servers = serverList.getUpdatedListOfServers(); - Assertions.assertThat(servers).hasSize(1); - - assertThat(servers.get(0).getHealthService().isValid()).isEqualTo(true); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServiceListTests.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServiceListTests.java deleted file mode 100644 index 23476abb..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/ribbon/AnsServiceListTests.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.ribbon; - -import java.util.Arrays; -import java.util.List; - -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import com.netflix.loadbalancer.Server; -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.BDDMockito.given; -import static org.mockito.Mockito.mock; - -/** - * @author xiaolongzuo - */ -public class AnsServiceListTests { - - static final String IP_ADDR = "10.0.0.2"; - - static final int PORT = 8080; - - @Test - public void testAnsServer() { - AnsServerList serverList = getAnsServerList(); - List servers = serverList.getInitialListOfServers(); - assertNotNull("servers was null", servers); - assertEquals("servers was not size 1", 1, servers.size()); - Server des = assertAnsServer(servers); - assertEquals("hostPort was wrong", IP_ADDR + ":" + PORT, des.getHostPort()); - } - - protected Server assertAnsServer(List servers) { - Server actualServer = servers.get(0); - assertTrue("server was not a DomainExtractingServer", - actualServer instanceof AnsServer); - AnsServer des = AnsServer.class.cast(actualServer); - assertNotNull("host is null", des.getHealthService()); - assertEquals("unit was wrong", "DEFAULT", des.getHealthService().getUnit()); - return des; - } - - protected AnsServerList getAnsServerList() { - Host host = mock(Host.class); - given(host.getIp()).willReturn(IP_ADDR); - given(host.getDoubleWeight()).willReturn(1.0); - given(host.getPort()).willReturn(PORT); - given(host.getWeight()).willReturn(1); - given(host.getUnit()).willReturn("DEFAULT"); - - AnsServer server = new AnsServer(host, "testDom"); - @SuppressWarnings("unchecked") - AnsServerList originalServerList = mock(AnsServerList.class); - given(originalServerList.getInitialListOfServers()) - .willReturn(Arrays.asList(server)); - return originalServerList; - } - -} diff --git a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/test/AnsMockTest.java b/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/test/AnsMockTest.java deleted file mode 100644 index 8eaeb0e7..00000000 --- a/spring-cloud-alicloud-ans/src/test/java/com/alibaba/alicloud/ans/test/AnsMockTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.ans.test; - -import java.util.Map; - -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -/** - * @author xiaojing - */ -public class AnsMockTest { - - public static Host hostInstance(String serviceName, boolean valid, - Map metadata) { - Host host = new Host(); - host.setHostname(serviceName); - host.setValid(valid); - return host; - } - - public static Host hostInstance(String serviceName, boolean valid, String ip, - int port, Map metadata) { - Host host = new Host(); - host.setIp(ip); - host.setPort(port); - host.setValid(valid); - host.setHostname(serviceName); - return host; - } -} diff --git a/spring-cloud-alicloud-context/pom.xml b/spring-cloud-alicloud-context/pom.xml deleted file mode 100644 index a65ed868..00000000 --- a/spring-cloud-alicloud-context/pom.xml +++ /dev/null @@ -1,124 +0,0 @@ - - - - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - 4.0.0 - - spring-cloud-alicloud-context - Spring Cloud AliCloud Context - - - - - com.aliyun - aliyun-java-sdk-edas - provided - - - com.aliyun - aliyun-java-sdk-core - - - - - - com.alibaba.cloud - alicloud-context - - - - com.aliyun - aliyun-java-sdk-core - provided - - - - com.alibaba.edas - schedulerX-client - provided - - - - com.alibaba.ans - ans-sdk - provided - - - - com.aliyun.oss - aliyun-sdk-oss - provided - - - - com.alibaba.edas.acm - acm-sdk - provided - - - - org.springframework.cloud - spring-cloud-commons - - - - org.springframework.boot - spring-boot-starter-logging - provided - true - - - - org.springframework.boot - spring-boot - provided - true - - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - - org.springframework.boot - spring-boot-starter-test - test - - - - org.springframework.boot - spring-boot-starter-web - test - - - - org.powermock - powermock-module-junit4 - 2.0.0 - test - - - - org.powermock - powermock-api-mockito2 - 2.0.0 - test - - - - diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudContextAutoConfiguration.java deleted file mode 100644 index 32c93b78..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudContextAutoConfiguration.java +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.cloud.commons.util.InetUtilsProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties({ AliCloudProperties.class, InetUtilsProperties.class }) -public class AliCloudContextAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public InetUtils inetUtils(InetUtilsProperties inetUtilsProperties) { - return new InetUtils(inetUtilsProperties); - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudProperties.java deleted file mode 100644 index 1b498c96..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/AliCloudProperties.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context; - -import com.alibaba.cloud.context.AliCloudConfiguration; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author xiaolongzuo - */ -@ConfigurationProperties("spring.cloud.alicloud") -public class AliCloudProperties implements AliCloudConfiguration { - - /** - * alibaba cloud access key. - */ - private String accessKey; - - /** - * alibaba cloud secret key. - */ - private String secretKey; - - @Override - public String getAccessKey() { - return accessKey; - } - - public void setAccessKey(String accessKey) { - this.accessKey = accessKey; - } - - @Override - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/Constants.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/Constants.java deleted file mode 100644 index 8e3fe893..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/Constants.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context; - -/** - * @author Jim - */ -public interface Constants { - - interface Sentinel { - String PROPERTY_PREFIX = "spring.cloud.sentinel"; - String NACOS_DATASOURCE_AK = PROPERTY_PREFIX + ".nacos.config.access-key"; - String NACOS_DATASOURCE_SK = PROPERTY_PREFIX + ".nacos.config.secret-key"; - String NACOS_DATASOURCE_NAMESPACE = PROPERTY_PREFIX + ".nacos.config.namespace"; - String NACOS_DATASOURCE_ENDPOINT = PROPERTY_PREFIX + ".nacos.config.endpoint"; - String PROJECT_NAME = PROPERTY_PREFIX + ".nacos.config.project-name"; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmContextBootstrapConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmContextBootstrapConfiguration.java deleted file mode 100644 index 16605a70..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmContextBootstrapConfiguration.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.acm; - -import javax.annotation.PostConstruct; - -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.cloud.context.acm.AliCloudAcmInitializer; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties(AcmProperties.class) -@ConditionalOnClass(name = "com.alibaba.alicloud.acm.AcmAutoConfiguration") -@ImportAutoConfiguration(EdasContextAutoConfiguration.class) -public class AcmContextBootstrapConfiguration { - - @Autowired - private AcmProperties acmProperties; - - @Autowired - private EdasProperties edasProperties; - - @Autowired - private AliCloudProperties aliCloudProperties; - - @Autowired - private Environment environment; - - @PostConstruct - public void initAcmProperties() { - AliCloudAcmInitializer.initialize(aliCloudProperties, edasProperties, - acmProperties); - } - - @Bean - public AcmIntegrationProperties acmIntegrationProperties() { - AcmIntegrationProperties acmIntegrationProperties = new AcmIntegrationProperties(); - String applicationName = environment.getProperty("spring.application.name"); - String applicationGroup = environment.getProperty("spring.application.group"); - Assert.isTrue(!StringUtils.isEmpty(applicationName), - "'spring.application.name' must be configured in bootstrap.properties or bootstrap.yml/yaml..."); - acmIntegrationProperties.setApplicationName(applicationName); - acmIntegrationProperties.setApplicationGroup(applicationGroup); - acmIntegrationProperties.setActiveProfiles(environment.getActiveProfiles()); - acmIntegrationProperties.setAcmProperties(acmProperties); - return acmIntegrationProperties; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmIntegrationProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmIntegrationProperties.java deleted file mode 100644 index da5abac5..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmIntegrationProperties.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.acm; - -import java.util.ArrayList; -import java.util.List; - -import org.springframework.util.StringUtils; - -/** - * @author xiaolongzuo - */ -public class AcmIntegrationProperties { - - private String applicationName; - - private String applicationGroup; - - private String[] activeProfiles = new String[0]; - - private AcmProperties acmProperties; - - public String getApplicationConfigurationDataIdWithoutGroup() { - return applicationName + "." + acmProperties.getFileExtension(); - } - - public List getGroupConfigurationDataIds() { - List groupConfigurationDataIds = new ArrayList<>(); - if (StringUtils.isEmpty(applicationGroup)) { - return groupConfigurationDataIds; - } - String[] parts = applicationGroup.split("\\."); - for (int i = 1; i < parts.length; i++) { - StringBuilder subGroup = new StringBuilder(parts[0]); - for (int j = 1; j <= i; j++) { - subGroup.append(".").append(parts[j]); - } - groupConfigurationDataIds - .add(subGroup + ":application." + acmProperties.getFileExtension()); - } - return groupConfigurationDataIds; - } - - public List getApplicationConfigurationDataIds() { - List applicationConfigurationDataIds = new ArrayList<>(); - if (!StringUtils.isEmpty(applicationGroup)) { - applicationConfigurationDataIds.add(applicationGroup + ":" + applicationName - + "." + acmProperties.getFileExtension()); - for (String profile : activeProfiles) { - applicationConfigurationDataIds - .add(applicationGroup + ":" + applicationName + "-" + profile - + "." + acmProperties.getFileExtension()); - } - - } - applicationConfigurationDataIds - .add(applicationName + "." + acmProperties.getFileExtension()); - for (String profile : activeProfiles) { - applicationConfigurationDataIds.add(applicationName + "-" + profile + "." - + acmProperties.getFileExtension()); - } - return applicationConfigurationDataIds; - } - - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - public void setApplicationGroup(String applicationGroup) { - this.applicationGroup = applicationGroup; - } - - public void setActiveProfiles(String[] activeProfiles) { - this.activeProfiles = activeProfiles; - } - - public String[] getActiveProfiles() { - return activeProfiles; - } - - public void setAcmProperties(AcmProperties acmProperties) { - this.acmProperties = acmProperties; - } - - public AcmProperties getAcmProperties() { - return acmProperties; - } -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmProperties.java deleted file mode 100644 index 48a50f7d..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/acm/AcmProperties.java +++ /dev/null @@ -1,156 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.acm; - -import com.alibaba.cloud.context.AliCloudServerMode; -import com.alibaba.cloud.context.acm.AcmConfiguration; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * acm properties - * - * @author leijuan - * @author xiaolongzuo - */ -@ConfigurationProperties(prefix = "spring.cloud.alicloud.acm") -public class AcmProperties implements AcmConfiguration { - - private AliCloudServerMode serverMode = AliCloudServerMode.LOCAL; - - private String serverList = "127.0.0.1"; - - private String serverPort = "8080"; - - /** - * diamond group - */ - private String group = "DEFAULT_GROUP"; - - /** - * timeout to get configuration - */ - private int timeout = 3000; - - /** - * the AliYun endpoint for ACM - */ - private String endpoint; - - /** - * ACM namespace - */ - private String namespace; - - /** - * name of ram role granted to ECS - */ - private String ramRoleName; - - private String fileExtension = "properties"; - - private boolean refreshEnabled = true; - - public String getFileExtension() { - return fileExtension; - } - - public void setFileExtension(String fileExtension) { - this.fileExtension = fileExtension; - } - - @Override - public String getServerList() { - return serverList; - } - - public void setServerList(String serverList) { - this.serverList = serverList; - } - - @Override - public String getServerPort() { - return serverPort; - } - - public void setServerPort(String serverPort) { - this.serverPort = serverPort; - } - - @Override - public boolean isRefreshEnabled() { - return refreshEnabled; - } - - public void setRefreshEnabled(boolean refreshEnabled) { - this.refreshEnabled = refreshEnabled; - } - - @Override - public String getGroup() { - return group; - } - - public void setGroup(String group) { - this.group = group; - } - - @Override - public int getTimeout() { - return timeout; - } - - public void setTimeout(int timeout) { - this.timeout = timeout; - } - - @Override - public String getEndpoint() { - return endpoint; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - - @Override - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - @Override - public String getRamRoleName() { - return ramRoleName; - } - - public void setRamRoleName(String ramRoleName) { - this.ramRoleName = ramRoleName; - } - - @Override - public AliCloudServerMode getServerMode() { - return serverMode; - } - - public void setServerMode(AliCloudServerMode serverMode) { - this.serverMode = serverMode; - } -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListener.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListener.java deleted file mode 100644 index 415e2a47..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListener.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.ans; - -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.alicloud.context.listener.AbstractOnceApplicationListener; -import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; -import com.alibaba.cloud.context.edas.AliCloudEdasSdk; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.event.ContextRefreshedEvent; - -/** - * Init {@link com.alibaba.ans.core.NamingService} properties. - * - * @author xiaolongzuo - */ -public class AnsContextApplicationListener - extends AbstractOnceApplicationListener { - - @Override - protected String conditionalOnClass() { - return "com.alibaba.alicloud.ans.AnsAutoConfiguration"; - } - - @Override - public void handleEvent(ContextRefreshedEvent event) { - ApplicationContext applicationContext = event.getApplicationContext(); - AliCloudProperties aliCloudProperties = applicationContext - .getBean(AliCloudProperties.class); - EdasProperties edasProperties = applicationContext.getBean(EdasProperties.class); - AnsProperties ansProperties = applicationContext.getBean(AnsProperties.class); - AliCloudEdasSdk aliCloudEdasSdk = applicationContext - .getBean(AliCloudEdasSdk.class); - AliCloudAnsInitializer.initialize(aliCloudProperties, edasProperties, - ansProperties, aliCloudEdasSdk); - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextAutoConfiguration.java deleted file mode 100644 index ba06520c..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsContextAutoConfiguration.java +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.ans; - -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; - -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@ConditionalOnClass(name = "com.alibaba.alicloud.ans.AnsAutoConfiguration") -@EnableConfigurationProperties(AnsProperties.class) -@ImportAutoConfiguration(EdasContextAutoConfiguration.class) -public class AnsContextAutoConfiguration { - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsProperties.java deleted file mode 100644 index 5a541cbf..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/ans/AnsProperties.java +++ /dev/null @@ -1,343 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.ans; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Enumeration; -import java.util.HashMap; -import java.util.Map; - -import javax.annotation.PostConstruct; - -import com.alibaba.cloud.context.AliCloudServerMode; -import com.alibaba.cloud.context.ans.AnsConfiguration; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.commons.util.InetUtils; -import org.springframework.util.StringUtils; - -/** - * @author xiaolongzuo - */ -@ConfigurationProperties("spring.cloud.alicloud.ans") -public class AnsProperties implements AnsConfiguration { - - /** - * Server side mode,the default is LOCAL. - */ - private AliCloudServerMode serverMode = AliCloudServerMode.LOCAL; - - /** - * Server list. - */ - private String serverList = "127.0.0.1"; - - /** - * Server port. - */ - private String serverPort = "8080"; - - /** - * Service names,default value is ${spring.cloud.alicloud.ans.doms}. When not - * configured, use ${spring.application.name}. - */ - @Value("${spring.cloud.alicloud.ans.client-domains:${spring.application.name:}}") - private String clientDomains; - - /** - * The weight of the registration service, obtained from the configuration - * ${spring.cloud.alicloud.ans.weight}, the default is 1. - */ - private float clientWeight = 1; - - /** - * When there are multiple doms and need to correspond to different weights, configure - * them by spring.cloud.alicloud.ans.weight.dom1=weight1. - */ - private Map clientWeights = new HashMap(); - - /** - * The token of the registration service, obtained from - * ${spring.cloud.alicloud.ans.token}. - */ - private String clientToken; - - /** - * When there are multiple doms and need to correspond to different tokens, configure - * them by spring.cloud.alicloud.ans.tokens.dom1=token1. - */ - private Map clientTokens = new HashMap(); - - /** - * Configure which cluster to register with, obtained from - * ${spring.cloud.alicloud.ans.cluster}, defaults to DEFAULT. - */ - private String clientCluster = "DEFAULT"; - - /** - * Temporarily not supported, reserved fields. - */ - private Map clientMetadata = new HashMap<>(); - - /** - * Registration is turned on by default, and registration can be turned off by the - * configuration of spring.cloud.alicloud.ans.register-enabled=false. - */ - private boolean registerEnabled = true; - - /** - * The ip of the service you want to publish, obtained from - * ${spring.cloud.alicloud.ans.client-ip}. - */ - private String clientIp; - - /** - * Configure which NIC the ip of the service you want to publish is obtained from. - */ - private String clientInterfaceName; - - /** - * The port of the service you want to publish. - */ - private int clientPort = -1; - - /** - * The environment isolation configuration under the tenant, the services in the same - * environment of the same tenant can discover each other. - */ - @Value("${spring.cloud.alicloud.ans.env:${env.id:DEFAULT}}") - private String env; - - /** - * Whether to register as https, configured by ${spring.cloud.alicloud.ans.secure}, - * default is false. - */ - private boolean secure = false; - - @Autowired - private InetUtils inetUtils; - - private Map tags = new HashMap<>(); - - @PostConstruct - public void init() throws SocketException { - - // Marked as spring cloud application - tags.put("ANS_SERVICE_TYPE", "SPRING_CLOUD"); - - if (StringUtils.isEmpty(clientIp)) { - if (StringUtils.isEmpty(clientInterfaceName)) { - clientIp = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress(); - } - else { - NetworkInterface networkInterface = NetworkInterface - .getByName(clientInterfaceName); - if (null == networkInterface) { - throw new RuntimeException( - "no such network interface " + clientInterfaceName); - } - - Enumeration inetAddress = networkInterface - .getInetAddresses(); - while (inetAddress.hasMoreElements()) { - InetAddress currentAddress = inetAddress.nextElement(); - if (currentAddress instanceof Inet4Address - && !currentAddress.isLoopbackAddress()) { - clientIp = currentAddress.getHostAddress(); - break; - } - } - - if (StringUtils.isEmpty(clientIp)) { - throw new RuntimeException( - "cannot find available ip from network interface " - + clientInterfaceName); - } - - } - } - } - - @Override - public String getServerPort() { - return serverPort; - } - - public void setServerPort(String serverPort) { - this.serverPort = serverPort; - } - - @Override - public String getServerList() { - return serverList; - } - - public void setServerList(String serverList) { - this.serverList = serverList; - } - - @Override - public boolean isRegisterEnabled() { - return registerEnabled; - } - - public void setRegisterEnabled(boolean registerEnabled) { - this.registerEnabled = registerEnabled; - } - - @Override - public boolean isSecure() { - return secure; - } - - public void setSecure(boolean secure) { - this.secure = secure; - } - - @Override - public String getEnv() { - return env; - } - - public void setEnv(String env) { - this.env = env; - } - - @Override - public Map getTags() { - return tags; - } - - public void setTags(Map tags) { - this.tags = tags; - } - - @Override - public AliCloudServerMode getServerMode() { - return serverMode; - } - - public void setServerMode(AliCloudServerMode serverMode) { - this.serverMode = serverMode; - } - - @Override - public String getClientDomains() { - return clientDomains; - } - - public void setClientDomains(String clientDomains) { - this.clientDomains = clientDomains; - } - - @Override - public float getClientWeight() { - return clientWeight; - } - - public void setClientWeight(float clientWeight) { - this.clientWeight = clientWeight; - } - - @Override - public Map getClientWeights() { - return clientWeights; - } - - public void setClientWeights(Map clientWeights) { - this.clientWeights = clientWeights; - } - - @Override - public String getClientToken() { - return clientToken; - } - - public void setClientToken(String clientToken) { - this.clientToken = clientToken; - } - - @Override - public Map getClientTokens() { - return clientTokens; - } - - public void setClientTokens(Map clientTokens) { - this.clientTokens = clientTokens; - } - - @Override - public String getClientCluster() { - return clientCluster; - } - - public void setClientCluster(String clientCluster) { - this.clientCluster = clientCluster; - } - - @Override - public Map getClientMetadata() { - return clientMetadata; - } - - public void setClientMetadata(Map clientMetadata) { - this.clientMetadata = clientMetadata; - } - - @Override - public String getClientIp() { - return clientIp; - } - - public void setClientIp(String clientIp) { - this.clientIp = clientIp; - } - - @Override - public String getClientInterfaceName() { - return clientInterfaceName; - } - - public void setClientInterfaceName(String clientInterfaceName) { - this.clientInterfaceName = clientInterfaceName; - } - - @Override - public int getClientPort() { - return clientPort; - } - - public void setClientPort(int clientPort) { - this.clientPort = clientPort; - } - - @Override - public String toString() { - return "AnsProperties{" + "doms='" + clientDomains + '\'' + ", weight=" - + clientWeight + ", weights=" + clientWeights + ", token='" + clientToken - + '\'' + ", tokens=" + clientTokens + ", cluster='" + clientCluster + '\'' - + ", metadata=" + clientMetadata + ", registerEnabled=" + registerEnabled - + ", ip='" + clientIp + '\'' + ", interfaceName='" + clientInterfaceName - + '\'' + ", port=" + clientPort + ", env='" + env + '\'' + ", secure=" - + secure + ", tags=" + tags + '}'; - } -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasContextAutoConfiguration.java deleted file mode 100644 index dcf9f28b..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasContextAutoConfiguration.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.edas; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.cloud.context.edas.AliCloudEdasSdk; -import com.alibaba.cloud.context.edas.AliCloudEdasSdkFactory; - -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties(EdasProperties.class) -@ImportAutoConfiguration(AliCloudContextAutoConfiguration.class) -public class EdasContextAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - @ConditionalOnClass(name = "com.aliyuncs.edas.model.v20170801.GetSecureTokenRequest") - public AliCloudEdasSdk aliCloudEdasSdk(AliCloudProperties aliCloudProperties, - EdasProperties edasProperties) { - return AliCloudEdasSdkFactory.getDefaultAliCloudEdasSdk(aliCloudProperties, - edasProperties.getRegionId()); - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasProperties.java deleted file mode 100644 index 2c99b417..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/edas/EdasProperties.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.edas; - -import com.alibaba.cloud.context.edas.EdasConfiguration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author xiaolongzuo - */ -@ConfigurationProperties("spring.cloud.alicloud.edas") -public class EdasProperties implements EdasConfiguration { - - private static final String DEFAULT_APPLICATION_NAME = ""; - - /** - * edas application name. - */ - @Value("${spring.application.name:${spring.cloud.alicloud.edas.application.name:}}") - private String applicationName; - - /** - * edas namespace - */ - private String namespace; - - /** - * whether or not connect edas. - */ - private boolean enabled; - - @Override - public String getRegionId() { - if (namespace == null) { - return null; - } - return namespace.contains(":") ? namespace.split(":")[0] : namespace; - } - - @Override - public boolean isApplicationNameValid() { - return !DEFAULT_APPLICATION_NAME.equals(applicationName); - } - - @Override - public String getApplicationName() { - return applicationName; - } - - public void setApplicationName(String applicationName) { - this.applicationName = applicationName; - } - - @Override - public String getNamespace() { - return namespace; - } - - public void setNamespace(String namespace) { - this.namespace = namespace; - } - - @Override - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - this.enabled = enabled; - } -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/listener/AbstractOnceApplicationListener.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/listener/AbstractOnceApplicationListener.java deleted file mode 100644 index ffc09c7b..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/listener/AbstractOnceApplicationListener.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.listener; - -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.atomic.AtomicBoolean; - -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ApplicationContextEvent; - -/** - * @author xiaolongzuo - */ -public abstract class AbstractOnceApplicationListener - implements ApplicationListener { - - private static final String BOOTSTRAP_CONFIG_NAME_VALUE = "bootstrap"; - - private static final String BOOTSTRAP_CONFIG_NAME_KEY = "spring.config.name"; - - private static ConcurrentHashMap, AtomicBoolean> lockMap = new ConcurrentHashMap<>(); - - @Override - public void onApplicationEvent(T event) { - if (event instanceof ApplicationContextEvent) { - ApplicationContext applicationContext = ((ApplicationContextEvent) event) - .getApplicationContext(); - // skip bootstrap context or super parent context. - if (BOOTSTRAP_CONFIG_NAME_VALUE.equals(applicationContext.getEnvironment() - .getProperty(BOOTSTRAP_CONFIG_NAME_KEY))) { - return; - } - } - Class clazz = getClass(); - lockMap.putIfAbsent(clazz, new AtomicBoolean(false)); - AtomicBoolean handled = lockMap.get(clazz); - // only execute once. - if (!handled.compareAndSet(false, true)) { - return; - } - if (conditionalOnClass() != null) { - try { - Class.forName(conditionalOnClass()); - } - catch (ClassNotFoundException e) { - // ignored - return; - } - } - handleEvent(event); - } - - /** - * handle event. - * - * @param event - */ - protected abstract void handleEvent(T event); - - /** - * condition on class. - * - * @return - */ - protected String conditionalOnClass() { - return null; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListener.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListener.java deleted file mode 100644 index 695ee518..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListener.java +++ /dev/null @@ -1,56 +0,0 @@ -package com.alibaba.alicloud.context.nacos; - -import com.alibaba.alicloud.context.listener.AbstractOnceApplicationListener; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - -/** - * @author pbting - */ -public class NacosConfigParameterInitListener - extends AbstractOnceApplicationListener { - private static final Logger log = LoggerFactory - .getLogger(NacosConfigParameterInitListener.class); - - @Override - protected String conditionalOnClass() { - return "com.alibaba.cloud.nacos.NacosConfigAutoConfiguration"; - } - - @Override - protected void handleEvent(ApplicationEnvironmentPreparedEvent event) { - preparedNacosConfiguration(); - } - - private void preparedNacosConfiguration() { - EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory - .getEdasChangeOrderConfiguration(); - - if (log.isDebugEnabled()) { - log.debug("Initialize Nacos Config Parameter ,is managed {}.", - edasChangeOrderConfiguration.isEdasManaged()); - } - - if (!edasChangeOrderConfiguration.isEdasManaged()) { - return; - } - - System.getProperties().setProperty("spring.cloud.nacos.config.server-mode", - "EDAS"); - // initialize nacos configuration - System.getProperties().setProperty("spring.cloud.nacos.config.server-addr", ""); - System.getProperties().setProperty("spring.cloud.nacos.config.endpoint", - edasChangeOrderConfiguration.getAddressServerDomain()); - System.getProperties().setProperty("spring.cloud.nacos.config.namespace", - edasChangeOrderConfiguration.getTenantId()); - System.getProperties().setProperty("spring.cloud.nacos.config.access-key", - edasChangeOrderConfiguration.getDauthAccessKey()); - System.getProperties().setProperty("spring.cloud.nacos.config.secret-key", - edasChangeOrderConfiguration.getDauthSecretKey()); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java deleted file mode 100644 index 8a347aa8..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListener.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.context.nacos; - -import java.util.Properties; - -import com.alibaba.alicloud.context.listener.AbstractOnceApplicationListener; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - -/** - * @author pbting - * @date 2019-02-14 11:12 AM - */ -public class NacosDiscoveryParameterInitListener - extends AbstractOnceApplicationListener { - private static final Logger log = LoggerFactory - .getLogger(NacosDiscoveryParameterInitListener.class); - - @Override - protected String conditionalOnClass() { - return "com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration"; - } - - @Override - protected void handleEvent(ApplicationEnvironmentPreparedEvent event) { - EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory - .getEdasChangeOrderConfiguration(); - - if (log.isDebugEnabled()) { - log.debug("Initialize Nacos Discovery Parameter ,is managed {}.", - edasChangeOrderConfiguration.isEdasManaged()); - } - - if (!edasChangeOrderConfiguration.isEdasManaged()) { - return; - } - // initialize nacos configuration - Properties properties = System.getProperties(); - properties.setProperty("spring.cloud.nacos.discovery.server-mode", "EDAS"); - // step 1: set some properties for spring cloud alibaba nacos discovery - properties.setProperty("spring.cloud.nacos.discovery.server-addr", ""); - properties.setProperty("spring.cloud.nacos.discovery.endpoint", - edasChangeOrderConfiguration.getAddressServerDomain()); - properties.setProperty("spring.cloud.nacos.discovery.namespace", - edasChangeOrderConfiguration.getTenantId()); - properties.setProperty("spring.cloud.nacos.discovery.access-key", - edasChangeOrderConfiguration.getDauthAccessKey()); - properties.setProperty("spring.cloud.nacos.discovery.secret-key", - edasChangeOrderConfiguration.getDauthSecretKey()); - - // step 2: set these properties for nacos client - properties.setProperty("nacos.naming.web.context", "/vipserver"); - properties.setProperty("nacos.naming.exposed.port", "80"); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssContextAutoConfiguration.java deleted file mode 100644 index ea619cf3..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssContextAutoConfiguration.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.oss; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.cloud.context.AliCloudAuthorizationMode; - -import com.aliyun.oss.OSS; -import com.aliyun.oss.OSSClientBuilder; - -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - -/** - * OSS Auto {@link Configuration} - * - * @author Jim - * @author xiaolongzuo - */ -@Configuration -@ConditionalOnClass(name = "com.alibaba.alicloud.oss.OssAutoConfiguration") -@ConditionalOnProperty(name = "spring.cloud.alicloud.oss.enabled", matchIfMissing = true) -@EnableConfigurationProperties(OssProperties.class) -@ImportAutoConfiguration(AliCloudContextAutoConfiguration.class) -public class OssContextAutoConfiguration { - - @ConditionalOnMissingBean - @Bean - public OSS ossClient(AliCloudProperties aliCloudProperties, - OssProperties ossProperties) { - if (ossProperties.getAuthorizationMode() == AliCloudAuthorizationMode.AK_SK) { - Assert.isTrue(!StringUtils.isEmpty(ossProperties.getEndpoint()), - "Oss endpoint can't be empty."); - Assert.isTrue(!StringUtils.isEmpty(aliCloudProperties.getAccessKey()), - "${spring.cloud.alicloud.access-key} can't be empty."); - Assert.isTrue(!StringUtils.isEmpty(aliCloudProperties.getSecretKey()), - "${spring.cloud.alicloud.secret-key} can't be empty."); - return new OSSClientBuilder().build(ossProperties.getEndpoint(), - aliCloudProperties.getAccessKey(), aliCloudProperties.getSecretKey(), - ossProperties.getConfig()); - } - else if (ossProperties.getAuthorizationMode() == AliCloudAuthorizationMode.STS) { - Assert.isTrue(!StringUtils.isEmpty(ossProperties.getEndpoint()), - "Oss endpoint can't be empty."); - Assert.isTrue(!StringUtils.isEmpty(ossProperties.getSts().getAccessKey()), - "Access key can't be empty."); - Assert.isTrue(!StringUtils.isEmpty(ossProperties.getSts().getSecretKey()), - "Secret key can't be empty."); - Assert.isTrue(!StringUtils.isEmpty(ossProperties.getSts().getSecurityToken()), - "Security Token can't be empty."); - return new OSSClientBuilder().build(ossProperties.getEndpoint(), - ossProperties.getSts().getAccessKey(), - ossProperties.getSts().getSecretKey(), - ossProperties.getSts().getSecurityToken(), ossProperties.getConfig()); - } - else { - throw new IllegalArgumentException("Unknown auth mode."); - } - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssProperties.java deleted file mode 100644 index 33c46092..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/oss/OssProperties.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.oss; - -import com.alibaba.cloud.context.AliCloudAuthorizationMode; - -import com.aliyun.oss.ClientBuilderConfiguration; - -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * {@link ConfigurationProperties} for configuring OSS. - * - * @author Jim - * @author xiaolongzuo - */ -@ConfigurationProperties("spring.cloud.alicloud.oss") -public class OssProperties { - - /** - * Authorization Mode, please see oss - * docs. - */ - @Value("${spring.cloud.alicloud.oss.authorization-mode:AK_SK}") - private AliCloudAuthorizationMode authorizationMode; - - /** - * Endpoint, please see oss - * docs. - */ - private String endpoint; - - /** - * Sts token, please see oss - * docs. - */ - private StsToken sts; - - /** - * Client Configuration, please see oss - * docs. - */ - private ClientBuilderConfiguration config; - - public AliCloudAuthorizationMode getAuthorizationMode() { - return authorizationMode; - } - - public void setAuthorizationMode(AliCloudAuthorizationMode authorizationMode) { - this.authorizationMode = authorizationMode; - } - - public ClientBuilderConfiguration getConfig() { - return config; - } - - public void setConfig(ClientBuilderConfiguration config) { - this.config = config; - } - - public String getEndpoint() { - return endpoint; - } - - public void setEndpoint(String endpoint) { - this.endpoint = endpoint; - } - - public StsToken getSts() { - return sts; - } - - public void setSts(StsToken sts) { - this.sts = sts; - } - - public static class StsToken { - - private String accessKey; - - private String secretKey; - - private String securityToken; - - public String getAccessKey() { - return accessKey; - } - - public void setAccessKey(String accessKey) { - this.accessKey = accessKey; - } - - public String getSecretKey() { - return secretKey; - } - - public void setSecretKey(String secretKey) { - this.secretKey = secretKey; - } - - public String getSecurityToken() { - return securityToken; - } - - public void setSecurityToken(String securityToken) { - this.securityToken = securityToken; - } - - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxContextAutoConfiguration.java deleted file mode 100644 index 7b154521..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxContextAutoConfiguration.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.scx; - -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.cloud.context.edas.AliCloudEdasSdk; -import com.alibaba.cloud.context.scx.AliCloudScxInitializer; -import com.alibaba.edas.schedulerx.SchedulerXClient; - -import org.springframework.boot.autoconfigure.ImportAutoConfiguration; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@ConditionalOnClass(name = "com.alibaba.alicloud.scx.ScxAutoConfiguration") -@ConditionalOnProperty(name = "spring.cloud.alicloud.scx.enabled", matchIfMissing = true) -@EnableConfigurationProperties(ScxProperties.class) -@ImportAutoConfiguration(EdasContextAutoConfiguration.class) -public class ScxContextAutoConfiguration { - - @Bean(initMethod = "init") - @ConditionalOnMissingBean - public SchedulerXClient schedulerXClient(AliCloudProperties aliCloudProperties, - EdasProperties edasProperties, ScxProperties scxProperties, - AliCloudEdasSdk aliCloudEdasSdk) { - return AliCloudScxInitializer.initialize(aliCloudProperties, edasProperties, - scxProperties, aliCloudEdasSdk); - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxProperties.java deleted file mode 100644 index 93002ce3..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/scx/ScxProperties.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.scx; - -import com.alibaba.cloud.context.scx.ScxConfiguration; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author xiaolongzuo - */ -@ConfigurationProperties("spring.cloud.alicloud.scx") -public class ScxProperties implements ScxConfiguration { - - /** - * Group id, please see scx - * docs. - */ - private String groupId; - - /** - * Domain name, please see scx - * docs. - */ - private String domainName; - - @Override - public String getGroupId() { - return groupId; - } - - public void setGroupId(String groupId) { - this.groupId = groupId; - } - - @Override - public String getDomainName() { - return domainName; - } - - public void setDomainName(String domainName) { - this.domainName = domainName; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListener.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListener.java deleted file mode 100644 index b049e1dd..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListener.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.sentinel; - -import com.alibaba.alicloud.context.Constants; -import com.alibaba.alicloud.context.listener.AbstractOnceApplicationListener; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - -/** - * @author Jim - */ -public class SentinelAliCloudListener - extends AbstractOnceApplicationListener { - - private static final Logger logger = LoggerFactory - .getLogger(SentinelAliCloudListener.class); - - @Override - protected void handleEvent(ApplicationEnvironmentPreparedEvent event) { - EdasChangeOrderConfiguration edasChangeOrderConfiguration = EdasChangeOrderConfigurationFactory - .getEdasChangeOrderConfiguration(); - logger.info("Sentinel Nacos datasource will" - + (edasChangeOrderConfiguration.isEdasManaged() ? " be " : " not be ") - + "changed by edas change order."); - if (!edasChangeOrderConfiguration.isEdasManaged()) { - return; - } - System.getProperties().setProperty(Constants.Sentinel.NACOS_DATASOURCE_ENDPOINT, - edasChangeOrderConfiguration.getAddressServerDomain()); - System.getProperties().setProperty(Constants.Sentinel.NACOS_DATASOURCE_NAMESPACE, - edasChangeOrderConfiguration.getTenantId()); - System.getProperties().setProperty(Constants.Sentinel.NACOS_DATASOURCE_AK, - edasChangeOrderConfiguration.getDauthAccessKey()); - System.getProperties().setProperty(Constants.Sentinel.NACOS_DATASOURCE_SK, - edasChangeOrderConfiguration.getDauthSecretKey()); - System.getProperties().setProperty(Constants.Sentinel.PROJECT_NAME, - edasChangeOrderConfiguration.getProjectName()); - } - - @Override - protected String conditionalOnClass() { - return "com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource"; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsContextAutoConfiguration.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsContextAutoConfiguration.java deleted file mode 100644 index d741803e..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsContextAutoConfiguration.java +++ /dev/null @@ -1,18 +0,0 @@ -package com.alibaba.alicloud.context.sms; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Configuration; - -/** - * @author pbting - * @author xiaolongzuo - */ -@Configuration -@EnableConfigurationProperties(SmsProperties.class) -@ConditionalOnClass(name = "com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest") -@ConditionalOnProperty(value = "spring.cloud.alicloud.sms.enabled", matchIfMissing = true) -public class SmsContextAutoConfiguration { - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsProperties.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsProperties.java deleted file mode 100644 index 8ada0a80..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/sms/SmsProperties.java +++ /dev/null @@ -1,74 +0,0 @@ -package com.alibaba.alicloud.context.sms; - -import org.springframework.boot.context.properties.ConfigurationProperties; - -/** - * @author pbting - * @author xiaolongzuo - */ -@ConfigurationProperties(prefix = "spring.cloud.alicloud.sms") -public class SmsProperties { - - /** - * Product name. - */ - public static final String SMS_PRODUCT = "Dysmsapi"; - - /** - * Product domain. - */ - public static final String SMS_DOMAIN = "dysmsapi.aliyuncs.com"; - - /** - * Report queue name. - */ - private String reportQueueName; - - /** - * Up queue name. - */ - private String upQueueName; - - /** - * Connect timeout. - */ - private String connectTimeout = "10000"; - - /** - * Read timeout. - */ - private String readTimeout = "10000"; - - public String getConnectTimeout() { - return connectTimeout; - } - - public void setConnectTimeout(String connectTimeout) { - this.connectTimeout = connectTimeout; - } - - public String getReadTimeout() { - return readTimeout; - } - - public void setReadTimeout(String readTimeout) { - this.readTimeout = readTimeout; - } - - public String getReportQueueName() { - return reportQueueName; - } - - public void setReportQueueName(String reportQueueName) { - this.reportQueueName = reportQueueName; - } - - public String getUpQueueName() { - return upQueueName; - } - - public void setUpQueueName(String upQueueName) { - this.upQueueName = upQueueName; - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/statistics/StatisticsTaskStarter.java b/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/statistics/StatisticsTaskStarter.java deleted file mode 100644 index fbb81e23..00000000 --- a/spring-cloud-alicloud-context/src/main/java/com/alibaba/alicloud/context/statistics/StatisticsTaskStarter.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.statistics; - -import java.util.ArrayList; -import java.util.List; - -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.alicloud.context.acm.AcmProperties; -import com.alibaba.alicloud.context.ans.AnsContextAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.alicloud.context.oss.OssContextAutoConfiguration; -import com.alibaba.alicloud.context.oss.OssProperties; -import com.alibaba.alicloud.context.scx.ScxContextAutoConfiguration; -import com.alibaba.alicloud.context.scx.ScxProperties; -import com.alibaba.cloud.context.AliCloudServerMode; -import com.alibaba.cloud.context.edas.AliCloudEdasSdk; -import com.alibaba.cloud.context.statistics.StatisticsTask; - -import org.springframework.beans.factory.InitializingBean; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.context.annotation.Configuration; - -/** - * @author xiaolongzuo - */ -@Configuration -@AutoConfigureAfter({ ScxContextAutoConfiguration.class, - OssContextAutoConfiguration.class, AnsContextAutoConfiguration.class, - AcmContextBootstrapConfiguration.class }) -public class StatisticsTaskStarter implements InitializingBean { - - private static final String NACOS_CONFIG_SERVER_MODE_KEY = "spring.cloud.nacos.config.server-mode"; - - private static final String NACOS_DISCOVERY_SERVER_MODE_KEY = "spring.cloud.nacos.discovery.server-mode"; - - private static final String NACOS_SERVER_MODE_VALUE = "EDAS"; - - @Autowired(required = false) - private AliCloudEdasSdk aliCloudEdasSdk; - - @Autowired(required = false) - private EdasProperties edasProperties; - - @Autowired(required = false) - private ScxProperties scxProperties; - - @Autowired(required = false) - private OssProperties ossProperties; - - @Autowired(required = false) - private AnsProperties ansProperties; - - @Autowired(required = false) - private AcmProperties acmProperties; - - @Autowired(required = false) - private ScxContextAutoConfiguration scxContextAutoConfiguration; - - @Autowired(required = false) - private OssContextAutoConfiguration ossContextAutoConfiguration; - - @Autowired(required = false) - private AnsContextAutoConfiguration ansContextAutoConfiguration; - - @Autowired(required = false) - private AcmContextBootstrapConfiguration acmContextBootstrapConfiguration; - - @Override - public void afterPropertiesSet() { - StatisticsTask statisticsTask = new StatisticsTask(aliCloudEdasSdk, - edasProperties, getComponents()); - statisticsTask.start(); - } - - private List getComponents() { - List components = new ArrayList<>(); - if (scxContextAutoConfiguration != null && scxProperties != null) { - components.add("SC-SCX"); - } - if (ossContextAutoConfiguration != null && ossProperties != null) { - components.add("SC-OSS"); - } - boolean edasEnabled = edasProperties != null && edasProperties.isEnabled(); - boolean ansEnableEdas = edasEnabled || (ansProperties != null - && ansProperties.getServerMode() == AliCloudServerMode.EDAS); - if (ansContextAutoConfiguration != null && ansEnableEdas) { - components.add("SC-ANS"); - } - boolean acmEnableEdas = edasEnabled || (acmProperties != null - && acmProperties.getServerMode() == AliCloudServerMode.EDAS); - if (acmContextBootstrapConfiguration != null && acmEnableEdas) { - components.add("SC-ACM"); - } - if (NACOS_SERVER_MODE_VALUE - .equals(System.getProperty(NACOS_CONFIG_SERVER_MODE_KEY))) { - components.add("SC-NACOS-CONFIG"); - } - if (NACOS_SERVER_MODE_VALUE - .equals(System.getProperty(NACOS_DISCOVERY_SERVER_MODE_KEY))) { - components.add("SC-NACOS-DISCOVERY"); - } - return components; - } - -} diff --git a/spring-cloud-alicloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alicloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json deleted file mode 100644 index 2b81aad2..00000000 --- a/spring-cloud-alicloud-context/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "properties": [ - { - "name": "spring.cloud.alicloud.ans.client-domains", - "type": "java.lang.String", - "defaultValue": "", - "description": "Service name list, default value is ${spring.application.name}." - }, - { - "name": "spring.cloud.alicloud.ans.env", - "type": "java.lang.String", - "defaultValue": "DEFAULT", - "description": "The env for ans, default value is DEFAULT." - } - ] -} \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 8c6c9957..00000000 --- a/spring-cloud-alicloud-context/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,15 +0,0 @@ -org.springframework.cloud.bootstrap.BootstrapConfiguration=\ - com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.alibaba.alicloud.context.AliCloudContextAutoConfiguration,\ - com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration,\ - com.alibaba.alicloud.context.ans.AnsContextAutoConfiguration,\ - com.alibaba.alicloud.context.oss.OssContextAutoConfiguration,\ - com.alibaba.alicloud.context.scx.ScxContextAutoConfiguration,\ - com.alibaba.alicloud.context.statistics.StatisticsTaskStarter,\ - com.alibaba.alicloud.context.sms.SmsContextAutoConfiguration -org.springframework.context.ApplicationListener=\ - com.alibaba.alicloud.context.ans.AnsContextApplicationListener,\ - com.alibaba.alicloud.context.nacos.NacosConfigParameterInitListener,\ - com.alibaba.alicloud.context.nacos.NacosDiscoveryParameterInitListener,\ - com.alibaba.alicloud.context.sentinel.SentinelAliCloudListener \ No newline at end of file diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java deleted file mode 100644 index 9fbb2ed8..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/acm/AcmAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.acm; - -/** - * @author xiaolongzuo - */ -public class AcmAutoConfiguration { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/AliCloudPropertiesTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/AliCloudPropertiesTests.java deleted file mode 100644 index f0c00f04..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/AliCloudPropertiesTests.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context; - -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -/** - * @author xiaolongzuo - */ -public class AliCloudPropertiesTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(AliCloudContextAutoConfiguration.class)); - - @Test - public void testConfigurationValueDefaultsAreAsExpected() { - this.contextRunner.run(context -> { - AliCloudProperties aliCloudProperties = context - .getBean(AliCloudProperties.class); - assertThat(aliCloudProperties.getAccessKey()).isNull(); - assertThat(aliCloudProperties.getSecretKey()).isNull(); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded() { - this.contextRunner.withPropertyValues("spring.cloud.alicloud.access-key=123", - "spring.cloud.alicloud.secret-key=123456").run(context -> { - AliCloudProperties aliCloudProperties = context - .getBean(AliCloudProperties.class); - assertThat(aliCloudProperties.getAccessKey()).isEqualTo("123"); - assertThat(aliCloudProperties.getSecretKey()).isEqualTo("123456"); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/BaseAliCloudSpringApplication.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/BaseAliCloudSpringApplication.java deleted file mode 100644 index 7cd533bf..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/BaseAliCloudSpringApplication.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context; - -import org.junit.runner.RunWith; -import org.powermock.core.classloader.annotations.PowerMockIgnore; -import org.powermock.modules.junit4.PowerMockRunner; -import org.powermock.modules.junit4.PowerMockRunnerDelegate; - -import org.springframework.boot.autoconfigure.SpringBootApplication; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.junit4.SpringRunner; - -/** - * @author xiaolongzuo - */ -@RunWith(PowerMockRunner.class) -@PowerMockRunnerDelegate(SpringRunner.class) -@PowerMockIgnore("javax.management.*") -@SpringBootTest(classes = BaseAliCloudSpringApplication.AliCloudApplication.class, properties = { - "spring.application.name=myapp", - "spring.cloud.alicloud.edas.application.name=myapp", - "spring.cloud.alicloud.access-key=ak", "spring.cloud.alicloud.secret-key=sk", - "spring.cloud.alicloud.oss.endpoint=test", - "spring.cloud.alicloud.scx.group-id=1-2-3-4", - "spring.cloud.alicloud.edas.namespace=cn-test", - "spring.cloud.alicloud.ans.server-list=192.168.1.100", - "spring.cloud.alicloud.ans.server-port=8888", - "spring.cloud.alicloud.oss.enabled=false", - "spring.cloud.alicloud.scx.enabled=false" }) -public abstract class BaseAliCloudSpringApplication { - - @SpringBootApplication - public static class AliCloudApplication { - - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/acm/AcmPropertiesTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/acm/AcmPropertiesTests.java deleted file mode 100644 index 26eeba63..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/acm/AcmPropertiesTests.java +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.acm; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; -import com.alibaba.cloud.context.AliCloudServerMode; - -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - -/** - * @author xiaolongzuo - */ -public class AcmPropertiesTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration( - AutoConfigurations.of(AcmContextBootstrapConfiguration.class, - EdasContextAutoConfiguration.class, - AliCloudContextAutoConfiguration.class)); - - @Test - public void testConfigurationValueDefaultsAreAsExpected() { - this.contextRunner.withPropertyValues("spring.application.name=myapp") - .run(context -> { - AcmProperties config = context.getBean(AcmProperties.class); - assertThat(config.getServerMode()) - .isEqualTo(AliCloudServerMode.LOCAL); - assertThat(config.getServerList()).isEqualTo("127.0.0.1"); - assertThat(config.getServerPort()).isEqualTo("8080"); - assertThat(config.getEndpoint()).isNull(); - assertThat(config.getFileExtension()).isEqualTo("properties"); - assertThat(config.getGroup()).isEqualTo("DEFAULT_GROUP"); - assertThat(config.getNamespace()).isNull(); - assertThat(config.getRamRoleName()).isNull(); - assertThat(config.getTimeout()).isEqualTo(3000); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded() { - this.contextRunner.withPropertyValues("spring.application.name=myapp", - "spring.cloud.alicloud.access-key=ak", - "spring.cloud.alicloud.secret-key=sk", - "spring.cloud.alicloud.acm.server-mode=EDAS", - "spring.cloud.alicloud.acm.server-port=11111", - "spring.cloud.alicloud.acm.server-list=10.10.10.10", - "spring.cloud.alicloud.acm.namespace=testNamespace", - "spring.cloud.alicloud.acm.endpoint=testDomain", - "spring.cloud.alicloud.acm.group=testGroup", - "spring.cloud.alicloud.acm.file-extension=yaml").run(context -> { - AcmProperties acmProperties = context.getBean(AcmProperties.class); - assertThat(acmProperties.getServerMode()) - .isEqualTo(AliCloudServerMode.EDAS); - assertThat(acmProperties.getServerList()).isEqualTo("10.10.10.10"); - assertThat(acmProperties.getServerPort()).isEqualTo("11111"); - assertThat(acmProperties.getEndpoint()).isEqualTo("testDomain"); - assertThat(acmProperties.getGroup()).isEqualTo("testGroup"); - assertThat(acmProperties.getFileExtension()).isEqualTo("yaml"); - assertThat(acmProperties.getNamespace()).isEqualTo("testNamespace"); - }); - } - - @Test - public void testAcmIntegrationConfigurationValuesAreCorrectlyLoaded() { - this.contextRunner.withPropertyValues("spring.application.name=myapp", - "spring.application.group=com.alicloud.test", - "spring.cloud.alicloud.access-key=ak", - "spring.cloud.alicloud.secret-key=sk", - "spring.cloud.alicloud.acm.server-mode=EDAS", - "spring.cloud.alicloud.acm.server-port=11111", - "spring.cloud.alicloud.acm.server-list=10.10.10.10", - "spring.cloud.alicloud.acm.namespace=testNamespace", - "spring.cloud.alicloud.acm.endpoint=testDomain", - "spring.cloud.alicloud.acm.group=testGroup", - "spring.cloud.alicloud.acm.file-extension=yaml").run(context -> { - AcmIntegrationProperties acmIntegrationProperties = context - .getBean(AcmIntegrationProperties.class); - assertThat(acmIntegrationProperties.getGroupConfigurationDataIds() - .size()).isEqualTo(2); - assertThat(acmIntegrationProperties - .getApplicationConfigurationDataIds().size()).isEqualTo(2); - }); - } - - @Test - public void testAcmIntegrationConfigurationValuesAreCorrectlyLoaded2() { - this.contextRunner.withPropertyValues("spring.application.name=myapp", - "spring.application.group=com.alicloud.test", - "spring.profiles.active=profile1,profile2", - "spring.cloud.alicloud.access-key=ak", - "spring.cloud.alicloud.secret-key=sk", - "spring.cloud.alicloud.acm.server-mode=EDAS", - "spring.cloud.alicloud.acm.server-port=11111", - "spring.cloud.alicloud.acm.server-list=10.10.10.10", - "spring.cloud.alicloud.acm.namespace=testNamespace", - "spring.cloud.alicloud.acm.endpoint=testDomain", - "spring.cloud.alicloud.acm.group=testGroup", - "spring.cloud.alicloud.acm.file-extension=yaml").run(context -> { - AcmIntegrationProperties acmIntegrationProperties = context - .getBean(AcmIntegrationProperties.class); - assertThat(acmIntegrationProperties.getGroupConfigurationDataIds() - .size()).isEqualTo(2); - assertThat(acmIntegrationProperties - .getApplicationConfigurationDataIds().size()).isEqualTo(6); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListenerTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListenerTests.java deleted file mode 100644 index 7f04a791..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsContextApplicationListenerTests.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.ans; - -import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; - -import org.junit.Test; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - -/** - * @author xiaolongzuo - */ -public class AnsContextApplicationListenerTests extends BaseAliCloudSpringApplication { - - @Test - public void testAnsContextApplicationListenerDefault() { - assertThat(System - .getProperty("com.alibaba.ans.shaded.com.taobao.vipserver.serverlist")) - .isEqualTo("192.168.1.100"); - assertThat(System.getProperty("vipserver.server.port")).isEqualTo("8888"); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsPropertiesTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsPropertiesTests.java deleted file mode 100644 index b5034598..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/ans/AnsPropertiesTests.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.ans; - -import java.net.Inet4Address; -import java.net.InetAddress; -import java.net.NetworkInterface; -import java.net.SocketException; -import java.util.Vector; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; -import com.alibaba.cloud.context.AliCloudServerMode; - -import org.junit.Test; -import org.junit.runner.RunWith; -import org.powermock.api.mockito.PowerMockito; -import org.powermock.core.classloader.annotations.PrepareForTest; -import org.powermock.modules.junit4.PowerMockRunner; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - -/** - * @author xiaolongzuo - */ -@RunWith(PowerMockRunner.class) -@PrepareForTest({ NetworkInterface.class, AnsProperties.class }) -public class AnsPropertiesTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(AnsContextAutoConfiguration.class, - EdasContextAutoConfiguration.class, - AliCloudContextAutoConfiguration.class)); - - @Test - public void testConfigurationValueDefaultsAreAsExpected() { - this.contextRunner.withPropertyValues().run(context -> { - AnsProperties ansProperties = context.getBean(AnsProperties.class); - assertThat(ansProperties.getServerMode()).isEqualTo(AliCloudServerMode.LOCAL); - assertThat(ansProperties.getServerList()).isEqualTo("127.0.0.1"); - assertThat(ansProperties.getServerPort()).isEqualTo("8080"); - assertThat(ansProperties.getClientDomains()).isEqualTo(""); - assertThat(ansProperties.getClientWeight()).isEqualTo(1.0F); - assertThat(ansProperties.getClientWeights().size()).isEqualTo(0); - assertThat(ansProperties.getClientTokens().size()).isEqualTo(0); - assertThat(ansProperties.getClientMetadata().size()).isEqualTo(0); - assertThat(ansProperties.getClientToken()).isNull(); - assertThat(ansProperties.getClientCluster()).isEqualTo("DEFAULT"); - assertThat(ansProperties.isRegisterEnabled()).isTrue(); - assertThat(ansProperties.getClientInterfaceName()).isNull(); - assertThat(ansProperties.getClientPort()).isEqualTo(-1); - assertThat(ansProperties.getEnv()).isEqualTo("DEFAULT"); - assertThat(ansProperties.isSecure()).isFalse(); - assertThat(ansProperties.getTags().size()).isEqualTo(1); - assertThat(ansProperties.getTags().keySet().iterator().next()) - .isEqualTo("ANS_SERVICE_TYPE"); - assertThat(ansProperties.getTags().get("ANS_SERVICE_TYPE")) - .isEqualTo("SPRING_CLOUD"); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded1() { - this.contextRunner - .withPropertyValues("spring.cloud.alicloud.ans.server-mode=EDAS", - "spring.cloud.alicloud.ans.server-port=11111", - "spring.cloud.alicloud.ans.server-list=10.10.10.10", - "spring.cloud.alicloud.ans.client-domains=testDomain", - "spring.cloud.alicloud.ans.client-weight=0.9", - "spring.cloud.alicloud.ans.client-weights.testDomain=0.9") - .run(context -> { - AnsProperties ansProperties = context.getBean(AnsProperties.class); - assertThat(ansProperties.getServerMode()) - .isEqualTo(AliCloudServerMode.EDAS); - assertThat(ansProperties.getServerList()).isEqualTo("10.10.10.10"); - assertThat(ansProperties.getServerPort()).isEqualTo("11111"); - assertThat(ansProperties.getClientDomains()).isEqualTo("testDomain"); - assertThat(ansProperties.getClientWeight()).isEqualTo(0.9F); - assertThat(ansProperties.getClientWeights().size()).isEqualTo(1); - assertThat(ansProperties.getClientTokens().size()).isEqualTo(0); - assertThat(ansProperties.getClientMetadata().size()).isEqualTo(0); - assertThat(ansProperties.getClientToken()).isNull(); - assertThat(ansProperties.getClientCluster()).isEqualTo("DEFAULT"); - assertThat(ansProperties.isRegisterEnabled()).isTrue(); - assertThat(ansProperties.getClientInterfaceName()).isNull(); - assertThat(ansProperties.getClientPort()).isEqualTo(-1); - assertThat(ansProperties.getEnv()).isEqualTo("DEFAULT"); - assertThat(ansProperties.isSecure()).isFalse(); - assertThat(ansProperties.getTags().size()).isEqualTo(1); - assertThat(ansProperties.getTags().keySet().iterator().next()) - .isEqualTo("ANS_SERVICE_TYPE"); - assertThat(ansProperties.getTags().get("ANS_SERVICE_TYPE")) - .isEqualTo("SPRING_CLOUD"); - }); - } - - @Test(expected = RuntimeException.class) - public void testConfigurationValuesAreCorrectlyLoaded2() { - this.contextRunner.withPropertyValues( - "spring.cloud.alicloud.ans.client-interface-name=noneinterfacename") - .run(context -> { - AnsProperties ansProperties = context.getBean(AnsProperties.class); - assertThat(ansProperties.getClientInterfaceName()) - .isEqualTo("noneinterfacename"); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded3() throws SocketException { - NetworkInterface networkInterface = PowerMockito.mock(NetworkInterface.class); - Vector inetAddressList = new Vector<>(); - Inet4Address inetAddress = PowerMockito.mock(Inet4Address.class); - PowerMockito.when(inetAddress.getHostAddress()).thenReturn("192.168.1.100"); - inetAddressList.add(inetAddress); - PowerMockito.when(networkInterface.getInetAddresses()) - .thenReturn(inetAddressList.elements()); - PowerMockito.mockStatic(NetworkInterface.class); - PowerMockito.when(NetworkInterface.getByName("eth0")) - .thenReturn(networkInterface); - this.contextRunner - .withPropertyValues( - "spring.cloud.alicloud.ans.client-interface-name=eth0") - .run(context -> { - AnsProperties ansProperties = context.getBean(AnsProperties.class); - assertThat(ansProperties.getClientInterfaceName()).isEqualTo("eth0"); - assertThat(ansProperties.getClientIp()).isEqualTo("192.168.1.100"); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/edas/EdasPropertiesTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/edas/EdasPropertiesTests.java deleted file mode 100644 index 3e9b28e8..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/edas/EdasPropertiesTests.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.edas; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; - -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -/** - * @author xiaolongzuo - */ -public class EdasPropertiesTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(EdasContextAutoConfiguration.class, - AliCloudContextAutoConfiguration.class)); - - @Test - public void testConfigurationValueDefaultsAreAsExpected() { - this.contextRunner.withPropertyValues().run(context -> { - EdasProperties edasProperties = context.getBean(EdasProperties.class); - assertThat(edasProperties.getNamespace()).isNull(); - assertThat(edasProperties.isApplicationNameValid()).isFalse(); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded1() { - this.contextRunner - .withPropertyValues("spring.cloud.alicloud.edas.namespace=testns", - "spring.application.name=myapps") - .run(context -> { - EdasProperties edasProperties = context.getBean(EdasProperties.class); - assertThat(edasProperties.getNamespace()).isEqualTo("testns"); - assertThat(edasProperties.getApplicationName()).isEqualTo("myapps"); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded2() { - this.contextRunner - .withPropertyValues("spring.cloud.alicloud.edas.namespace=testns", - "spring.cloud.alicloud.edas.application.name=myapps") - .run(context -> { - EdasProperties edasProperties = context.getBean(EdasProperties.class); - assertThat(edasProperties.getNamespace()).isEqualTo("testns"); - assertThat(edasProperties.getApplicationName()).isEqualTo("myapps"); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java deleted file mode 100644 index 61532226..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosConfigParameterInitListenerTests.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.nacos; - -import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; -import com.alibaba.alicloud.utils.ChangeOrderUtils; -import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.powermock.core.classloader.annotations.PrepareForTest; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -/** - * @author xiaolongzuo - */ -@PrepareForTest({ EdasChangeOrderConfigurationFactory.class, - NacosConfigParameterInitListener.class, AliCloudAnsInitializer.class }) -public class NacosConfigParameterInitListenerTests extends BaseAliCloudSpringApplication { - - @BeforeClass - public static void setUp() { - ChangeOrderUtils.mockChangeOrder(); - } - - @Test - public void testNacosParameterInitListener() { - assertThat(System.getProperty("spring.cloud.nacos.config.server-mode")) - .isEqualTo("EDAS"); - assertThat(System.getProperty("spring.cloud.nacos.config.server-addr")) - .isEqualTo(""); - assertThat(System.getProperty("spring.cloud.nacos.config.endpoint")) - .isEqualTo("testDomain"); - assertThat(System.getProperty("spring.cloud.nacos.config.namespace")) - .isEqualTo("testTenantId"); - assertThat(System.getProperty("spring.cloud.nacos.config.access-key")) - .isEqualTo("testAK"); - assertThat(System.getProperty("spring.cloud.nacos.config.secret-key")) - .isEqualTo("testSK"); - - } -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java deleted file mode 100644 index 5ba92819..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/nacos/NacosDiscoveryParameterInitListenerTests.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.nacos; - -import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; -import com.alibaba.alicloud.utils.ChangeOrderUtils; -import com.alibaba.cloud.context.ans.AliCloudAnsInitializer; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.powermock.core.classloader.annotations.PrepareForTest; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -/** - * @author xiaolongzuo - */ -@PrepareForTest({ EdasChangeOrderConfigurationFactory.class, - NacosDiscoveryParameterInitListener.class, AliCloudAnsInitializer.class }) -public class NacosDiscoveryParameterInitListenerTests - extends BaseAliCloudSpringApplication { - - @BeforeClass - public static void setUp() { - ChangeOrderUtils.mockChangeOrder(); - } - - @Test - public void testNacosParameterInitListener() { - assertThat(System.getProperty("spring.cloud.nacos.discovery.server-mode")) - .isEqualTo("EDAS"); - assertThat(System.getProperty("spring.cloud.nacos.discovery.server-addr")) - .isEqualTo(""); - assertThat(System.getProperty("spring.cloud.nacos.discovery.endpoint")) - .isEqualTo("testDomain"); - assertThat(System.getProperty("spring.cloud.nacos.discovery.namespace")) - .isEqualTo("testTenantId"); - assertThat(System.getProperty("spring.cloud.nacos.discovery.access-key")) - .isEqualTo("testAK"); - assertThat(System.getProperty("spring.cloud.nacos.discovery.secret-key")) - .isEqualTo("testSK"); - assertThat(System.getProperties().getProperty("nacos.naming.web.context")) - .isEqualTo("/vipserver"); - assertThat(System.getProperties().getProperty("nacos.naming.exposed.port")) - .isEqualTo("80"); - } -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/oss/OssAutoConfigurationTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/oss/OssAutoConfigurationTests.java deleted file mode 100644 index ecbd0c0f..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/oss/OssAutoConfigurationTests.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.oss; - -import com.alibaba.alicloud.context.AliCloudProperties; - -import com.aliyun.oss.OSS; -import com.aliyun.oss.OSSClient; -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * {@link OSS} {@link OssProperties} Test - * - * @author Jim - */ -public class OssAutoConfigurationTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(OssContextAutoConfiguration.class)) - .withPropertyValues("spring.cloud.alicloud.accessKey=your-ak", - "spring.cloud.alicloud.secretKey=your-sk", - "spring.cloud.alicloud.oss.endpoint=http://oss-cn-beijing.aliyuncs.com", - "spring.cloud.alicloud.oss.config.userAgent=alibaba", - "spring.cloud.alicloud.oss.sts.access-key=your-sts-ak", - "spring.cloud.alicloud.oss.sts.secret-key=your-sts-sk", - "spring.cloud.alicloud.oss.sts.security-token=your-sts-token"); - - @Test - public void testOSSProperties() { - this.contextRunner.run(context -> { - assertThat(context.getBeansOfType(OssProperties.class).size() == 1).isTrue(); - AliCloudProperties aliCloudProperties = context - .getBean(AliCloudProperties.class); - OssProperties ossProperties = context.getBean(OssProperties.class); - assertThat(aliCloudProperties.getAccessKey()).isEqualTo("your-ak"); - assertThat(aliCloudProperties.getSecretKey()).isEqualTo("your-sk"); - assertThat(ossProperties.getEndpoint()) - .isEqualTo("http://oss-cn-beijing.aliyuncs.com"); - assertThat(ossProperties.getConfig().getUserAgent()).isEqualTo("alibaba"); - assertThat(ossProperties.getSts().getAccessKey()).isEqualTo("your-sts-ak"); - assertThat(ossProperties.getSts().getSecretKey()).isEqualTo("your-sts-sk"); - assertThat(ossProperties.getSts().getSecurityToken()) - .isEqualTo("your-sts-token"); - }); - } - - @Test - public void testOSSClient1() { - this.contextRunner.run(context -> { - assertThat(context.getBeansOfType(OSS.class).size() == 1).isTrue(); - assertThat(context.getBeanNamesForType(OSS.class)[0]).isEqualTo("ossClient"); - OSSClient ossClient = (OSSClient) context.getBean(OSS.class); - assertThat(ossClient.getEndpoint().toString()) - .isEqualTo("http://oss-cn-beijing.aliyuncs.com"); - assertThat(ossClient.getClientConfiguration().getUserAgent()) - .isEqualTo("alibaba"); - assertThat( - ossClient.getCredentialsProvider().getCredentials().getAccessKeyId()) - .isEqualTo("your-ak"); - assertThat(ossClient.getCredentialsProvider().getCredentials() - .getSecretAccessKey()).isEqualTo("your-sk"); - }); - } - - @Test - public void testOSSClient2() { - this.contextRunner - .withPropertyValues("spring.cloud.alicloud.oss.authorization-mode=STS") - .run(context -> { - assertThat(context.getBeansOfType(OSS.class).size() == 1).isTrue(); - assertThat(context.getBeanNamesForType(OSS.class)[0]) - .isEqualTo("ossClient"); - OSSClient ossClient = (OSSClient) context.getBean(OSS.class); - assertThat(ossClient.getEndpoint().toString()) - .isEqualTo("http://oss-cn-beijing.aliyuncs.com"); - assertThat(ossClient.getClientConfiguration().getUserAgent()) - .isEqualTo("alibaba"); - assertThat(ossClient.getCredentialsProvider().getCredentials() - .getAccessKeyId()).isEqualTo("your-sts-ak"); - assertThat(ossClient.getCredentialsProvider().getCredentials() - .getSecretAccessKey()).isEqualTo("your-sts-sk"); - assertThat(ossClient.getCredentialsProvider().getCredentials() - .getSecurityToken()).isEqualTo("your-sts-token"); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/scx/ScxAutoConfigurationTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/scx/ScxAutoConfigurationTests.java deleted file mode 100644 index 38fd1f7f..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/scx/ScxAutoConfigurationTests.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.scx; - -import com.alibaba.alicloud.context.edas.EdasProperties; - -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.Assertions.assertThat; - -/** - * @author xiaolongzuo - */ -public class ScxAutoConfigurationTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(ScxContextAutoConfiguration.class)) - .withPropertyValues("spring.cloud.alicloud.scx.group-id=1-2-3-4") - .withPropertyValues("spring.cloud.alicloud.edas.namespace=cn-test"); - - @Test - public void testSxcProperties() { - this.contextRunner.run(context -> { - assertThat(context.getBeansOfType(ScxProperties.class).size() == 1).isTrue(); - EdasProperties edasProperties = context.getBean(EdasProperties.class); - ScxProperties scxProperties = context.getBean(ScxProperties.class); - assertThat(scxProperties.getGroupId()).isEqualTo("1-2-3-4"); - assertThat(edasProperties.getNamespace()).isEqualTo("cn-test"); - assertThat(scxProperties.getDomainName()).isNull(); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListenerTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListenerTests.java deleted file mode 100644 index 5fde2951..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sentinel/SentinelAliCloudListenerTests.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.sentinel; - -import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; -import com.alibaba.alicloud.context.Constants; -import com.alibaba.alicloud.utils.ChangeOrderUtils; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.junit.BeforeClass; -import org.junit.Test; -import org.powermock.core.classloader.annotations.PrepareForTest; - -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - -/** - * @author xiaolongzuo - */ -@PrepareForTest({ EdasChangeOrderConfigurationFactory.class, - SentinelAliCloudListener.class }) -public class SentinelAliCloudListenerTests extends BaseAliCloudSpringApplication { - - @BeforeClass - public static void setUp() { - ChangeOrderUtils.mockChangeOrder(); - } - - @Test - public void testNacosParameterInitListener() { - assertThat(System.getProperty(Constants.Sentinel.NACOS_DATASOURCE_ENDPOINT)) - .isEqualTo("testDomain"); - assertThat(System.getProperty(Constants.Sentinel.PROJECT_NAME)) - .isEqualTo("testProjectName"); - assertThat(System.getProperty(Constants.Sentinel.NACOS_DATASOURCE_NAMESPACE)) - .isEqualTo("testTenantId"); - assertThat(System.getProperty(Constants.Sentinel.NACOS_DATASOURCE_AK)) - .isEqualTo("testAK"); - assertThat(System.getProperty(Constants.Sentinel.NACOS_DATASOURCE_SK)) - .isEqualTo("testSK"); - - } -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sms/SmsPropertiesTests.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sms/SmsPropertiesTests.java deleted file mode 100644 index dd1965b8..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/context/sms/SmsPropertiesTests.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.context.sms; - -import com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; - -import org.assertj.core.api.AssertionsForClassTypes; -import org.junit.Test; - -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - -/** - * @author xiaolongzuo - */ -public class SmsPropertiesTests { - - private ApplicationContextRunner contextRunner = new ApplicationContextRunner() - .withConfiguration(AutoConfigurations.of(SmsContextAutoConfiguration.class, - EdasContextAutoConfiguration.class, - AliCloudContextAutoConfiguration.class)); - - @Test - public void testConfigurationValueDefaultsAreAsExpected() { - this.contextRunner.run(context -> { - SmsProperties config = context.getBean(SmsProperties.class); - assertThat(config.getReportQueueName()).isNull(); - assertThat(config.getUpQueueName()).isNull(); - assertThat(config.getConnectTimeout()).isEqualTo("10000"); - assertThat(config.getReadTimeout()).isEqualTo("10000"); - }); - } - - @Test - public void testConfigurationValuesAreCorrectlyLoaded() { - this.contextRunner - .withPropertyValues("spring.cloud.alicloud.sms.reportQueueName=q1", - "spring.cloud.alicloud.sms.upQueueName=q2", - "spring.cloud.alicloud.sms.connect-timeout=20", - "spring.cloud.alicloud.sms.read-timeout=30") - .run(context -> { - SmsProperties config = context.getBean(SmsProperties.class); - AssertionsForClassTypes.assertThat(config.getReportQueueName()) - .isEqualTo("q1"); - AssertionsForClassTypes.assertThat(config.getUpQueueName()) - .isEqualTo("q2"); - AssertionsForClassTypes.assertThat(config.getConnectTimeout()) - .isEqualTo("20"); - AssertionsForClassTypes.assertThat(config.getReadTimeout()) - .isEqualTo("30"); - }); - } - -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java deleted file mode 100644 index 159d28ee..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss; - -/** - * @author xiaolongzuo - */ -public class OssAutoConfiguration { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java deleted file mode 100644 index cae4aade..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.scx; - -/** - * @author xiaolongzuo - */ -public class ScxAutoConfiguration { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/utils/ChangeOrderUtils.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/utils/ChangeOrderUtils.java deleted file mode 100644 index f03bd41f..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/alicloud/utils/ChangeOrderUtils.java +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.utils; - -import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; -import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; - -import org.powermock.api.mockito.PowerMockito; - -/** - * @author xiaolongzuo - */ -public class ChangeOrderUtils { - - private ChangeOrderUtils() { - } - - public static void mockChangeOrder() { - EdasChangeOrderConfiguration edasChangeOrderConfiguration = PowerMockito - .mock(EdasChangeOrderConfiguration.class); - PowerMockito.when(edasChangeOrderConfiguration.isEdasManaged()).thenReturn(true); - PowerMockito.when(edasChangeOrderConfiguration.getAddressServerDomain()) - .thenReturn("testDomain"); - PowerMockito.when(edasChangeOrderConfiguration.getTenantId()) - .thenReturn("testTenantId"); - PowerMockito.when(edasChangeOrderConfiguration.getDauthAccessKey()) - .thenReturn("testAK"); - PowerMockito.when(edasChangeOrderConfiguration.getDauthSecretKey()) - .thenReturn("testSK"); - PowerMockito.when(edasChangeOrderConfiguration.getProjectName()) - .thenReturn("testProjectName"); - PowerMockito.when(edasChangeOrderConfiguration.getAddressServerPort()) - .thenReturn("8080"); - PowerMockito.mockStatic(EdasChangeOrderConfigurationFactory.class); - PowerMockito - .when(EdasChangeOrderConfigurationFactory - .getEdasChangeOrderConfiguration()) - .thenReturn(edasChangeOrderConfiguration); - } -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java deleted file mode 100644 index bef13171..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos; - -/** - * @author xiaolongzuo - */ -public class NacosConfigAutoConfiguration { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java deleted file mode 100644 index d9f47e11..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.nacos; - -/** - * @author xiaolongzuo - */ -public class NacosDiscoveryAutoConfiguration { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/alibaba/csp/sentinel/datasource/nacos/NacosDataSource.java b/spring-cloud-alicloud-context/src/test/java/com/alibaba/csp/sentinel/datasource/nacos/NacosDataSource.java deleted file mode 100644 index 7159a2f4..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/alibaba/csp/sentinel/datasource/nacos/NacosDataSource.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.csp.sentinel.datasource.nacos; - -/** - * @author xiaolongzuo - */ -public class NacosDataSource { -} diff --git a/spring-cloud-alicloud-context/src/test/java/com/aliyuncs/dysmsapi/model/v20170525/SendSmsRequest.java b/spring-cloud-alicloud-context/src/test/java/com/aliyuncs/dysmsapi/model/v20170525/SendSmsRequest.java deleted file mode 100644 index ef660e84..00000000 --- a/spring-cloud-alicloud-context/src/test/java/com/aliyuncs/dysmsapi/model/v20170525/SendSmsRequest.java +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.aliyuncs.dysmsapi.model.v20170525; - -/** - * @author xiaolongzuo - */ -public class SendSmsRequest { -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssApplicationListener.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssApplicationListener.java deleted file mode 100644 index 74cda28d..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssApplicationListener.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss; - -import java.util.Map; - -import com.aliyun.oss.OSS; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.context.ApplicationListener; -import org.springframework.context.event.ContextClosedEvent; - -/** - * Shutdown All OSS Clients when {@code ApplicationContext} gets closed - * {@link ApplicationListener} - * - * @author Jim - */ -public class OssApplicationListener implements ApplicationListener { - - private static final Logger log = LoggerFactory - .getLogger(OssApplicationListener.class); - - @Override - public void onApplicationEvent(ContextClosedEvent event) { - Map ossClientMap = event.getApplicationContext() - .getBeansOfType(OSS.class); - log.info("{} OSSClients will be shutdown soon", ossClientMap.size()); - ossClientMap.keySet().forEach(beanName -> { - log.info("shutdown ossClient: {}", beanName); - ossClientMap.get(beanName).shutdown(); - }); - } -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java deleted file mode 100644 index 2d87eddc..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssAutoConfiguration.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss; - -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.alibaba.alicloud.oss.resource.OssStorageProtocolResolver; -import com.aliyun.oss.OSS; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -import static com.alibaba.alicloud.oss.OssConstants.OSS_TASK_EXECUTOR_BEAN_NAME; - -/** - * OSS Auto {@link Configuration}. - * - * @author Jim - */ -@Configuration -@ConditionalOnClass(OSS.class) -@ConditionalOnProperty(name = OssConstants.ENABLED, havingValue = "true", matchIfMissing = true) -public class OssAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - public OssStorageProtocolResolver ossStorageProtocolResolver() { - return new OssStorageProtocolResolver(); - } - - @Bean(name = OSS_TASK_EXECUTOR_BEAN_NAME) - @ConditionalOnMissingBean - public ExecutorService ossTaskExecutor() { - int coreSize = Runtime.getRuntime().availableProcessors(); - return new ThreadPoolExecutor(coreSize, 128, 60, TimeUnit.SECONDS, - new SynchronousQueue<>()); - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssConstants.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssConstants.java deleted file mode 100644 index 8bee73f6..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/OssConstants.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss; - -/** - * OSS constants. - * - * @author Jim - */ -public final class OssConstants { - - /** - * Prefix of OSSConfigurationProperties. - */ - public static final String PREFIX = "spring.cloud.alibaba.oss"; - - /** - * Enable OSS. - */ - public static final String ENABLED = PREFIX + ".enabled"; - - /** - * OSS ThreadPool bean name. - */ - public static final String OSS_TASK_EXECUTOR_BEAN_NAME = "ossTaskExecutor"; - - private OssConstants() { - throw new AssertionError("Must not instantiate constant utility class"); - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpoint.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpoint.java deleted file mode 100644 index 40a2d3a6..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpoint.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.endpoint; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import com.aliyun.oss.OSSClient; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import org.springframework.context.ApplicationContext; - -/** - * Actuator {@link Endpoint} to expose OSS Meta Data - * - * @author Jim - */ -@Endpoint(id = "oss") -public class OssEndpoint { - - @Autowired - private ApplicationContext applicationContext; - - @ReadOperation - public Map invoke() { - Map result = new HashMap<>(); - - Map ossClientMap = applicationContext - .getBeansOfType(OSSClient.class); - - int size = ossClientMap.size(); - - List ossClientList = new ArrayList<>(); - - ossClientMap.keySet().forEach(beanName -> { - Map ossProperties = new HashMap<>(); - OSSClient client = ossClientMap.get(beanName); - ossProperties.put("beanName", beanName); - ossProperties.put("endpoint", client.getEndpoint().toString()); - ossProperties.put("clientConfiguration", client.getClientConfiguration()); - ossProperties.put("credentials", - client.getCredentialsProvider().getCredentials()); - ossProperties.put("bucketList", client.listBuckets().stream() - .map(bucket -> bucket.getName()).toArray()); - ossClientList.add(ossProperties); - }); - - result.put("size", size); - result.put("info", ossClientList); - - return result; - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpointAutoConfiguration.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpointAutoConfiguration.java deleted file mode 100644 index e4e49f34..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/endpoint/OssEndpointAutoConfiguration.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.endpoint; - -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * OSS {@link Endpoint} Auto-{@link Configuration} - * - * @author Jim - */ -@ConditionalOnClass(Endpoint.class) -public class OssEndpointAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - @ConditionalOnEnabledEndpoint - public OssEndpoint ossEndpoint() { - return new OssEndpoint(); - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageProtocolResolver.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageProtocolResolver.java deleted file mode 100644 index 0a372e1d..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageProtocolResolver.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.resource; - -import com.aliyun.oss.OSS; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.BeansException; -import org.springframework.beans.factory.config.BeanFactoryPostProcessor; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.context.ResourceLoaderAware; -import org.springframework.core.io.DefaultResourceLoader; -import org.springframework.core.io.ProtocolResolver; -import org.springframework.core.io.Resource; -import org.springframework.core.io.ResourceLoader; - -/** - * A {@link ProtocolResolver} implementation for the {@code oss://} protocol. - * - * @author Jim - */ -public class OssStorageProtocolResolver - implements ProtocolResolver, BeanFactoryPostProcessor, ResourceLoaderAware { - - /** - * protocol of oss resource. - */ - public static final String PROTOCOL = "oss://"; - - private static final Logger log = LoggerFactory - .getLogger(OssStorageProtocolResolver.class); - - private ConfigurableListableBeanFactory beanFactory; - - private OSS oss; - - private OSS getOSS() { - if (this.oss == null) { - if (this.beanFactory.getBeansOfType(OSS.class).size() > 1) { - log.warn( - "There are multiple OSS instances, consider marking one of them as @Primary to resolve oss " - + "protocol."); - } - this.oss = this.beanFactory.getBean(OSS.class); - } - return this.oss; - } - - @Override - public Resource resolve(String location, ResourceLoader resourceLoader) { - if (!location.startsWith(PROTOCOL)) { - return null; - } - return new OssStorageResource(getOSS(), location, beanFactory); - } - - @Override - public void setResourceLoader(ResourceLoader resourceLoader) { - if (DefaultResourceLoader.class.isAssignableFrom(resourceLoader.getClass())) { - ((DefaultResourceLoader) resourceLoader).addProtocolResolver(this); - } - else { - log.warn("The provided delegate resource loader is not an implementation " - + "of DefaultResourceLoader. Custom Protocol using oss:// prefix will not be enabled."); - } - } - - @Override - public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) - throws BeansException { - this.beanFactory = beanFactory; - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageResource.java b/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageResource.java deleted file mode 100644 index 6f84d2b5..00000000 --- a/spring-cloud-alicloud-oss/src/main/java/com/alibaba/alicloud/oss/resource/OssStorageResource.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.resource; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.io.PipedInputStream; -import java.io.PipedOutputStream; -import java.net.URI; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.concurrent.ExecutorService; - -import com.aliyun.oss.ClientException; -import com.aliyun.oss.OSS; -import com.aliyun.oss.OSSException; -import com.aliyun.oss.model.Bucket; -import com.aliyun.oss.model.OSSObject; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.core.io.Resource; -import org.springframework.core.io.WritableResource; -import org.springframework.util.Assert; - -import static com.alibaba.alicloud.oss.OssConstants.OSS_TASK_EXECUTOR_BEAN_NAME; - -/** - * Implements {@link Resource} for reading and writing objects in Aliyun Object Storage - * Service (OSS). An instance of this class represents a handle to a bucket or an - * OSSObject. - * - * @author Jim - * @see OSS - * @see Bucket - * @see OSSObject - */ -public class OssStorageResource implements WritableResource { - - private static final Logger logger = LoggerFactory - .getLogger(OssStorageResource.class); - - private static final String MESSAGE_KEY_NOT_EXIST = "The specified key does not exist."; - - private final OSS oss; - - private final String bucketName; - - private final String objectKey; - - private final URI location; - - private final boolean autoCreateFiles; - - private final ExecutorService ossTaskExecutor; - - private final ConfigurableListableBeanFactory beanFactory; - - public OssStorageResource(OSS oss, String location, - ConfigurableListableBeanFactory beanFactory) { - this(oss, location, beanFactory, false); - } - - public OssStorageResource(OSS oss, String location, - ConfigurableListableBeanFactory beanFactory, boolean autoCreateFiles) { - Assert.notNull(oss, "Object Storage Service can not be null"); - Assert.isTrue(location.startsWith(OssStorageProtocolResolver.PROTOCOL), - "Location must start with " + OssStorageProtocolResolver.PROTOCOL); - this.oss = oss; - this.autoCreateFiles = autoCreateFiles; - this.beanFactory = beanFactory; - try { - URI locationUri = new URI(location); - this.bucketName = locationUri.getAuthority(); - - if (locationUri.getPath() != null && locationUri.getPath().length() > 1) { - this.objectKey = locationUri.getPath().substring(1); - } - else { - this.objectKey = null; - } - this.location = locationUri; - } - catch (URISyntaxException e) { - throw new IllegalArgumentException("Invalid location: " + location, e); - } - - this.ossTaskExecutor = this.beanFactory.getBean(OSS_TASK_EXECUTOR_BEAN_NAME, - ExecutorService.class); - } - - public boolean isAutoCreateFiles() { - return this.autoCreateFiles; - } - - @Override - public boolean exists() { - try { - return isBucket() ? getBucket() != null : getOSSObject() != null; - } - catch (Exception e) { - return false; - } - } - - /** - * Since the oss: protocol will normally not have a URL stream handler registered, - * this method will always throw a {@link java.net.MalformedURLException}. - * @return The URL for the OSS resource, if a URL stream handler is registered for the - * oss protocol. - */ - @Override - public URL getURL() throws IOException { - return this.location.toURL(); - } - - @Override - public URI getURI() throws IOException { - return this.location; - } - - @Override - public File getFile() throws IOException { - throw new UnsupportedOperationException( - getDescription() + " cannot be resolved to absolute file path"); - } - - @Override - public long contentLength() throws IOException { - assertExisted(); - if (isBucket()) { - throw new FileNotFoundException("OSSObject not existed."); - } - return getOSSObject().getObjectMetadata().getContentLength(); - } - - @Override - public long lastModified() throws IOException { - assertExisted(); - if (isBucket()) { - throw new FileNotFoundException("OSSObject not existed."); - } - return getOSSObject().getObjectMetadata().getLastModified().getTime(); - } - - @Override - public Resource createRelative(String relativePath) throws IOException { - return new OssStorageResource(this.oss, - this.location.resolve(relativePath).toString(), this.beanFactory); - } - - @Override - public String getFilename() { - return isBucket() ? this.bucketName : this.objectKey; - } - - @Override - public String getDescription() { - return this.location.toString(); - } - - @Override - public InputStream getInputStream() throws IOException { - assertExisted(); - if (isBucket()) { - throw new IllegalStateException( - "Cannot open an input stream to a bucket: '" + this.location + "'"); - } - else { - return getOSSObject().getObjectContent(); - } - } - - /** - * Returns the {@link Bucket} associated with the resource. - * @return the bucket if it exists, or null otherwise - */ - public Bucket getBucket() { - return this.oss.listBuckets().stream() - .filter(bucket -> bucket.getName().equals(this.bucketName)).findFirst() - .orElse(null); - } - - /** - * Checks for the existence of the {@link Bucket} associated with the resource. - * @return true if the bucket exists - */ - public boolean bucketExists() { - return getBucket() != null; - } - - /** - * Gets the underlying resource object in Aliyun Object Storage Service. - * @return The resource object, will be null if it does not exist in Aliyun Object - * Storage Service. - * @throws OSSException it is thrown upon error when accessing OSS - * @throws ClientException it is the one thrown by the client side when accessing OSS - */ - public OSSObject getOSSObject() { - return this.oss.getObject(this.bucketName, this.objectKey); - } - - /** - * Check if this resource references a bucket and not a blob. - * @return if the resource is bucket - */ - public boolean isBucket() { - return this.objectKey == null; - } - - private void assertExisted() throws FileNotFoundException { - if (!exists()) { - throw new FileNotFoundException("Bucket or OSSObject not existed."); - } - } - - /** - * create a bucket. - * @return OSS Bucket - */ - public Bucket createBucket() { - return this.oss.createBucket(this.bucketName); - } - - @Override - public boolean isWritable() { - return !isBucket() && (this.autoCreateFiles || exists()); - } - - /** - * acquire an OutputStream for write. Note: please close the stream after writing is - * done - * @return OutputStream of OSS resource - * @throws IOException throw by oss operation - */ - @Override - public OutputStream getOutputStream() throws IOException { - if (isBucket()) { - throw new IllegalStateException( - "Cannot open an output stream to a bucket: '" + getURI() + "'"); - } - else { - OSSObject ossObject; - - try { - ossObject = this.getOSSObject(); - } - catch (OSSException ex) { - if (ex.getMessage() != null - && ex.getMessage().startsWith(MESSAGE_KEY_NOT_EXIST)) { - ossObject = null; - } - else { - throw ex; - } - } - - if (ossObject == null) { - if (!this.autoCreateFiles) { - throw new FileNotFoundException( - "The object was not found: " + getURI()); - } - - } - - PipedInputStream in = new PipedInputStream(); - final PipedOutputStream out = new PipedOutputStream(in); - - ossTaskExecutor.submit(() -> { - try { - OssStorageResource.this.oss.putObject(bucketName, objectKey, in); - } - catch (Exception ex) { - logger.error("Failed to put object", ex); - } - }); - - return out; - } - - } - -} diff --git a/spring-cloud-alicloud-oss/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-oss/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 4f24942b..00000000 --- a/spring-cloud-alicloud-oss/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,6 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ -com.alibaba.alicloud.oss.OssAutoConfiguration,\ -com.alibaba.alicloud.oss.endpoint.OssEndpointAutoConfiguration - -org.springframework.context.ApplicationListener=\ -com.alibaba.alicloud.oss.OssApplicationListener \ No newline at end of file diff --git a/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java b/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java deleted file mode 100644 index 0d429975..00000000 --- a/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.resource; - -import java.io.ByteArrayInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; - -import com.aliyun.oss.model.Bucket; -import com.aliyun.oss.model.OSSObject; -import com.aliyun.oss.model.ObjectMetadata; -import com.aliyun.oss.model.PutObjectResult; - -import org.springframework.util.StreamUtils; - -/** - * @author lich - */ -public class DummyOssClient { - - private Map storeMap = new ConcurrentHashMap<>(); - - private Map bucketSet = new HashMap<>(); - - public String getStoreKey(String bucketName, String objectKey) { - return String.join(".", bucketName, objectKey); - } - - public PutObjectResult putObject(String bucketName, String objectKey, - InputStream inputStream) { - - try { - byte[] result = StreamUtils.copyToByteArray(inputStream); - storeMap.put(getStoreKey(bucketName, objectKey), result); - } - catch (IOException ex) { - throw new RuntimeException(ex); - } - finally { - try { - inputStream.close(); - } - catch (IOException ex) { - throw new RuntimeException(ex); - } - } - - return new PutObjectResult(); - } - - public OSSObject getOSSObject(String bucketName, String objectKey) { - byte[] value = storeMap.get(this.getStoreKey(bucketName, objectKey)); - if (value == null) { - return null; - } - OSSObject ossObject = new OSSObject(); - ossObject.setBucketName(bucketName); - ossObject.setKey(objectKey); - InputStream inputStream = new ByteArrayInputStream(value); - ossObject.setObjectContent(inputStream); - - ObjectMetadata objectMetadata = new ObjectMetadata(); - objectMetadata.setContentLength(value.length); - ossObject.setObjectMetadata(objectMetadata); - - return ossObject; - } - - public Bucket createBucket(String bucketName) { - if (bucketSet.containsKey(bucketName)) { - return bucketSet.get(bucketName); - } - Bucket bucket = new Bucket(); - bucket.setCreationDate(new Date()); - bucket.setName(bucketName); - bucketSet.put(bucketName, bucket); - return bucket; - } - - public List bucketList() { - return new ArrayList<>(bucketSet.values()); - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/OssStorageResourceTest.java b/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/OssStorageResourceTest.java deleted file mode 100644 index 2e977102..00000000 --- a/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/OssStorageResourceTest.java +++ /dev/null @@ -1,273 +0,0 @@ -/* - * Copyright 2013-2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * https://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.oss.resource; - -import java.io.ByteArrayInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.util.Random; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.SynchronousQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -import com.aliyun.oss.OSS; -import org.junit.Rule; -import org.junit.Test; -import org.junit.rules.ExpectedException; -import org.junit.runner.RunWith; -import org.mockito.Mockito; - -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; -import org.springframework.core.io.Resource; -import org.springframework.core.io.WritableResource; -import org.springframework.test.context.junit4.SpringRunner; -import org.springframework.util.StreamUtils; - -import static com.alibaba.alicloud.oss.OssConstants.OSS_TASK_EXECUTOR_BEAN_NAME; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.Mockito.doAnswer; -import static org.mockito.Mockito.mock; - -/** - * @author lich - */ -@SpringBootTest -@RunWith(SpringRunner.class) -public class OssStorageResourceTest { - - /** - * Used to test exception messages and types. - */ - @Rule - public ExpectedException expectedEx = ExpectedException.none(); - - @Autowired - private ConfigurableListableBeanFactory beanFactory; - - @Autowired - private OSS oss; - - @Value("oss://aliyun-test-bucket/") - private Resource bucketResource; - - @Value("oss://aliyun-test-bucket/myfilekey") - private Resource remoteResource; - - public static byte[] generateRandomBytes(int blen) { - byte[] array = new byte[blen]; - new Random().nextBytes(array); - return array; - } - - @Test - public void testResourceType() { - assertThat(remoteResource.getClass()).isEqualTo(OssStorageResource.class); - OssStorageResource ossStorageResource = (OssStorageResource) remoteResource; - assertThat(ossStorageResource.getFilename()).isEqualTo("myfilekey"); - assertThat(ossStorageResource.isBucket()).isEqualTo(false); - } - - @Test - public void testValidObject() throws Exception { - assertThat(remoteResource.exists()).isEqualTo(true); - OssStorageResource ossStorageResource = (OssStorageResource) remoteResource; - assertThat(ossStorageResource.bucketExists()).isEqualTo(true); - assertThat(remoteResource.contentLength()).isEqualTo(4096L); - assertThat(remoteResource.getURI().toString()) - .isEqualTo("oss://aliyun-test-bucket/myfilekey"); - assertThat(remoteResource.getFilename()).isEqualTo("myfilekey"); - } - - @Test - public void testBucketResource() throws Exception { - assertThat(bucketResource.exists()).isEqualTo(true); - assertThat(((OssStorageResource) this.bucketResource).isBucket()).isEqualTo(true); - assertThat(((OssStorageResource) this.bucketResource).bucketExists()) - .isEqualTo(true); - assertThat(bucketResource.getURI().toString()) - .isEqualTo("oss://aliyun-test-bucket/"); - assertThat(this.bucketResource.getFilename()).isEqualTo("aliyun-test-bucket"); - } - - @Test - public void testBucketNotEndingInSlash() { - assertThat( - new OssStorageResource(this.oss, "oss://aliyun-test-bucket", beanFactory) - .isBucket()).isEqualTo(true); - } - - @Test - public void testSpecifyPathCorrect() { - OssStorageResource ossStorageResource = new OssStorageResource(this.oss, - "oss://aliyun-test-bucket/myfilekey", beanFactory, false); - assertThat(ossStorageResource.exists()).isEqualTo(true); - } - - @Test - public void testSpecifyBucketCorrect() { - OssStorageResource ossStorageResource = new OssStorageResource(this.oss, - "oss://aliyun-test-bucket", beanFactory, false); - - assertThat(ossStorageResource.isBucket()).isEqualTo(true); - assertThat(ossStorageResource.getBucket().getName()) - .isEqualTo("aliyun-test-bucket"); - assertThat(ossStorageResource.exists()).isEqualTo(true); - } - - @Test - public void testBucketOutputStream() throws IOException { - this.expectedEx.expect(IllegalStateException.class); - this.expectedEx.expectMessage( - "Cannot open an output stream to a bucket: 'oss://aliyun-test-bucket/'"); - ((WritableResource) this.bucketResource).getOutputStream(); - } - - @Test - public void testBucketInputStream() throws IOException { - this.expectedEx.expect(IllegalStateException.class); - this.expectedEx.expectMessage( - "Cannot open an input stream to a bucket: 'oss://aliyun-test-bucket/'"); - this.bucketResource.getInputStream(); - } - - @Test - public void testBucketContentLength() throws IOException { - this.expectedEx.expect(FileNotFoundException.class); - this.expectedEx.expectMessage("OSSObject not existed."); - this.bucketResource.contentLength(); - } - - @Test - public void testBucketFile() throws IOException { - this.expectedEx.expect(UnsupportedOperationException.class); - this.expectedEx.expectMessage( - "oss://aliyun-test-bucket/ cannot be resolved to absolute file path"); - this.bucketResource.getFile(); - } - - @Test - public void testBucketLastModified() throws IOException { - this.expectedEx.expect(FileNotFoundException.class); - this.expectedEx.expectMessage("OSSObject not existed."); - this.bucketResource.lastModified(); - } - - @Test - public void testBucketResourceStatuses() { - assertThat(this.bucketResource.isOpen()).isEqualTo(false); - assertThat(((WritableResource) this.bucketResource).isWritable()) - .isEqualTo(false); - assertThat(this.bucketResource.exists()).isEqualTo(true); - } - - @Test - public void testWritable() throws Exception { - assertThat(this.remoteResource instanceof WritableResource).isEqualTo(true); - WritableResource writableResource = (WritableResource) this.remoteResource; - assertThat(writableResource.isWritable()).isEqualTo(true); - writableResource.getOutputStream(); - } - - @Test - public void testWritableOutputStream() throws Exception { - String location = "oss://aliyun-test-bucket/test"; - OssStorageResource resource = new OssStorageResource(this.oss, location, - beanFactory, true); - OutputStream os = resource.getOutputStream(); - assertThat(os).isNotNull(); - - byte[] randomBytes = generateRandomBytes(1203); - String expectedString = new String(randomBytes); - - os.write(randomBytes); - os.close(); - - InputStream in = resource.getInputStream(); - - byte[] result = StreamUtils.copyToByteArray(in); - String actualString = new String(result); - - assertThat(actualString).isEqualTo(expectedString); - } - - @Test - public void testCreateBucket() { - String location = "oss://my-new-test-bucket/"; - OssStorageResource resource = new OssStorageResource(this.oss, location, - beanFactory, true); - - resource.createBucket(); - - assertThat(resource.bucketExists()).isEqualTo(true); - } - - /** - * Configuration for the tests. - */ - @Configuration - @Import(OssStorageProtocolResolver.class) - static class TestConfiguration { - - @Bean(name = OSS_TASK_EXECUTOR_BEAN_NAME) - @ConditionalOnMissingBean - public ExecutorService ossTaskExecutor() { - return new ThreadPoolExecutor(8, 128, 60, TimeUnit.SECONDS, - new SynchronousQueue<>()); - } - - @Bean - public static OSS mockOSS() { - DummyOssClient dummyOssStub = new DummyOssClient(); - OSS oss = mock(OSS.class); - - doAnswer(invocation -> dummyOssStub.putObject(invocation.getArgument(0), - invocation.getArgument(1), invocation.getArgument(2))).when(oss) - .putObject(Mockito.anyString(), Mockito.anyString(), - Mockito.any(InputStream.class)); - - doAnswer(invocation -> dummyOssStub.getOSSObject(invocation.getArgument(0), - invocation.getArgument(1))).when(oss).getObject(Mockito.anyString(), - Mockito.anyString()); - - doAnswer(invocation -> dummyOssStub.bucketList()).when(oss).listBuckets(); - - doAnswer(invocation -> dummyOssStub.createBucket(invocation.getArgument(0))) - .when(oss).createBucket(Mockito.anyString()); - - // prepare object - dummyOssStub.createBucket("aliyun-test-bucket"); - - byte[] content = generateRandomBytes(4096); - ByteArrayInputStream inputStream = new ByteArrayInputStream(content); - dummyOssStub.putObject("aliyun-test-bucket", "myfilekey", inputStream); - - return oss; - } - - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-schedulerx/pom.xml b/spring-cloud-alicloud-schedulerx/pom.xml deleted file mode 100644 index 96e6fdbd..00000000 --- a/spring-cloud-alicloud-schedulerx/pom.xml +++ /dev/null @@ -1,53 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - 4.0.0 - spring-cloud-alicloud-schedulerx - Spring Cloud Alibaba Cloud SchedulerX - - - - com.alibaba.cloud - spring-cloud-alicloud-context - - - org.slf4j - slf4j-api - - - com.alibaba.edas - schedulerX-client - - - com.aliyun - aliyun-java-sdk-core - - - com.aliyun - aliyun-java-sdk-edas - - - org.springframework.boot - spring-boot-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - org.springframework.boot - spring-boot-actuator - true - - - \ No newline at end of file diff --git a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java b/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java deleted file mode 100644 index 47beae5c..00000000 --- a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/ScxAutoConfiguration.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.scx; - -import org.springframework.context.annotation.Configuration; - -/** - * placeholder configuration - * - * @author xiaolongzuo - */ -@Configuration -public class ScxAutoConfiguration { - -} diff --git a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpoint.java b/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpoint.java deleted file mode 100644 index 8334aff1..00000000 --- a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpoint.java +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.scx.endpoint; - -import java.util.HashMap; -import java.util.Map; - -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.alicloud.context.scx.ScxProperties; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -/** - * @author xiaolongzuo - */ -@Endpoint(id = "scx") -public class ScxEndpoint { - - private static final Logger LOGGER = LoggerFactory.getLogger(ScxEndpoint.class); - - private ScxProperties scxProperties; - - private EdasProperties edasProperties; - - public ScxEndpoint(EdasProperties edasProperties, ScxProperties scxProperties) { - this.edasProperties = edasProperties; - this.scxProperties = scxProperties; - } - - /** - * @return scx endpoint - */ - @ReadOperation - public Map invoke() { - Map scxEndpoint = new HashMap<>(); - LOGGER.info("SCX endpoint invoke, scxProperties is {}", scxProperties); - scxEndpoint.put("namespace", - edasProperties == null ? "" : edasProperties.getNamespace()); - scxEndpoint.put("scxProperties", scxProperties); - return scxEndpoint; - } - -} diff --git a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpointAutoConfiguration.java b/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpointAutoConfiguration.java deleted file mode 100644 index e841b845..00000000 --- a/spring-cloud-alicloud-schedulerx/src/main/java/com/alibaba/alicloud/scx/endpoint/ScxEndpointAutoConfiguration.java +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.alicloud.scx.endpoint; - -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.alicloud.context.scx.ScxProperties; - -import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; - -/** - * @author xiaolongzuo - */ -@ConditionalOnWebApplication -@ConditionalOnClass(Endpoint.class) -public class ScxEndpointAutoConfiguration { - - @Bean - @ConditionalOnMissingBean - @ConditionalOnEnabledEndpoint - public ScxEndpoint scxEndpoint(EdasProperties edasProperties, - ScxProperties scxProperties) { - return new ScxEndpoint(edasProperties, scxProperties); - } - -} diff --git a/spring-cloud-alicloud-schedulerx/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-schedulerx/src/main/resources/META-INF/spring.factories deleted file mode 100644 index 3032200c..00000000 --- a/spring-cloud-alicloud-schedulerx/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.alibaba.alicloud.scx.endpoint.ScxEndpointAutoConfiguration,\ - com.alibaba.alicloud.scx.ScxAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/pom.xml b/spring-cloud-alicloud-sms/pom.xml deleted file mode 100644 index 20acea72..00000000 --- a/spring-cloud-alicloud-sms/pom.xml +++ /dev/null @@ -1,78 +0,0 @@ - - - - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - 4.0.0 - - spring-cloud-alicloud-sms - Spring Cloud Alibaba Cloud SMS - - - - - com.alibaba.cloud - spring-cloud-alicloud-context - - - com.aliyun - aliyun-java-sdk-core - - - - - - - com.aliyun - aliyun-java-sdk-core - - - com.aliyun - aliyun-java-sdk-dysmsapi - - - com.aliyun.mns - aliyun-sdk-mns - - - - org.springframework.boot - spring-boot-actuator - provided - true - - - - org.springframework.boot - spring-boot-actuator-autoconfigure - provided - true - - - - org.springframework.boot - spring-boot-configuration-processor - provided - true - - - - org.slf4j - slf4j-api - provided - true - - - - org.springframework.boot - spring-boot-starter-test - test - - - - - diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/AbstractSmsService.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/AbstractSmsService.java deleted file mode 100644 index b27c5dab..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/AbstractSmsService.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -import java.util.concurrent.ConcurrentHashMap; - -import com.aliyuncs.DefaultAcsClient; -import com.aliyuncs.IAcsClient; -import com.aliyuncs.profile.DefaultProfile; - -/** - * - * @author pbting - */ -public abstract class AbstractSmsService implements ISmsService { - - private ConcurrentHashMap acsClientConcurrentHashMap = new ConcurrentHashMap<>(); - - @Override - public IAcsClient getHangZhouRegionClientProfile(String accessKeyId, - String accessKeySecret) { - - return acsClientConcurrentHashMap.computeIfAbsent( - getKey("cn-hangzhou", accessKeyId, accessKeySecret), - (iacsClient) -> new DefaultAcsClient(DefaultProfile - .getProfile("cn-hangzhou", accessKeyId, accessKeySecret))); - } - - private String getKey(String regionId, String accessKeyId, String accessKeySecret) { - - return regionId + ":" + accessKeyId + ":" + accessKeySecret; - } - -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/ISmsService.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/ISmsService.java deleted file mode 100644 index 45f81b44..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/ISmsService.java +++ /dev/null @@ -1,120 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -import com.aliyuncs.IAcsClient; -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; -import com.aliyuncs.exceptions.ClientException; -import com.aliyuncs.exceptions.ServerException; - -/** - * @author pbting - */ -public interface ISmsService { - - /** - * - * @param accessKeyId - * @param secret - * @return IAcsClient - */ - IAcsClient getHangZhouRegionClientProfile(String accessKeyId, String secret); - - /** - * - * @param sendSmsRequest - * @throws ServerException - * @throws ClientException - * @return SendSmsResponse - */ - SendSmsResponse sendSmsRequest(SendSmsRequest sendSmsRequest) - throws ServerException, ClientException; - - /** - * - * @param sendBatchSmsRequest - * @throws ServerException - * @throws ClientException - * @return SendBatchSmsResponse - */ - SendBatchSmsResponse sendSmsBatchRequest(SendBatchSmsRequest sendBatchSmsRequest) - throws ServerException, ClientException; - - /** - * 因为阿里云支持多个 - * accessKeyId/accessKeySecret,当不想使用默认的配置accessKeyId/accessKeySecret时,可以使用这个方法来支持额外 - * 的accessKeyId/accessKeySecret 发送 - * @param sendSmsRequest - * @param accessKeyId - * @param accessKeySecret - * @return - * @throws ServerException - * @throws ClientException - */ - SendSmsResponse sendSmsRequest(SendSmsRequest sendSmsRequest, String accessKeyId, - String accessKeySecret) throws ServerException, ClientException; - - /** - * - * @param sendSmsRequest - * @param accessKeyId - * @param accessKeySecret - * @throws ServerException - * @throws ClientException - * @return SendBatchSmsResponse - */ - SendBatchSmsResponse sendSmsBatchRequest(SendBatchSmsRequest sendSmsRequest, - String accessKeyId, String accessKeySecret) - throws ServerException, ClientException; - - /** - * - * @param smsReportMessageListener - * @return boolean - */ - boolean startSmsReportMessageListener( - SmsReportMessageListener smsReportMessageListener); - - /** - * - * @param smsUpMessageListener - * @return boolean - */ - boolean startSmsUpMessageListener(SmsUpMessageListener smsUpMessageListener); - - /** - * - * @param request - * @param accessKeyId - * @param accessKeySecret - * @return QuerySendDetailsResponse - */ - QuerySendDetailsResponse querySendDetails(QuerySendDetailsRequest request, - String accessKeyId, String accessKeySecret) throws ClientException; - - /** - * - * @param request - * @return QuerySendDetailsResponse - */ - QuerySendDetailsResponse querySendDetails(QuerySendDetailsRequest request) - throws ClientException; -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsInitializerEventListener.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsInitializerEventListener.java deleted file mode 100644 index 60ff79c1..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsInitializerEventListener.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -import java.util.Collection; -import java.util.concurrent.atomic.AtomicBoolean; - -import com.alibaba.alicloud.context.sms.SmsProperties; -import com.alibaba.alicloud.sms.base.MessageListener; - -import com.aliyuncs.exceptions.ClientException; -import com.aliyuncs.profile.DefaultProfile; - -import org.springframework.boot.context.event.ApplicationStartedEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.stereotype.Component; - -/** - * @author pbting - */ -@Component -public class SmsInitializerEventListener - implements ApplicationListener { - - private final AtomicBoolean isCalled = new AtomicBoolean(false); - - private SmsProperties msConfigProperties; - - private ISmsService smsService; - - public SmsInitializerEventListener(SmsProperties msConfigProperties, - ISmsService smsService) { - this.msConfigProperties = msConfigProperties; - this.smsService = smsService; - } - - @Override - public void onApplicationEvent(ApplicationStartedEvent event) { - if (!isCalled.compareAndSet(false, true)) { - return; - } - - // 整个application context refreshed then do - // 可自助调整超时时间 - System.setProperty("sun.net.client.defaultConnectTimeout", - msConfigProperties.getConnectTimeout()); - System.setProperty("sun.net.client.defaultReadTimeout", - msConfigProperties.getReadTimeout()); - // 初始化acsClient,暂不支持region化 - try { - DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", - SmsProperties.SMS_PRODUCT, SmsProperties.SMS_DOMAIN); - Collection messageListeners = event.getApplicationContext() - .getBeansOfType(MessageListener.class).values(); - if (messageListeners.isEmpty()) { - return; - } - - for (MessageListener messageListener : messageListeners) { - if (SmsReportMessageListener.class.isInstance(messageListener)) { - if (msConfigProperties.getReportQueueName() != null - && msConfigProperties.getReportQueueName().trim() - .length() > 0) { - smsService.startSmsReportMessageListener( - (SmsReportMessageListener) messageListener); - continue; - } - - throw new IllegalArgumentException("the SmsReport queue name for " - + messageListener.getClass().getCanonicalName() - + " must be set."); - } - - if (SmsUpMessageListener.class.isInstance(messageListener)) { - - if (msConfigProperties.getUpQueueName() != null - && msConfigProperties.getUpQueueName().trim().length() > 0) { - smsService.startSmsUpMessageListener( - (SmsUpMessageListener) messageListener); - continue; - } - - throw new IllegalArgumentException("the SmsUp queue name for " - + messageListener.getClass().getCanonicalName() - + " must be set."); - } - } - } - catch (ClientException e) { - throw new RuntimeException( - "initialize sms profile end point cause an exception"); - } - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsMessageListener.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsMessageListener.java deleted file mode 100644 index 5904f053..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsMessageListener.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -import com.alibaba.alicloud.sms.base.MessageListener; - -/** - * @author pbting - */ -public interface SmsMessageListener extends MessageListener { -} diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsReportMessageListener.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsReportMessageListener.java deleted file mode 100644 index 39deafa6..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsReportMessageListener.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -/** - * @author pbting - */ -public interface SmsReportMessageListener extends SmsMessageListener { -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsServiceImpl.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsServiceImpl.java deleted file mode 100644 index 79dc7800..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsServiceImpl.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -import java.text.ParseException; - -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.alicloud.context.sms.SmsProperties; -import com.alibaba.alicloud.sms.base.DefaultAlicomMessagePuller; -import com.alibaba.alicloud.sms.endpoint.EndpointManager; -import com.alibaba.alicloud.sms.endpoint.ReceiveMessageEntity; - -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.QuerySendDetailsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsResponse; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse; -import com.aliyuncs.exceptions.ClientException; -import com.aliyuncs.exceptions.ServerException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * @author pbting - */ -public final class SmsServiceImpl extends AbstractSmsService { - - private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class); - /** - * will expose user to call this method send sms message - * @param sendSmsRequest - * @return - */ - private SmsProperties smsProperties; - - private AliCloudProperties aliCloudProperties; - - public SmsServiceImpl(AliCloudProperties aliCloudProperties, - SmsProperties smsProperties) { - this.aliCloudProperties = aliCloudProperties; - this.smsProperties = smsProperties; - } - - @Override - public SendSmsResponse sendSmsRequest(SendSmsRequest sendSmsRequest) - throws ClientException { - - return sendSmsRequest(sendSmsRequest, aliCloudProperties.getAccessKey(), - aliCloudProperties.getSecretKey()); - } - - /** - * 因为阿里云支持多个 - * accessKeyId/accessKeySecret,当不想使用默认的配置accessKeyId/accessKeySecret时,可以使用这个方法来支持额外 - * 的accessKeyId/accessKeySecret 发送 - * @param sendSmsRequest - * @param accessKeyId - * @param accessKeySecret - * @throws ServerException - * @throws ClientException - * @return SendSmsResponse - */ - @Override - public SendSmsResponse sendSmsRequest(SendSmsRequest sendSmsRequest, - String accessKeyId, String accessKeySecret) - throws ServerException, ClientException { - EndpointManager.addSendSmsRequest(sendSmsRequest); - // hint 此处可能会抛出异常,注意catch - return getHangZhouRegionClientProfile(accessKeyId, accessKeySecret) - .getAcsResponse(sendSmsRequest); - } - - /** - * - * @param smsReportMessageListener - * @return boolean - */ - @Override - public boolean startSmsReportMessageListener( - SmsReportMessageListener smsReportMessageListener) { - // 短信回执:SmsReport,短信上行:SmsUp - String messageType = "SmsReport"; - String queueName = smsProperties.getReportQueueName(); - return startReceiveMsg(messageType, queueName, smsReportMessageListener); - } - - /** - * - * @param smsUpMessageListener - * @return boolean - */ - @Override - public boolean startSmsUpMessageListener(SmsUpMessageListener smsUpMessageListener) { - // 短信回执:SmsReport,短信上行:SmsUp - String messageType = "SmsUp"; - String queueName = smsProperties.getUpQueueName(); - return startReceiveMsg(messageType, queueName, smsUpMessageListener); - } - - /** - * - * @param messageType - * @param queueName - * @param messageListener - * @return boolean - */ - private boolean startReceiveMsg(String messageType, String queueName, - SmsMessageListener messageListener) { - String accessKeyId = aliCloudProperties.getAccessKey(); - String accessKeySecret = aliCloudProperties.getSecretKey(); - boolean result = true; - try { - new DefaultAlicomMessagePuller().startReceiveMsg(accessKeyId, accessKeySecret, - messageType, queueName, messageListener); - EndpointManager.addReceiveMessageEntity( - new ReceiveMessageEntity(messageType, queueName, messageListener)); - } - catch (ClientException e) { - log.error("start sms report message listener cause an exception", e); - result = false; - } - catch (ParseException e) { - log.error("start sms report message listener cause an exception", e); - result = false; - } - return result; - } - - /** - * - * @param sendBatchSmsRequest - * @throws ServerException - * @throws ClientException - * @return SendBatchSmsResponse - */ - @Override - public SendBatchSmsResponse sendSmsBatchRequest( - SendBatchSmsRequest sendBatchSmsRequest) - throws ServerException, ClientException { - - return sendSmsBatchRequest(sendBatchSmsRequest, aliCloudProperties.getAccessKey(), - aliCloudProperties.getSecretKey()); - } - - /** - * - * @param sendBatchSmsRequest - * @param accessKeyId - * @param accessKeySecret - * @throws ClientException - * @return SendBatchSmsResponse - */ - @Override - public SendBatchSmsResponse sendSmsBatchRequest( - SendBatchSmsRequest sendBatchSmsRequest, String accessKeyId, - String accessKeySecret) throws ClientException { - EndpointManager.addSendBatchSmsRequest(sendBatchSmsRequest); - return getHangZhouRegionClientProfile(accessKeyId, accessKeySecret) - .getAcsResponse(sendBatchSmsRequest); - } - - /** - * - * @param request - * @param accessKeyId - * @param accessKeySecret - * @throws ClientException - * @return QuerySendDetailsResponse - */ - @Override - public QuerySendDetailsResponse querySendDetails(QuerySendDetailsRequest request, - String accessKeyId, String accessKeySecret) throws ClientException { - return getHangZhouRegionClientProfile(accessKeyId, accessKeySecret) - .getAcsResponse(request); - } - - /** - * - * @param request - * @throws ClientException - * @return QuerySendDetailsResponse - */ - @Override - public QuerySendDetailsResponse querySendDetails(QuerySendDetailsRequest request) - throws ClientException { - return querySendDetails(request, aliCloudProperties.getAccessKey(), - aliCloudProperties.getSecretKey()); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsUpMessageListener.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsUpMessageListener.java deleted file mode 100644 index 9e4e8124..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/SmsUpMessageListener.java +++ /dev/null @@ -1,22 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms; - -/** - * @author pbting - */ -public interface SmsUpMessageListener extends SmsMessageListener { -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/DefaultAlicomMessagePuller.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/DefaultAlicomMessagePuller.java deleted file mode 100755 index 3a8cb837..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/DefaultAlicomMessagePuller.java +++ /dev/null @@ -1,430 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.Date; -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.ScheduledExecutorService; -import java.util.concurrent.ScheduledThreadPoolExecutor; - -import com.aliyun.mns.client.CloudQueue; -import com.aliyun.mns.common.ClientException; -import com.aliyun.mns.common.ServiceException; -import com.aliyun.mns.model.Message; -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 阿里通信官方消息默认拉取工具类 - */ -public class DefaultAlicomMessagePuller { - - private static final Logger log = LoggerFactory - .getLogger(DefaultAlicomMessagePuller.class); - - private String mnsAccountEndpoint = "https://1943695596114318.mns.cn-hangzhou.aliyuncs.com/";// 阿里通信消息的endpoint,固定。 - private String endpointNameForPop = "cn-hangzhou"; - private String regionIdForPop = "cn-hangzhou"; - private String domainForPop = "dybaseapi.aliyuncs.com"; - private TokenGetterForAlicom tokenGetter; - private MessageListener messageListener; - private boolean isRunning = false; - private Integer pullMsgThreadSize = 1; - private boolean debugLogOpen = false; - private Integer sleepSecondWhenNoData = 30; - - public void openDebugLog(boolean debugLogOpen) { - this.debugLogOpen = debugLogOpen; - } - - public Integer getSleepSecondWhenNoData() { - return sleepSecondWhenNoData; - } - - public void setSleepSecondWhenNoData(Integer sleepSecondWhenNoData) { - this.sleepSecondWhenNoData = sleepSecondWhenNoData; - } - - public Integer getPullMsgThreadSize() { - return pullMsgThreadSize; - } - - public void setPullMsgThreadSize(Integer pullMsgThreadSize) { - if (pullMsgThreadSize != null && pullMsgThreadSize > 1) { - this.pullMsgThreadSize = pullMsgThreadSize; - } - } - - private ExecutorService executorService; - - public ExecutorService getExecutorService() { - return executorService; - } - - public void setExecutorService(ExecutorService executorService) { - this.executorService = executorService; - } - - protected static final Map S_LOCK_OBJ_MAP = new HashMap<>(); - protected static Map sPollingMap = new ConcurrentHashMap<>(); - protected Object lockObj; - - public boolean setPolling(String queueName) { - synchronized (lockObj) { - Boolean ret = sPollingMap.get(queueName); - if (ret == null || !ret) { - sPollingMap.put(queueName, true); - return true; - } - return false; - } - } - - public void clearPolling(String queueName) { - synchronized (lockObj) { - sPollingMap.put(queueName, false); - lockObj.notifyAll(); - if (debugLogOpen) { - log.info("PullMessageTask_WakeUp:Everyone WakeUp and Work!"); - } - } - } - - public boolean isRunning() { - return isRunning; - } - - public void setRunning(boolean running) { - isRunning = running; - } - - private class PullMessageTask implements Runnable { - private String messageType; - private String queueName; - - @Override - public void run() { - - boolean polling = false; - while (isRunning) { - try { - synchronized (lockObj) { - Boolean p = sPollingMap.get(queueName); - if (p != null && p) { - try { - if (debugLogOpen) { - log.info("PullMessageTask_sleep:" - + Thread.currentThread().getName() - + " Have a nice sleep!"); - } - polling = false; - lockObj.wait(); - } - catch (InterruptedException e) { - if (debugLogOpen) { - log.info("PullMessageTask_Interrupted!" - + Thread.currentThread().getName() - + " QueueName is " + queueName); - } - continue; - } - } - } - - TokenForAlicom tokenObject = tokenGetter.getTokenByMessageType( - messageType, queueName, mnsAccountEndpoint); - CloudQueue queue = tokenObject.getQueue(); - Message popMsg = null; - if (!polling) { - popMsg = queue.popMessage(); - if (debugLogOpen) { - SimpleDateFormat format = new SimpleDateFormat( - "yyyy-MM-dd HH:mm:ss"); - log.info("PullMessageTask_popMessage:" - + Thread.currentThread().getName() + "-popDone at " - + "," + format.format(new Date()) + " msgSize=" - + (popMsg == null ? 0 : popMsg.getMessageId())); - } - if (popMsg == null) { - polling = true; - continue; - } - } - else { - if (setPolling(queueName)) { - if (debugLogOpen) { - log.info("PullMessageTask_setPolling:" - + Thread.currentThread().getName() + " Polling!"); - } - } - else { - continue; - } - do { - if (debugLogOpen) { - log.info("PullMessageTask_Keep_Polling" - + Thread.currentThread().getName() - + "KEEP Polling!"); - } - try { - popMsg = queue.popMessage(sleepSecondWhenNoData); - } - catch (ClientException e) { - if (debugLogOpen) { - log.info( - "PullMessageTask_Pop_Message:ClientException Refresh accessKey" - + e); - } - tokenObject = tokenGetter.getTokenByMessageType( - messageType, queueName, mnsAccountEndpoint); - queue = tokenObject.getQueue(); - - } - catch (ServiceException e) { - if (debugLogOpen) { - log.info( - "PullMessageTask_Pop_Message:ServiceException Refresh accessKey" - + e); - } - tokenObject = tokenGetter.getTokenByMessageType( - messageType, queueName, mnsAccountEndpoint); - queue = tokenObject.getQueue(); - - } - catch (Exception e) { - if (debugLogOpen) { - log.info( - "PullMessageTask_Pop_Message:Exception Happened when polling popMessage: " - + e); - } - } - } - while (popMsg == null && isRunning); - clearPolling(queueName); - } - boolean dealResult = messageListener.dealMessage(popMsg); - if (dealResult) { - // remember to delete message when consume message successfully. - if (debugLogOpen) { - log.info("PullMessageTask_Deal_Message:" - + Thread.currentThread().getName() + "deleteMessage " - + popMsg.getMessageId()); - } - queue.deleteMessage(popMsg.getReceiptHandle()); - } - } - catch (ClientException e) { - log.error("PullMessageTask_execute_error,messageType:" + messageType - + ",queueName:" + queueName, e); - break; - - } - catch (ServiceException e) { - if (e.getErrorCode().equals("AccessDenied")) { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName - + ",please check messageType and queueName", e); - } - else { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName, e); - } - break; - - } - catch (com.aliyuncs.exceptions.ClientException e) { - if (e.getErrCode().equals("InvalidAccessKeyId.NotFound")) { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName - + ",please check AccessKeyId", e); - } - if (e.getErrCode().equals("SignatureDoesNotMatch")) { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName - + ",please check AccessKeySecret", e); - } - else { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName, e); - } - break; - - } - catch (Exception e) { - log.error("PullMessageTask_execute_error,messageType:" + messageType - + ",queueName:" + queueName, e); - try { - Thread.sleep(sleepSecondWhenNoData); - } - catch (InterruptedException e1) { - log.error("PullMessageTask_execute_error,messageType:" - + messageType + ",queueName:" + queueName, e); - } - } - } - - } - - } - - /** - * @param accessKeyId accessKeyId - * @param accessKeySecret accessKeySecret - * @param messageType 消息类型 - * @param queueName 队列名称 - * @param messageListener 回调的listener,用户自己实现 - * @throws com.aliyuncs.exceptions.ClientException - * @throws ParseException - */ - public void startReceiveMsg(String accessKeyId, String accessKeySecret, - String messageType, String queueName, MessageListener messageListener) - throws com.aliyuncs.exceptions.ClientException, ParseException { - - tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret, - endpointNameForPop, regionIdForPop, domainForPop, null); - - this.messageListener = messageListener; - isRunning = true; - PullMessageTask task = new PullMessageTask(); - task.messageType = messageType; - task.queueName = queueName; - - synchronized (S_LOCK_OBJ_MAP) { - lockObj = S_LOCK_OBJ_MAP.get(queueName); - if (lockObj == null) { - lockObj = new Object(); - S_LOCK_OBJ_MAP.put(queueName, lockObj); - } - } - - if (executorService == null) { - ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor( - pullMsgThreadSize, - new BasicThreadFactory.Builder() - .namingPattern( - "PullMessageTask-" + messageType + "-thread-pool-%d") - .daemon(true).build()); - executorService = scheduledExecutorService; - } - for (int i = 0; i < pullMsgThreadSize; i++) { - executorService.execute(task); - } - } - - /** - * @param accessKeyId accessKeyId - * @param accessKeySecret accessKeySecret - * @param messageType 消息类型 - * @param queueName 队列名称 - * @param messageListener 回调的listener,用户自己实现 - * @throws com.aliyuncs.exceptions.ClientException - * @throws ParseException - */ - public void startReceiveMsgForVPC(String accessKeyId, String accessKeySecret, - String messageType, String queueName, String regionIdForPop, - String endpointNameForPop, String domainForPop, String mnsAccountEndpoint, - MessageListener messageListener) - throws com.aliyuncs.exceptions.ClientException, ParseException { - this.mnsAccountEndpoint = mnsAccountEndpoint; - tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret, - endpointNameForPop, regionIdForPop, domainForPop, null); - - this.messageListener = messageListener; - isRunning = true; - PullMessageTask task = new PullMessageTask(); - task.messageType = messageType; - task.queueName = queueName; - - synchronized (S_LOCK_OBJ_MAP) { - lockObj = S_LOCK_OBJ_MAP.get(queueName); - if (lockObj == null) { - lockObj = new Object(); - S_LOCK_OBJ_MAP.put(queueName, lockObj); - } - } - - if (executorService == null) { - ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor( - pullMsgThreadSize, - new BasicThreadFactory.Builder() - .namingPattern( - "PullMessageTask-" + messageType + "-thread-pool-%d") - .daemon(true).build()); - executorService = scheduledExecutorService; - } - for (int i = 0; i < pullMsgThreadSize; i++) { - executorService.execute(task); - } - } - - /** - * 虚商用户定制接收消息方法 - * @param accessKeyId accessKeyId - * @param accessKeySecret accessKeySecret - * @param ownerId 实际的ownerId - * @param messageType 消息类型 - * @param queueName 队列名称 - * @param messageListener 回调listener - * @throws com.aliyuncs.exceptions.ClientException - * @throws ParseException - */ - public void startReceiveMsgForPartnerUser(String accessKeyId, String accessKeySecret, - Long ownerId, String messageType, String queueName, - MessageListener messageListener) - throws com.aliyuncs.exceptions.ClientException, ParseException { - - tokenGetter = new TokenGetterForAlicom(accessKeyId, accessKeySecret, - endpointNameForPop, regionIdForPop, domainForPop, ownerId); - - this.messageListener = messageListener; - isRunning = true; - PullMessageTask task = new PullMessageTask(); - task.messageType = messageType; - task.queueName = queueName; - - synchronized (S_LOCK_OBJ_MAP) { - lockObj = S_LOCK_OBJ_MAP.get(queueName); - if (lockObj == null) { - lockObj = new Object(); - S_LOCK_OBJ_MAP.put(queueName, lockObj); - } - } - - if (executorService == null) { - ScheduledExecutorService scheduledExecutorService = new ScheduledThreadPoolExecutor( - pullMsgThreadSize, - new BasicThreadFactory.Builder() - .namingPattern( - "PullMessageTask-" + messageType + "-thread-pool-%d") - .daemon(true).build()); - executorService = scheduledExecutorService; - } - for (int i = 0; i < pullMsgThreadSize; i++) { - executorService.execute(task); - } - } - - public void stop() { - isRunning = false; - } - -} diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/MessageListener.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/MessageListener.java deleted file mode 100755 index 9e857f2a..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/MessageListener.java +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import com.aliyun.mns.model.Message; - -public interface MessageListener { - - boolean dealMessage(Message message); - -} diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueRequest.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueRequest.java deleted file mode 100644 index e8214812..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueRequest.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import com.aliyuncs.RpcAcsRequest; - -public class QueryTokenForMnsQueueRequest - extends RpcAcsRequest { - private String resourceOwnerAccount; - private String messageType; - private Long resourceOwnerId; - private Long ownerId; - - public QueryTokenForMnsQueueRequest() { - super("Dybaseapi", "2017-05-25", "QueryTokenForMnsQueue"); - } - - public String getResourceOwnerAccount() { - return this.resourceOwnerAccount; - } - - public void setResourceOwnerAccount(String resourceOwnerAccount) { - this.resourceOwnerAccount = resourceOwnerAccount; - if (resourceOwnerAccount != null) { - this.putQueryParameter("ResourceOwnerAccount", resourceOwnerAccount); - } - - } - - public String getMessageType() { - return this.messageType; - } - - public void setMessageType(String messageType) { - this.messageType = messageType; - if (messageType != null) { - this.putQueryParameter("MessageType", messageType); - } - - } - - public Long getResourceOwnerId() { - return this.resourceOwnerId; - } - - public void setResourceOwnerId(Long resourceOwnerId) { - this.resourceOwnerId = resourceOwnerId; - if (resourceOwnerId != null) { - this.putQueryParameter("ResourceOwnerId", resourceOwnerId.toString()); - } - - } - - public Long getOwnerId() { - return this.ownerId; - } - - public void setOwnerId(Long ownerId) { - this.ownerId = ownerId; - if (ownerId != null) { - this.putQueryParameter("OwnerId", ownerId.toString()); - } - - } - - @Override - public Class getResponseClass() { - return QueryTokenForMnsQueueResponse.class; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponse.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponse.java deleted file mode 100644 index 724804e8..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponse.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import com.aliyuncs.AcsResponse; -import com.aliyuncs.transform.UnmarshallerContext; - -public class QueryTokenForMnsQueueResponse extends AcsResponse { - private String requestId; - private String code; - private String message; - private QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO; - - public QueryTokenForMnsQueueResponse() { - } - - public String getRequestId() { - return this.requestId; - } - - public void setRequestId(String requestId) { - this.requestId = requestId; - } - - public String getCode() { - return this.code; - } - - public void setCode(String code) { - this.code = code; - } - - public String getMessage() { - return this.message; - } - - public void setMessage(String message) { - this.message = message; - } - - public QueryTokenForMnsQueueResponse.MessageTokenDTO getMessageTokenDTO() { - return this.messageTokenDTO; - } - - public void setMessageTokenDTO( - QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO) { - this.messageTokenDTO = messageTokenDTO; - } - - @Override - public QueryTokenForMnsQueueResponse getInstance(UnmarshallerContext context) { - return QueryTokenForMnsQueueResponseUnmarshaller.unmarshall(this, context); - } - - public static class MessageTokenDTO { - private String accessKeyId; - private String accessKeySecret; - private String securityToken; - private String createTime; - private String expireTime; - - public MessageTokenDTO() { - } - - public String getAccessKeyId() { - return this.accessKeyId; - } - - public void setAccessKeyId(String accessKeyId) { - this.accessKeyId = accessKeyId; - } - - public String getAccessKeySecret() { - return this.accessKeySecret; - } - - public void setAccessKeySecret(String accessKeySecret) { - this.accessKeySecret = accessKeySecret; - } - - public String getSecurityToken() { - return this.securityToken; - } - - public void setSecurityToken(String securityToken) { - this.securityToken = securityToken; - } - - public String getCreateTime() { - return this.createTime; - } - - public void setCreateTime(String createTime) { - this.createTime = createTime; - } - - public String getExpireTime() { - return this.expireTime; - } - - public void setExpireTime(String expireTime) { - this.expireTime = expireTime; - } - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponseUnmarshaller.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponseUnmarshaller.java deleted file mode 100644 index 87c58c28..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/QueryTokenForMnsQueueResponseUnmarshaller.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import com.aliyuncs.transform.UnmarshallerContext; - -public class QueryTokenForMnsQueueResponseUnmarshaller { - - public QueryTokenForMnsQueueResponseUnmarshaller() { - } - - public static QueryTokenForMnsQueueResponse unmarshall( - QueryTokenForMnsQueueResponse queryTokenForMnsQueueResponse, - UnmarshallerContext context) { - queryTokenForMnsQueueResponse.setRequestId( - context.stringValue("QueryTokenForMnsQueueResponse.RequestId")); - queryTokenForMnsQueueResponse - .setCode(context.stringValue("QueryTokenForMnsQueueResponse.Code")); - queryTokenForMnsQueueResponse - .setMessage(context.stringValue("QueryTokenForMnsQueueResponse.Message")); - QueryTokenForMnsQueueResponse.MessageTokenDTO messageTokenDTO = new QueryTokenForMnsQueueResponse.MessageTokenDTO(); - messageTokenDTO.setAccessKeyId(context.stringValue( - "QueryTokenForMnsQueueResponse.MessageTokenDTO.AccessKeyId")); - messageTokenDTO.setAccessKeySecret(context.stringValue( - "QueryTokenForMnsQueueResponse.MessageTokenDTO.AccessKeySecret")); - messageTokenDTO.setSecurityToken(context.stringValue( - "QueryTokenForMnsQueueResponse.MessageTokenDTO.SecurityToken")); - messageTokenDTO.setCreateTime(context - .stringValue("QueryTokenForMnsQueueResponse.MessageTokenDTO.CreateTime")); - messageTokenDTO.setExpireTime(context - .stringValue("QueryTokenForMnsQueueResponse.MessageTokenDTO.ExpireTime")); - queryTokenForMnsQueueResponse.setMessageTokenDTO(messageTokenDTO); - return queryTokenForMnsQueueResponse; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenForAlicom.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenForAlicom.java deleted file mode 100755 index 443e8517..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenForAlicom.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import com.aliyun.mns.client.CloudQueue; -import com.aliyun.mns.client.MNSClient; - -/** - * 用于接收云通信消息的临时token - * - */ -public class TokenForAlicom { - private String messageType; - private String token; - private Long expireTime; - private String tempAccessKeyId; - private String tempAccessKeySecret; - private MNSClient client; - private CloudQueue queue; - - public String getMessageType() { - return messageType; - } - - public void setMessageType(String messageType) { - this.messageType = messageType; - } - - public String getToken() { - return token; - } - - public void setToken(String token) { - this.token = token; - } - - public Long getExpireTime() { - return expireTime; - } - - public void setExpireTime(Long expireTime) { - this.expireTime = expireTime; - } - - public String getTempAccessKeyId() { - return tempAccessKeyId; - } - - public void setTempAccessKeyId(String tempAccessKeyId) { - this.tempAccessKeyId = tempAccessKeyId; - } - - public String getTempAccessKeySecret() { - return tempAccessKeySecret; - } - - public void setTempAccessKeySecret(String tempAccessKeySecret) { - this.tempAccessKeySecret = tempAccessKeySecret; - } - - public MNSClient getClient() { - return client; - } - - public void setClient(MNSClient client) { - this.client = client; - } - - public CloudQueue getQueue() { - return queue; - } - - public void setQueue(CloudQueue queue) { - this.queue = queue; - } - - public void closeClient() { - if (client != null) { - this.client.close(); - } - } - -} diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenGetterForAlicom.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenGetterForAlicom.java deleted file mode 100755 index 0c0fd984..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/base/TokenGetterForAlicom.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.base; - -import java.text.ParseException; -import java.text.SimpleDateFormat; -import java.util.TimeZone; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentMap; - -import com.aliyun.mns.client.CloudAccount; -import com.aliyun.mns.client.CloudQueue; -import com.aliyun.mns.client.MNSClient; -import com.aliyuncs.DefaultAcsClient; -import com.aliyuncs.IAcsClient; -import com.aliyuncs.exceptions.ClientException; -import com.aliyuncs.exceptions.ServerException; -import com.aliyuncs.http.FormatType; -import com.aliyuncs.http.MethodType; -import com.aliyuncs.http.ProtocolType; -import com.aliyuncs.profile.DefaultProfile; -import com.aliyuncs.profile.IClientProfile; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * 获取接收云通信消息的临时token - * - */ -public class TokenGetterForAlicom { - private static final Logger log = LoggerFactory.getLogger(TokenGetterForAlicom.class); - private String accessKeyId; - private String accessKeySecret; - private String endpointNameForPop; - private String regionIdForPop; - private String domainForPop; - private IAcsClient iAcsClient; - private Long ownerId; - private final static String PRODUCT_NAME = "Dybaseapi"; - private long bufferTime = 1000 * 60 * 2;// 过期时间小于2分钟则重新获取,防止服务器时间误差 - private final Object lock = new Object(); - private ConcurrentMap tokenMap = new ConcurrentHashMap(); - - public TokenGetterForAlicom(String accessKeyId, String accessKeySecret, - String endpointNameForPop, String regionIdForPop, String domainForPop, - Long ownerId) throws ClientException { - this.accessKeyId = accessKeyId; - this.accessKeySecret = accessKeySecret; - this.endpointNameForPop = endpointNameForPop; - this.regionIdForPop = regionIdForPop; - this.domainForPop = domainForPop; - this.ownerId = ownerId; - init(); - } - - private void init() throws ClientException { - DefaultProfile.addEndpoint(endpointNameForPop, regionIdForPop, PRODUCT_NAME, - domainForPop); - IClientProfile profile = DefaultProfile.getProfile(regionIdForPop, accessKeyId, - accessKeySecret); - profile.getHttpClientConfig().setCompatibleMode(true); - iAcsClient = new DefaultAcsClient(profile); - } - - private TokenForAlicom getTokenFromRemote(String messageType) - throws ServerException, ClientException, ParseException { - SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - df.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai")); - QueryTokenForMnsQueueRequest request = new QueryTokenForMnsQueueRequest(); - request.setAcceptFormat(FormatType.JSON); - request.setMessageType(messageType); - request.setOwnerId(ownerId); - request.setProtocol(ProtocolType.HTTPS); - request.setMethod(MethodType.POST); - QueryTokenForMnsQueueResponse response = iAcsClient.getAcsResponse(request); - String resultCode = response.getCode(); - if (resultCode != null && "OK".equals(resultCode)) { - QueryTokenForMnsQueueResponse.MessageTokenDTO dto = response - .getMessageTokenDTO(); - TokenForAlicom token = new TokenForAlicom(); - String timeStr = dto.getExpireTime(); - token.setMessageType(messageType); - token.setExpireTime(df.parse(timeStr).getTime()); - token.setToken(dto.getSecurityToken()); - token.setTempAccessKeyId(dto.getAccessKeyId()); - token.setTempAccessKeySecret(dto.getAccessKeySecret()); - return token; - } - else { - log.error("getTokenFromRemote_error,messageType:" + messageType + ",code:" - + response.getCode() + ",message:" + response.getMessage()); - throw new ServerException(response.getCode(), response.getMessage()); - } - } - - public TokenForAlicom getTokenByMessageType(String messageType, String queueName, - String mnsAccountEndpoint) - throws ServerException, ClientException, ParseException { - TokenForAlicom token = tokenMap.get(messageType); - Long now = System.currentTimeMillis(); - if (token == null || (token.getExpireTime() - now) < bufferTime) {// 过期时间小于2分钟则重新获取,防止服务器时间误差 - synchronized (lock) { - token = tokenMap.get(messageType); - if (token == null || (token.getExpireTime() - now) < bufferTime) { - TokenForAlicom oldToken = null; - if (token != null) { - oldToken = token; - } - token = getTokenFromRemote(messageType); - // 因为换token时需要重建client和关闭老的client,所以创建client的代码和创建token放在一起 - CloudAccount account = new CloudAccount(token.getTempAccessKeyId(), - token.getTempAccessKeySecret(), mnsAccountEndpoint, - token.getToken()); - MNSClient client = account.getMNSClient(); - CloudQueue queue = client.getQueueRef(queueName); - token.setClient(client); - token.setQueue(queue); - tokenMap.put(messageType, token); - if (oldToken != null) { - oldToken.closeClient(); - } - } - } - } - return token; - } -} diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/config/SmsAutoConfiguration.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/config/SmsAutoConfiguration.java deleted file mode 100644 index c71e7b90..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/config/SmsAutoConfiguration.java +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.config; - -import com.alibaba.alicloud.context.AliCloudProperties; -import com.alibaba.alicloud.context.sms.SmsProperties; -import com.alibaba.alicloud.sms.ISmsService; -import com.alibaba.alicloud.sms.SmsInitializerEventListener; -import com.alibaba.alicloud.sms.SmsServiceImpl; - -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; - -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - -/** - * @author pbting - */ -@Configuration -@EnableConfigurationProperties -@ConditionalOnClass(value = SendSmsRequest.class) -@ConditionalOnProperty(value = "spring.cloud.alicloud.sms.enable", matchIfMissing = true) -public class SmsAutoConfiguration { - - @Bean - public SmsServiceImpl smsService(AliCloudProperties aliCloudProperties, - SmsProperties smsProperties) { - return new SmsServiceImpl(aliCloudProperties, smsProperties); - } - - @Bean - public SmsInitializerEventListener smsInitializePostListener( - SmsProperties smsProperties, ISmsService smsService) { - return new SmsInitializerEventListener(smsProperties, smsService); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/EndpointManager.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/EndpointManager.java deleted file mode 100644 index 79354f24..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/EndpointManager.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.endpoint; - -import java.util.HashMap; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.locks.ReentrantLock; - -import com.aliyuncs.dysmsapi.model.v20170525.SendBatchSmsRequest; -import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest; - -/** - * - */ -public final class EndpointManager { - - private final static int BACKLOG_SIZE = 20; - - private final static ReentrantLock SEND_REENTRANT_LOCK = new ReentrantLock(true); - private final static ReentrantLock SEND_BATCH_REENTRANT_LOCK = new ReentrantLock( - true); - - private final static LinkedBlockingQueue SEND_SMS_REQUESTS = new LinkedBlockingQueue( - BACKLOG_SIZE); - private final static LinkedBlockingQueue SEND_BATCH_SMS_REQUESTS = new LinkedBlockingQueue( - BACKLOG_SIZE); - private final static LinkedBlockingQueue RECEIVE_MESSAGE_ENTITIES = new LinkedBlockingQueue( - BACKLOG_SIZE); - - public static void addSendSmsRequest(SendSmsRequest sendSmsRequest) { - if (SEND_SMS_REQUESTS.offer(sendSmsRequest)) { - return; - } - try { - SEND_REENTRANT_LOCK.lock(); - SEND_SMS_REQUESTS.poll(); - SEND_SMS_REQUESTS.offer(sendSmsRequest); - } - finally { - SEND_REENTRANT_LOCK.unlock(); - } - } - - public static void addSendBatchSmsRequest(SendBatchSmsRequest sendBatchSmsRequest) { - if (SEND_BATCH_SMS_REQUESTS.offer(sendBatchSmsRequest)) { - return; - } - try { - SEND_BATCH_REENTRANT_LOCK.lock(); - SEND_BATCH_SMS_REQUESTS.poll(); - SEND_BATCH_SMS_REQUESTS.offer(sendBatchSmsRequest); - } - finally { - SEND_BATCH_REENTRANT_LOCK.unlock(); - } - } - - public static void addReceiveMessageEntity( - ReceiveMessageEntity receiveMessageEntity) { - if (RECEIVE_MESSAGE_ENTITIES.offer(receiveMessageEntity)) { - return; - } - RECEIVE_MESSAGE_ENTITIES.poll(); - RECEIVE_MESSAGE_ENTITIES.offer(receiveMessageEntity); - } - - public static Map getSmsEndpointMessage() { - List sendSmsRequests = new LinkedList<>(); - List sendBatchSmsRequests = new LinkedList<>(); - List receiveMessageEntities = new LinkedList<>(); - try { - SEND_REENTRANT_LOCK.lock(); - SEND_BATCH_REENTRANT_LOCK.lock(); - sendSmsRequests.addAll(SEND_SMS_REQUESTS); - sendBatchSmsRequests.addAll(SEND_BATCH_SMS_REQUESTS); - } - finally { - SEND_REENTRANT_LOCK.unlock(); - SEND_BATCH_REENTRANT_LOCK.unlock(); - } - receiveMessageEntities.addAll(RECEIVE_MESSAGE_ENTITIES); - - Map endpointMessages = new HashMap<>(); - endpointMessages.put("send-sms-request", sendSmsRequests); - endpointMessages.put("send-batch-sms-request", sendBatchSmsRequests); - endpointMessages.put("message-listener", receiveMessageEntities); - - return endpointMessages; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/ReceiveMessageEntity.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/ReceiveMessageEntity.java deleted file mode 100644 index 685fbe97..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/ReceiveMessageEntity.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.endpoint; - -import java.io.Serializable; - -import com.alibaba.alicloud.sms.base.MessageListener; - -/** - * @author pbting - */ -public class ReceiveMessageEntity implements Serializable { - private String messageType; - private String queueName; - private MessageListener messageListener; - - public ReceiveMessageEntity(String messageType, String queueName, - MessageListener messageListener) { - this.messageType = messageType; - this.queueName = queueName; - this.messageListener = messageListener; - } - - public String getMessageType() { - return messageType; - } - - public void setMessageType(String messageType) { - this.messageType = messageType; - } - - public String getQueueName() { - return queueName; - } - - public void setQueueName(String queueName) { - this.queueName = queueName; - } - - public MessageListener getMessageListener() { - return messageListener; - } - - public void setMessageListener(MessageListener messageListener) { - this.messageListener = messageListener; - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpoint.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpoint.java deleted file mode 100644 index 57da7bd5..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpoint.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.endpoint; - -import java.util.Map; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - -@Endpoint(id = "sms") -public class SmsEndpoint { - - @ReadOperation - public Map invoke() { - - return EndpointManager.getSmsEndpointMessage(); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpointAutoConfiguration.java b/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpointAutoConfiguration.java deleted file mode 100644 index cf8a6bb7..00000000 --- a/spring-cloud-alicloud-sms/src/main/java/com/alibaba/alicloud/sms/endpoint/SmsEndpointAutoConfiguration.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Copyright (C) 2019 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package com.alibaba.alicloud.sms.endpoint; - -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; -import org.springframework.context.annotation.Bean; - -@ConditionalOnWebApplication -@ConditionalOnClass(Endpoint.class) -public class SmsEndpointAutoConfiguration { - - @Bean - public SmsEndpoint smsEndpoint() { - return new SmsEndpoint(); - } -} \ No newline at end of file diff --git a/spring-cloud-alicloud-sms/src/main/resources/META-INF/spring.factories b/spring-cloud-alicloud-sms/src/main/resources/META-INF/spring.factories deleted file mode 100644 index a6c328d2..00000000 --- a/spring-cloud-alicloud-sms/src/main/resources/META-INF/spring.factories +++ /dev/null @@ -1,3 +0,0 @@ -org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ - com.alibaba.alicloud.sms.config.SmsAutoConfiguration,\ - com.alibaba.alicloud.sms.endpoint.SmsEndpointAutoConfiguration \ No newline at end of file diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config-server/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config-server/pom.xml deleted file mode 100644 index 0ed8761b..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config-server/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alibaba-nacos-config-server - Spring Cloud Starter Alibaba Nacos Config Server - - - - com.alibaba.cloud - spring-cloud-alibaba-nacos-config - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config/pom.xml deleted file mode 100644 index ef7f4e6e..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-config/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alibaba-nacos-config - Spring Cloud Starter Alibaba Nacos Config - - - - com.alibaba.cloud - spring-cloud-alibaba-nacos-config - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-discovery/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-discovery/pom.xml deleted file mode 100644 index 56e1254c..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-nacos-discovery/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alibaba-nacos-discovery - Spring Cloud Starter Alibaba Nacos Discovery - - - - com.alibaba.cloud - spring-cloud-alibaba-nacos-discovery - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-seata/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-seata/pom.xml deleted file mode 100644 index bcd023be..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-seata/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alibaba-seata - Spring Cloud Starter Alibaba Seata - - - - com.alibaba.cloud - spring-cloud-alibaba-seata - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sentinel/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sentinel/pom.xml deleted file mode 100644 index 1736ec06..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sentinel/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alibaba-sentinel - Spring Cloud Starter Alibaba Sentinel - - - - com.alibaba.cloud - spring-cloud-alibaba-sentinel - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sidecar/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sidecar/pom.xml deleted file mode 100644 index 9fa50ef4..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sidecar/pom.xml +++ /dev/null @@ -1,22 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - ../pom.xml - - 4.0.0 - - spring-cloud-starter-alibaba-sidecar - Spring Cloud Starter Alibaba Sidecar - - - - com.alibaba.cloud - spring-cloud-alibaba-sidecar - - - diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-dubbo/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-dubbo/pom.xml deleted file mode 100644 index 1f56ce1a..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-dubbo/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - ../pom.xml - - 4.0.0 - - spring-cloud-starter-dubbo - Spring Cloud Starter Dubbo - - - - ${project.groupId} - spring-cloud-alibaba-dubbo - ${project.version} - - - org.springframework.boot - spring-boot-starter - - - - \ No newline at end of file diff --git a/spring-cloud-starter-alibaba/spring-cloud-starter-stream-rocketmq/pom.xml b/spring-cloud-starter-alibaba/spring-cloud-starter-stream-rocketmq/pom.xml deleted file mode 100644 index 30d84a0f..00000000 --- a/spring-cloud-starter-alibaba/spring-cloud-starter-stream-rocketmq/pom.xml +++ /dev/null @@ -1,21 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alibaba - 2.0.1.RELEASE - ../pom.xml - - spring-cloud-starter-stream-rocketmq - Spring Cloud Starter Stream RocketMQ - - - - com.alibaba.cloud - spring-cloud-stream-binder-rocketmq - - - - diff --git a/spring-cloud-starter-alicloud/pom.xml b/spring-cloud-starter-alicloud/pom.xml deleted file mode 100644 index 715ac450..00000000 --- a/spring-cloud-starter-alicloud/pom.xml +++ /dev/null @@ -1,20 +0,0 @@ - - 4.0.0 - - com.alibaba.cloud - spring-cloud-alibaba - 2.0.1.RELEASE - - spring-cloud-starter-alicloud - pom - Spring Cloud Alibaba Cloud Starters - Spring Cloud Alibaba Cloud Starters - - spring-cloud-starter-alicloud-oss - spring-cloud-starter-alicloud-acm - spring-cloud-starter-alicloud-ans - spring-cloud-starter-alicloud-schedulerx - spring-cloud-starter-alicloud-sms - - \ No newline at end of file diff --git a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-acm/pom.xml b/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-acm/pom.xml deleted file mode 100644 index 46c27224..00000000 --- a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-acm/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alicloud - 2.0.1.RELEASE - - spring-cloud-starter-alicloud-acm - Spring Cloud Starter Alibaba Cloud ACM - - - - com.alibaba.cloud - spring-cloud-alicloud-acm - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-ans/pom.xml b/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-ans/pom.xml deleted file mode 100644 index 6dfa167f..00000000 --- a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-ans/pom.xml +++ /dev/null @@ -1,25 +0,0 @@ - - - 4.0.0 - - com.alibaba.cloud - spring-cloud-starter-alicloud - 2.0.1.RELEASE - - - spring-cloud-starter-alicloud-ans - Spring Cloud Starter Alibaba Cloud ANS - - - - com.alibaba.cloud - spring-cloud-alicloud-ans - - - org.springframework.boot - spring-boot-starter - - - - \ No newline at end of file diff --git a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-oss/pom.xml b/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-oss/pom.xml deleted file mode 100644 index d0f42da0..00000000 --- a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-oss/pom.xml +++ /dev/null @@ -1,28 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alicloud - 2.0.1.RELEASE - - spring-cloud-starter-alicloud-oss - Spring Cloud Starter Alibaba Cloud OSS - - - - com.alibaba.cloud - spring-cloud-alicloud-oss - - - com.aliyun.oss - aliyun-sdk-oss - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-schedulerx/pom.xml b/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-schedulerx/pom.xml deleted file mode 100644 index 40dc8710..00000000 --- a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-schedulerx/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alicloud - 2.0.1.RELEASE - - spring-cloud-starter-alicloud-schedulerx - Spring Cloud Starter Alibaba Cloud SchedulerX - - - - com.alibaba.cloud - spring-cloud-alicloud-schedulerx - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-sms/pom.xml b/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-sms/pom.xml deleted file mode 100644 index 3ae12229..00000000 --- a/spring-cloud-starter-alicloud/spring-cloud-starter-alicloud-sms/pom.xml +++ /dev/null @@ -1,24 +0,0 @@ - - 4.0.0 - - - com.alibaba.cloud - spring-cloud-starter-alicloud - 2.0.1.RELEASE - - spring-cloud-starter-alicloud-sms - Spring Cloud Starter Alibaba Cloud SMS - - - - com.alibaba.cloud - spring-cloud-alicloud-sms - - - org.springframework.boot - spring-boot-starter - - - - diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java deleted file mode 100644 index 16a3f76f..00000000 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQExtendedBindingProperties.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright (C) 2018 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -package com.alibaba.cloud.stream.binder.rocketmq.properties; - -import java.util.HashMap; -import java.util.Map; - -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.cloud.stream.binder.ExtendedBindingProperties; - -/** - * @author Timur Valiev - * @author Jim - */ -@ConfigurationProperties("spring.cloud.stream.rocketmq") -public class RocketMQExtendedBindingProperties implements - ExtendedBindingProperties { - - private Map bindings = new HashMap<>(); - - public Map getBindings() { - return this.bindings; - } - - public void setBindings(Map bindings) { - this.bindings = bindings; - } - - @Override - public synchronized RocketMQConsumerProperties getExtendedConsumerProperties( - String channelName) { - if (bindings.containsKey(channelName)) { - if (bindings.get(channelName).getConsumer() != null) { - return bindings.get(channelName).getConsumer(); - } - else { - RocketMQConsumerProperties properties = new RocketMQConsumerProperties(); - this.bindings.get(channelName).setConsumer(properties); - return properties; - } - } - else { - RocketMQConsumerProperties properties = new RocketMQConsumerProperties(); - RocketMQBindingProperties rbp = new RocketMQBindingProperties(); - rbp.setConsumer(properties); - bindings.put(channelName, rbp); - return properties; - } - } - - @Override - public synchronized RocketMQProducerProperties getExtendedProducerProperties( - String channelName) { - if (bindings.containsKey(channelName)) { - if (bindings.get(channelName).getProducer() != null) { - return bindings.get(channelName).getProducer(); - } - else { - RocketMQProducerProperties properties = new RocketMQProducerProperties(); - this.bindings.get(channelName).setProducer(properties); - return properties; - } - } - else { - RocketMQProducerProperties properties = new RocketMQProducerProperties(); - RocketMQBindingProperties rbp = new RocketMQBindingProperties(); - rbp.setProducer(properties); - bindings.put(channelName, rbp); - return properties; - } - } -}