diff --git a/README-zh.md b/README-zh.md index c70ea7fa..c4f7dd96 100644 --- a/README-zh.md +++ b/README-zh.md @@ -1,21 +1,21 @@ # Spring Cloud Alibaba [![CircleCI](https://circleci.com/gh/alibaba/spring-cloud-alibaba/tree/master.svg?style=svg)](https://circleci.com/gh/alibaba/spring-cloud-alibaba/tree/master) -[![Maven Central](https://img.shields.io/maven-central/v/org.springframework.cloud/spring-cloud-alibaba-dependencies.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:org.springframework.cloud%20AND%20a:spring-cloud-alibaba-dependencies) -[![Codecov](https://codecov.io/gh/spring-cloud-incubator/spring-cloud-alibaba/branch/master/graph/badge.svg)](https://codecov.io/gh/spring-cloud-incubator/spring-cloud-alibaba) +[![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.cloud/spring-cloud-alibaba-dependencies.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:com.alibaba.cloud%20AND%20a:spring-cloud-alibaba-dependencies) +[![Codecov](https://codecov.io/gh/alibaba/spring-cloud-alibaba/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/spring-cloud-alibaba) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用微服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。 依托 Spring Cloud Alibaba,您只需要添加一些注解和少量配置,就可以将 Spring Cloud 应用接入阿里微服务解决方案,通过阿里中间件来迅速搭建分布式应用系统。 -参考文档 请查看 [WIKI](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/wiki) 。 +参考文档 请查看 [WIKI](https://github.com/alibaba/spring-cloud-alibaba/wiki) 。 -为 Spring Cloud Alibaba 贡献代码请参考 [如何贡献](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/wiki/%E5%A6%82%E4%BD%95%E8%B4%A1%E7%8C%AE%E4%BB%A3%E7%A0%81) 。 +为 Spring Cloud Alibaba 贡献代码请参考 [如何贡献](https://github.com/alibaba/spring-cloud-alibaba/wiki/%E5%A6%82%E4%BD%95%E8%B4%A1%E7%8C%AE%E4%BB%A3%E7%A0%81) 。 ## 主要功能 -* **服务限流降级**:默认支持 Servlet、Feign、RestTemplate、Dubbo 和 RocketMQ 限流降级功能的接入,可以在运行时通过控制台实时修改限流降级规则,还支持查看限流降级 Metrics 监控。 +* **服务限流降级**:默认支持 WebServlet、WebFlux, OpenFeign、RestTemplate、Spring Cloud Gateway, Zuul, Dubbo 和 RocketMQ 限流降级功能的接入,可以在运行时通过控制台实时修改限流降级规则,还支持查看限流降级 Metrics 监控。 * **服务注册与发现**:适配 Spring Cloud 服务注册与发现标准,默认集成了 Ribbon 的支持。 * **分布式配置管理**:支持分布式系统中的外部化配置,配置更改时自动刷新。 * **消息驱动能力**:基于 Spring Cloud Stream 为微服务应用构建消息驱动能力。 @@ -25,7 +25,7 @@ Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。 * **阿里云短信服务**:覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。 -更多功能请参考 [Roadmap](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。 +更多功能请参考 [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。 ## 组件 @@ -35,7 +35,7 @@ Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。 **[RocketMQ](https://rocketmq.apache.org/)**:一款开源的分布式消息系统,基于高可用分布式集群技术,提供低延时的、高可靠的消息发布与订阅服务。 -**[Dubbo](https://github.com/apache/incubator-dubbo)**:Apache Dubbo™ (incubating) 是一款高性能 Java RPC 框架。 +**[Dubbo](https://github.com/apache/dubbo)**:Apache Dubbo™ 是一款高性能 Java RPC 框架。 **[Seata](https://github.com/seata/seata)**:阿里巴巴开源产品,一个易于使用的高性能微服务分布式事务解决方案。 @@ -47,11 +47,12 @@ Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。 **[Alibaba Cloud SMS](https://www.aliyun.com/product/sms)**: 覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。 -更多组件请参考 [Roadmap](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。 +更多组件请参考 [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap-zh.md)。 ## 如何构建 -* master 分支对应的是 Spring Cloud Finchley,最低支持 JDK 1.8。 +* master 分支对应的是 Spring Cloud Greenwich,最低支持 JDK 1.8。 +* finchley 分支对应的是 Spring Cloud Finchley,最低支持 JDK 1.8。 * 1.x 分支对应的是 Spring Cloud Edgware,最低支持 JDK 1.7。 Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone 到本地,然后执行以下命令: @@ -63,7 +64,6 @@ Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone ## 如何使用 ### 如何引入依赖 -项目的最新版本是 0.2.1.RELEASE 和 0.1.1.RELEASE,版本 0.2.1.RELEASE 对应的是 Spring Cloud Finchley 版本,版本 0.1.1.RELEASE 对应的是 Spring Cloud Edgware 版本。 如果需要使用已发布的版本,在 `dependencyManagement` 中添加如下配置。 @@ -100,34 +100,33 @@ Spring Cloud 使用 Maven 来构建,最快的使用方式是将本项目 clone Example 列表: -[Sentinel Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md) +[Sentinel Example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme-zh.md) -[Nacos Config Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md) +[Nacos Config Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md) -[Nacos Discovery Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md) +[Nacos Discovery Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md) -[RocketMQ Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md) +[RocketMQ Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md) [Seata Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/seata-example/readme-zh.md) -[Alibaba Cloud OSS Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/oss-example/readme-zh.md) +[Alibaba Cloud OSS Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/oss-example/readme-zh.md) -[Alibaba Cloud ANS Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/ans-example/ans-provider-example/readme-zh.md) +[Alibaba Cloud ANS Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/ans-example/ans-provider-example/readme-zh.md) -[Alibaba Cloud ACM Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/acm-example/acm-local-example/readme-zh.md) +[Alibaba Cloud ACM Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/acm-example/acm-local-example/readme-zh.md) -[Alibaba Cloud SchedulerX Example](https://github.com/xiaolongzuo/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/readme-zh.md) +[Alibaba Cloud SchedulerX Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/schedulerx-example/schedulerx-simple-task-example/readme-zh.md) ## 版本管理规范 + 项目的版本号格式为 x.x.x 的形式,其中 x 的数值类型为数字,从 0 开始取值,且不限于 0~9 这个范围。项目处于孵化器阶段时,第一位版本号固定使用 0,即版本号为 0.x.x 的格式。 -由于 Spring Boot 1 和 Spring Boot 2 在 Actuator 模块的接口和注解有很大的变更,且 spring-cloud-commons 从 1.x.x 版本升级到 2.0.0 版本也有较大的变更,因此我们使用了两个不同分支来分别支持 Spring Boot 1 和 Spring Boot 2: -* 0.1.x 版本适用于 Spring Boot 1 -* 0.2.x 版本适用于 Spring Boot 2 - -项目孵化阶段,项目版本升级机制如下: -* 功能改动的升级会增加第三位版本号的数值,例如 0.1.0 的下一个版本为0.1.1。 +由于 Spring Boot 1 和 Spring Boot 2 在 Actuator 模块的接口和注解有很大的变更,且 spring-cloud-commons 从 1.x.x 版本升级到 2.0.0 版本也有较大的变更,因此我们采取跟 SpringBoot 版本号一致的版本: +* 1.5.x 版本适用于 Spring Boot 1.5.x +* 2.0.x 版本适用于 Spring Boot 2.0.x +* 2.1.x 版本适用于 Spring Boot 2.1.x ## 社区交流 @@ -138,4 +137,4 @@ spring-cloud-alibaba@googlegroups.com,欢迎通过此邮件列表讨论与 spr ### 钉钉群 -![DingQR](https://img.alicdn.com/tfs/TB1fr81ba61gK0jSZFlXXXDKFXa-892-1213.jpg) +![DingQR](https://img.alicdn.com/tfs/TB1zrRie4v1gK0jSZFFXXb0sXXa-7862-3570.png) diff --git a/README.md b/README.md index bf210a5a..6f69e3dc 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ # Spring Cloud Alibaba [![CircleCI](https://circleci.com/gh/alibaba/spring-cloud-alibaba/tree/master.svg?style=svg)](https://circleci.com/gh/alibaba/spring-cloud-alibaba/tree/master) -[![Maven Central](https://img.shields.io/maven-central/v/org.springframework.cloud/spring-cloud-alibaba-dependencies.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:org.springframework.cloud%20AND%20a:spring-cloud-alibaba-dependencies) -[![Codecov](https://codecov.io/gh/spring-cloud-incubator/spring-cloud-alibaba/branch/master/graph/badge.svg)](https://codecov.io/gh/spring-cloud-incubator/spring-cloud-alibaba) +[![Maven Central](https://img.shields.io/maven-central/v/com.alibaba.cloud/spring-cloud-alibaba-dependencies.svg?label=Maven%20Central)](https://search.maven.org/search?q=g:com.alibaba.cloud%20AND%20a:spring-cloud-alibaba-dependencies) +[![Codecov](https://codecov.io/gh/alibaba/spring-cloud-alibaba/branch/master/graph/badge.svg)](https://codecov.io/gh/alibaba/spring-cloud-alibaba) [![License](https://img.shields.io/badge/license-Apache%202-4EB1BA.svg)](https://www.apache.org/licenses/LICENSE-2.0.html) A project maintained by Alibaba. -See the [中文文档](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/README-zh.md) for Chinese readme. +See the [中文文档](https://github.com/alibaba/spring-cloud-alibaba/blob/master/README-zh.md) for Chinese readme. Spring Cloud Alibaba provides a one-stop solution for distributed application development. It contains all the components required to develop distributed applications, making it easy for you to develop your applications using Spring Cloud. @@ -25,7 +25,7 @@ With Spring Cloud Alibaba, you only need to add some annotations and a small amo * **Alibaba Cloud SchedulerX**:accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds. * **Alibaba Cloud SMS**: A messaging service that covers the globe, Alibaba SMS provides convenient, efficient, and intelligent communication capabilities that help businesses quickly contact their customers. -For more features, please refer to [Roadmap](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/Roadmap.md). +For more features, please refer to [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap.md). ## Components @@ -47,12 +47,13 @@ For more features, please refer to [Roadmap](https://github.com/spring-cloud-inc **[Alibaba Cloud SchedulerX](https://www.aliyun.com/product/SchedulerX)**:accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds.. -For more features please refer to [Roadmap](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/Roadmap.md). +For more features please refer to [Roadmap](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap.md). ## How to build -* **master branch**: Corresponds to Spring Boot 2.x. JDK 1.8 or later versions are supported. -* **1.x branch**: Corresponds to Spring Boot 1.x, JDK 1.7 or later versions are supported. +* **master branch**: Corresponds to Spring Cloud Greenwich & Spring Boot 2.x. JDK 1.8 or later versions are supported. +* **finchley branch**: Corresponds to Spring Cloud Finchley & Spring Boot 2.x. JDK 1.8 or later versions are supported. +* **1.x branch**: Corresponds to Spring Cloud Edgware & Spring Boot 1.x, JDK 1.7 or later versions are supported. Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing: @@ -61,8 +62,7 @@ Spring Cloud uses Maven for most build-related activities, and you should be abl ## How to Use -### Add maven dependency -Version 0.2.1.RELEASE is compatible with the Spring Cloud Finchley. Version 0.1.1.RELEASE is compatible with the Spring Cloud Edgware. +### Add maven dependency These artifacts are available from Maven Central and Spring Release repository via BOM: @@ -71,7 +71,7 @@ These artifacts are available from Maven Central and Spring Release repository v com.alibaba.cloud spring-cloud-alibaba-dependencies - 0.2.1.RELEASE + 2.1.0.RELEASE pom import @@ -80,29 +80,16 @@ These artifacts are available from Maven Central and Spring Release repository v add the module in `dependencies`. -If you want to use the latest BUILD-SNAPSHOT version, add `Spring Snapshot Repository` in pom.xml , **Attention: BUILD-SNAPSHOT may be updated in any time** - - - - spring-snapshot - Spring Snapshot Repository - https://repo.spring.io/snapshot - - true - - - - ### Reference Doc -[Contents](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc) +[Contents](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc) -[Nacos Config](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc) +[Nacos Config](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc) -[Nacos Discovery](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc) +[Nacos Discovery](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc) -[ACM](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc) +[ACM](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc) ## Examples @@ -111,26 +98,26 @@ A `spring-cloud-alibaba-examples` module is included in our project for you to g Examples: -[Sentinel Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md) +[Sentinel Example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example/readme.md) -[Nacos Config Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md) +[Nacos Config Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md) -[Nacos Discovery Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md) +[Nacos Discovery Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md) -[RocketMQ Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/rocketmq-example/readme.md) +[RocketMQ Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/rocketmq-example/readme.md) -[Alibaba Cloud OSS Example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/oss-example/readme.md) +[Alibaba Cloud OSS Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/oss-example/readme.md) + +[Duboo Spring Cloud Example](https://github.com/alibaba/spring-cloud-alibaba/blob/master/spring-cloud-alibaba-examples/spring-cloud-alibaba-dubbo-examples/README_CN.md) ## Version control guidelines The version number of the project is in the form of x.x.x, where x is a number, starting from 0, and is not limited to the range 0~9. When the project is in the incubator phase, the version number is 0.x.x. -As the interfaces and annotations of Spring Boot 1 and Spring Boot 2 have been changed significantly in the Actuator module, and spring-cloud-commons is also changed quite a lot from 1.x.x to 2.0.0, we maintain two different branches to support Spring Boot 1 and Spring Boot 2: -* 0.1.x for Spring Boot 1 -* 0.2.x for Spring Boot 2 - -During the incubation period, the version management of the project will follow these rules: -* Functional updates will be reflected in the 3rd number of the version, for example, the next version of 0.1.0 will be 0.1.1. +As the interfaces and annotations of Spring Boot 1 and Spring Boot 2 have been changed significantly in the Actuator module, and spring-cloud-commons is also changed quite a lot from 1.x.x to 2.0.0, we take the same version rule as SpringBoot version number. +* 1.5.x for Spring Boot 1.5.x +* 2.0.x for Spring Boot 2.0.x +* 2.1.x for Spring Boot 2.1.x ## Code of Conduct This project is a sub-project of Spring Cloud, it adheres to the Contributor Covenant [code of conduct](https://github.com/spring-cloud/spring-cloud-build/blob/master/docs/src/main/asciidoc/code-of-conduct.adoc). By participating, you are expected to uphold this code. Please report unacceptable behavior to spring-code-of-conduct@pivotal.io. diff --git a/Roadmap.md b/Roadmap.md index 32722c70..7d1f4118 100644 --- a/Roadmap.md +++ b/Roadmap.md @@ -1,6 +1,6 @@ # Roadmap -See the [中文文档](https://github.com/spring-cloud-incubator/spring-cloud-alibabacloud/blob/master/Roadmap-zh.md) for Chinese Roadmap. +See the [中文文档](https://github.com/alibaba/spring-cloud-alibaba/blob/master/Roadmap-zh.md) for Chinese Roadmap. Spring Cloud Alibaba provides a one-stop solution for distributed application development. It contains all the components required to develop distributed applications, making it easy for you to develop your applications using Spring Cloud. diff --git a/pom.xml b/pom.xml index d2546d57..164fc1d6 100644 --- a/pom.xml +++ b/pom.xml @@ -28,12 +28,12 @@ - https://github.com/spring-cloud-incubator/spring-cloud-alibaba + https://github.com/alibaba/spring-cloud-alibaba - scm:git:git://github.com/spring-cloud-incubator/spring-cloud-alibaba.git + scm:git:git://github.com/alibaba/spring-cloud-alibaba.git - scm:git:ssh://git@github.com/spring-cloud-incubator/spring-cloud-alibaba.git + scm:git:ssh://git@github.com/alibaba/spring-cloud-alibaba.git HEAD @@ -44,10 +44,8 @@ flystar32@163.com - Jim Fang + fangjian fangjian0423@gmail.com - Alibaba - https://github.com/fangjian0423 xiaolongzuo @@ -77,6 +75,7 @@ 2.0.4.RELEASE 2.0.2.RELEASE 2.0.4.RELEASE + 2.0.3.RELEASE 4.12 3.0 @@ -117,6 +116,7 @@ spring-cloud-alicloud-ans spring-cloud-alicloud-schedulerx spring-cloud-alicloud-sms + spring-cloud-alibaba-sidecar @@ -186,6 +186,14 @@ import + + org.springframework.cloud + spring-cloud-consul-dependencies + ${spring-cloud-consul.version} + pom + import + + org.apache.dubbo dubbo-spring-boot-starter diff --git a/spring-cloud-alibaba-dependencies/pom.xml b/spring-cloud-alibaba-dependencies/pom.xml index 967914f6..962e6d12 100644 --- a/spring-cloud-alibaba-dependencies/pom.xml +++ b/spring-cloud-alibaba-dependencies/pom.xml @@ -20,8 +20,8 @@ 1.6.3 3.1.0 - 0.7.1 - 1.1.1 + 0.9.0 + 1.1.4 0.8.0 1.0.9 1.0.1 @@ -173,11 +173,6 @@ sentinel-apache-dubbo-adapter ${sentinel.version} - - com.alibaba.cloud - sentinel-dubbo-api - ${project.version} - com.alibaba.csp sentinel-cluster-server-default @@ -199,8 +194,8 @@ ${sentinel.version} - + io.seata seata-all @@ -290,6 +285,11 @@ spring-cloud-alibaba-dubbo ${project.version} + + com.alibaba.cloud + spring-cloud-alibaba-sidecar + ${project.version} + @@ -356,6 +356,12 @@ ${project.version} + + com.alibaba.cloud + spring-cloud-starter-alibaba-sidecar + ${project.version} + + com.alibaba.cloud diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc index 7ae01717..f44c1a18 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc @@ -93,3 +93,4 @@ access-key 和 secret-key 则是阿里云账号的 AK/SK,需要首先注册阿 namespace 是阿里云 EDAS 产品的概念,用于隔离不同的环境,比如测试环境和生产环境。要获取 namespace 需要 https://common-buy.aliyun.com/?spm=5176.11451019.0.0.6f5965c0Uq5tue&commodityCode=edaspostpay#/buy[开通 EDAS 服务],按量计费模式下开通是免费的,开通以后进入 https://edas.console.aliyun.com/#/namespaces?regionNo=cn-hangzhou[EDAS控制台],即可看到对应的 namespace,比如 cn-hangzhou。 NOTE: EDAS 提供应用托管服务,如果你将应用托管到 EDAS,那么 EDAS 将会自动为你填充所有配置。 + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dependency-management.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dependency-management.adoc index e432667c..ed4f55f3 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dependency-management.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/dependency-management.adoc @@ -20,3 +20,4 @@ Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。 在下面的章节中,假设您使用的是 Spring Cloud Alibaba bom,相关 starter 依赖将不包含版本号。 + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/introduction.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/introduction.adoc index 06d53cc6..21bbd4d7 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/introduction.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/introduction.adoc @@ -1,4 +1,4 @@ -## 介绍 +== 介绍 Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。 diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc index 9f12c0f9..3457e2a8 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-discovery.adoc @@ -44,7 +44,7 @@ image::https://img.alicdn.com/tfs/TB1dyWJbQL0gK0jSZFtXXXQCXXa-2788-1086.png[] * pom.xml的配置。一个完整的 pom.xml 配置如下所示: .pom.xml -[source,xml,indent=0] +[source,xml] ---- ``` -### Spring Cloud Alibaba RocketMQ Binder 实现 +=== Spring Cloud Alibaba RocketMQ Binder 实现 这是 Spring Cloud Stream RocketMQ Binder 的实现架构: @@ -166,12 +166,12 @@ NOTE: 在使用 RocketMQ Binder 的同时也可以配置 rocketmq.** 用于触 MessageBuilder builder = MessageBuilder.withPayload(msg) .setHeader(RocketMQHeaders.TAGS, "binder") .setHeader(RocketMQHeaders.KEYS, "my-key") - .setHeader("DELAY", "1"); + .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "1"); Message message = builder.build(); output().send(message); ``` -### MessageSource 支持 +=== MessageSource 支持 SCS RocketMQ Binder 支持 `MessageSource`,可以进行消息的拉取,例子如下: @@ -225,9 +225,9 @@ public class MQApplication { -### 配置选项 +=== 配置选项 -#### RocketMQ Binder Properties +==== RocketMQ Binder Properties spring.cloud.stream.rocketmq.binder.name-server:: RocketMQ NameServer 地址(老版本使用 namesrv-addr 配置项)。 @@ -251,7 +251,7 @@ spring.cloud.stream.rocketmq.binder.customized-trace-topic:: Default: `RMQ_SYS_TRACE_TOPIC`. -#### RocketMQ Consumer Properties +==== RocketMQ Consumer Properties 下面的这些配置是以 `spring.cloud.stream.rocketmq.bindings..consumer.` 为前缀的 RocketMQ Consumer 相关的配置。 @@ -287,7 +287,7 @@ suspendCurrentQueueTimeMillis:: + 默认值: `1000`. -#### RocketMQ Provider Properties +==== RocketMQ Provider Properties 下面的这些配置是以 `spring.cloud.stream.rocketmq.bindings..producer.` 为前缀的 RocketMQ Producer 相关的配置。 @@ -336,7 +336,7 @@ retryNextServer:: + 默认值: `false`. -### 阿里云 MQ 服务 +=== 阿里云 MQ 服务 使用阿里云 MQ 服务需要配置 AccessKey、SecretKey 以及云上的 NameServer 地址。 @@ -351,4 +351,4 @@ spring.cloud.stream.rocketmq.binder.name-server=NameServerInMQ NOTE: topic 和 group 请以 实例id% 为前缀进行配置。比如 topic 为 "test",需要配置成 "实例id%test" .NameServer 的获取(配置中请去掉 http:// 前缀) -image::https://spring-cloud-alibaba.oss-cn-beijing.aliyuncs.com/MQ.png[] \ No newline at end of file +image::https://spring-cloud-alibaba.oss-cn-beijing.aliyuncs.com/MQ.png[] diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sentinel.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sentinel.adoc index 5cf33ea6..64ffefe9 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sentinel.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sentinel.adoc @@ -1,6 +1,6 @@ == Spring Cloud Alibaba Sentinel -### Sentinel 介绍 +=== Sentinel 介绍 随着微服务的流行,服务和服务之间的稳定性变得越来越重要。 https://github.com/alibaba/Sentinel[Sentinel] 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性。 @@ -11,11 +11,12 @@ https://github.com/alibaba/Sentinel[Sentinel] 具有以下特征: * *广泛的开源生态*: Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。 * *完善的 SPI 扩展点*: Sentinel 提供简单易用、完善的 SPI 扩展点。您可以通过实现扩展点,快速的定制逻辑。例如定制规则管理、适配数据源等。 -### 如何使用 Sentinel +=== 如何使用 Sentinel 如果要在您的项目中引入 Sentinel,使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alibaba-sentinel` 的 starter。 ```xml +[source,yaml] com.alibaba.cloud spring-cloud-starter-alibaba-sentinel @@ -75,7 +76,7 @@ public class TestController { } ``` -##### Sentinel 控制台 +===== Sentinel 控制台 Sentinel 控制台提供一个轻量级的控制台,它提供机器发现、单机资源实时监控、集群资源汇总,以及规则管理的功能。您只需要对应用进行简单的配置,就可以使用这些功能。 @@ -86,7 +87,7 @@ image::https://github.com/alibaba/Sentinel/wiki/image/dashboard.png[] 开启该功能需要3个步骤: -###### 获取控制台 +====== 获取控制台 您可以从 https://github.com/alibaba/Sentinel/releases[release 页面] 下载最新版本的控制台 jar 包。 @@ -96,7 +97,7 @@ image::https://github.com/alibaba/Sentinel/wiki/image/dashboard.png[] * 使用以下命令将代码打包成一个 fat jar: `mvn clean package` -###### 启动控制台 +====== 启动控制台 Sentinel 控制台是一个标准的 SpringBoot 应用,以 SpringBoot 的方式运行 jar 包即可。 @@ -106,10 +107,9 @@ java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject 如若8080端口冲突,可使用 `-Dserver.port=新端口` 进行设置。 -#### 配置控制台信息 +==== 配置控制台信息 .application.yml -[source,yaml] ---- spring: cloud: @@ -123,7 +123,7 @@ spring: 更多 Sentinel 控制台的使用及问题参考: https://github.com/alibaba/Sentinel/wiki/%E6%8E%A7%E5%88%B6%E5%8F%B0[Sentinel控制台] -### OpenFeign 支持 +=== OpenFeign 支持 Sentinel 适配了 https://github.com/OpenFeign/feign[OpenFeign] 组件。如果想使用,除了引入 `sentinel-starter` 的依赖外还需要 2 个步骤: @@ -141,7 +141,7 @@ Sentinel 适配了 https://github.com/OpenFeign/feign[OpenFeign] 组件。如果 ```java @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class) public interface EchoService { - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); } @@ -164,7 +164,7 @@ NOTE: Feign 对应的接口中的资源名策略定义:httpmethod:protocol://r `EchoService` 接口中方法 `echo` 对应的资源名为 `GET:http://service-provider/echo/{str}`。 -### RestTemplate 支持 +=== RestTemplate 支持 Spring Cloud Alibaba Sentinel 支持对 `RestTemplate` 的服务调用使用 Sentinel 进行保护,在构造 `RestTemplate` bean的时候需要加上 `@SentinelRestTemplate` 注解。 @@ -206,7 +206,7 @@ Sentinel RestTemplate 限流的资源规则提供两种粒度: NOTE: 以 `https://www.taobao.com/test` 这个 url 并使用 GET 方法为例。对应的资源名有两种粒度,分别是 `GET:https://www.taobao.com` 以及 `GET:https://www.taobao.com/test` -### 动态数据源支持 +=== 动态数据源支持 `SentinelProperties` 内部提供了 `TreeMap` 类型的 `datasource` 属性用于配置数据源信息。 @@ -254,7 +254,7 @@ NOTE: 默认情况下,xml 格式是不支持的。需要添加 `jackson-datafo 关于 Sentinel 动态数据源的实现原理,参考: https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95[动态规则扩展] -### Zuul 支持 +=== Zuul 支持 https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流] @@ -277,7 +277,7 @@ https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[ ``` -### Spring Cloud Gateway 支持 +=== Spring Cloud Gateway 支持 https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流] @@ -300,7 +300,7 @@ https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[ ``` -### Sentinel 对外暴露的 Endpoint +=== Sentinel 对外暴露的 Endpoint Sentinel 内部提供了一个 Endpoint, 对应的 endpoint id 为 `sentinel`。 @@ -404,7 +404,7 @@ Endpoint 暴露的 json 中包含了多种属性: } ---- -### 关于 Sentinel Starter 更多的配置项信息 +=== 关于 Sentinel Starter 更多的配置项信息 下表显示当应用的 `ApplicationContext` 中存在对应的Bean的类型时,会进行自动化设置: diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc new file mode 100644 index 00000000..74ad66ce --- /dev/null +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/sidecar.adoc @@ -0,0 +1,165 @@ +== 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] 。目前支持的服务发现组件: + +* Nacos + +* Consul + +=== 术语 + +==== 异构微服务 + +非Spring Cloud应用,统称异构微服务。比如你的遗留项目,或者非JVM应用。 + +==== ``完美整合''的三层含义 + +* 享受服务发现的优势 +* 有负载均衡 +* 有断路器 + +=== Why or Why not? + +==== 为什么要编写Alibaba Sidecar? + +原因有两点: + +* 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方案,颇有点屠龙刀杀黄鳝的意思。 + +=== 原理 + +* Alibaba +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"}` 的字符串即可)。 + +=== 使用示例 + +* 如使用Nacos作为服务发现组件,详见`spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example` +* 如使用Consul作为服务发现组件,详见`spring-cloud-alibaba-examples/spring-cloud-alibaba-sidecar-examples/spring-cloud-alibaba-sidecar-nacos-example` + +==== 示例代码(以Nacos服务发现为例) + +* 加依赖: ++ +[source,xml] +---- + + com.alibaba.cloud + spring-cloud-starter-alibaba-sidecar + +---- +* 写配置: ++ +[source,yaml] +---- +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 +---- ++ +配置比较简单,就是把Alibaba Sidecar注册到Nacos上,然后添加了几行Alibaba Sidecar的配置。 + +==== 异构微服务 + +我准备了一个NodeJS编写的简单微服务。 + +[source,javascript] +---- +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'); +}); +---- + +==== 测试 + +===== 测试1:Spring Cloud微服务完美调用异构微服务 + +为你的Spring Cloud微服务整合Ribbon,然后构建 `http://node-service/\\**`,就可以请求到异构微服务的 `/**` 了。 + +示例: + +Ribbon请求 `http://node-service/` 会请求到 `http://localhost:8060/`,以此类推。 + +至于断路器,正常为你的Spring Cloud微服务整合Sentinel或者Hystirx、Resilience4J即可 。 + +===== 测试2:异构微服务完美调用Spring Cloud微服务 + +由于Alibaba Sidecar基于Spring Cloud Gateway,而网关自带转发能力。 + +示例: + +如果你有一个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,所以也带有了断路器。 + +=== Alibaba Sidecar优缺点分析 + +Alibaba Sidecar的设计和Sidecar基本一致,优缺点和Sidecar的优缺点也是一样的。 + +优点: + +* 接入简单,几行代码就可以将异构微服务整合到Spring Cloud生态 +* 不侵入原代码 + +缺点: + +* 每接入一个异构微服务实例,都需要额外部署一个Alibaba Sidecar实例,增加了部署成本(虽然这个成本在Kubernetes环境中几乎可以忽略不计(只需将Alibaba Sidecar实例和异构微服务作为一个Pod部署即可)); +* 异构微服务调用Spring Cloud微服务时,本质是把Alibaba Sidecar当网关在使用,经过了一层转发,性能有一定下降。 diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc index 8e0d889f..13e0e76e 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/spring-cloud-alibaba.adoc @@ -31,3 +31,6 @@ include::schedulerx.adoc[] include::sms.adoc[] +include::sidecar.adoc[] + + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc index 2213114a..dede7648 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc @@ -93,3 +93,4 @@ Access-key and secret-key are the AK/SK of your Alibaba Cloud account. Register Namespace is a concept in EDAS, which is used to isolate environments, such as testing environment and production environment. To find your namespace, click to https://common-buy.aliyun.com/?spm=5176.11451019.0.0.6f5965c0Uq5tue&commodityCode=edaspostpay#/buy[Sign up for EDAS] first. You will not be charged under the pay-as-you-go mode. Then log on to the https://edas.console.aliyun.com/#/namespaces?regionNo=cn-hangzhou[EDAS Console] and you will be able to see your namespace, for example cn-hangzhou. NOTE: EDAS provides application hosting service and will fill in all configurations automatically for the hosted applications. + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/circuitbreaker-sentinel.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/circuitbreaker-sentinel.adoc new file mode 100644 index 00000000..b2695e72 --- /dev/null +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/circuitbreaker-sentinel.adoc @@ -0,0 +1,73 @@ +=== Circuit Breaker: Spring Cloud Circuit Breaker With Sentinel & Configuring Sentinel Circuit Breakers + +==== Default Configuration + +To provide a default configuration for all of your circuit breakers create a `Customizer` bean that is passed a +`SentinelCircuitBreakerFactory` or `ReactiveSentinelCircuitBreakerFactory`. +The `configureDefault` method can be used to provide a default configuration. + +==== +[source,java] +---- +@Bean +public Customizer defaultCustomizer() { + return factory -> factory.configureDefault(id -> new SentinelConfigBuilder(id) + .build()); +} +---- +==== + +You can choose to provide default circuit breaking rules via `SentinelConfigBuilder#rules(rules)`. +You can also choose to load circuit breaking rules later elsewhere using +`DegradeRuleManager.loadRules(rules)` API of Sentinel, or via Sentinel dashboard. + +===== Reactive Example + +==== +[source,java] +---- +@Bean +public Customizer defaultCustomizer() { + return factory -> factory.configureDefault(id -> new SentinelConfigBuilder(id) + .build()); +} +---- +==== + +==== Specific Circuit Breaker Configuration + +Similarly to providing a default configuration, you can create a `Customizer` bean this is passed a +`SentinelCircuitBreakerFactory`. + +==== +[source,java] +---- +@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); +} +---- +==== + +===== Reactive Example + +==== +[source,java] +---- +@Bean +public Customizer customizer() { + List rules = Collections.singletonList( + new DegradeRule().setGrade(RuleConstant.DEGRADE_GRADE_RT) + .setCount(100) + .setTimeWindow(10) + ); + return factory -> factory.configure(builder -> builder.rules(rules), "foo", "bar"); +} +---- +==== \ No newline at end of file diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc index 0002c6c8..5342c9b6 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc @@ -17,3 +17,4 @@ If you’re a Maven Central user, add our BOM to your pom.xml ``` -### How Spring Cloud Alibaba RocketMQ Binder Works +=== How Spring Cloud Alibaba RocketMQ Binder Works This is the implementation architecture of Spring Cloud Stream RocketMQ Binder: @@ -165,12 +165,12 @@ For example, `TAGS`, `DELAY`, `TRANSACTIONAL_ARG`, `KEYS`, `WAIT_STORE_MSG_OK`, MessageBuilder builder = MessageBuilder.withPayload(msg) .setHeader(RocketMQHeaders.TAGS, "binder") .setHeader(RocketMQHeaders.KEYS, "my-key") - .setHeader("DELAY", "1"); + .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "1"); Message message = builder.build(); output().send(message); ``` -### Support MessageSource +=== Support MessageSource SCS RocketMQ Binder support `MessageSource`,which can receive messages by pull mode: @@ -222,9 +222,9 @@ public class MQApplication { } ``` -### Configuration Options +=== Configuration Options -#### RocketMQ Binder Properties +==== RocketMQ Binder Properties spring.cloud.stream.rocketmq.binder.name-server:: The name server of RocketMQ Server(Older versions use the namesrv-addr configuration item). @@ -248,7 +248,7 @@ The trace topic for message trace. Default: `RMQ_SYS_TRACE_TOPIC`. -#### RocketMQ Consumer Properties +==== RocketMQ Consumer Properties The following properties are available for RocketMQ producers only and must be prefixed with `spring.cloud.stream.rocketmq.bindings..consumer.`. @@ -284,7 +284,7 @@ Time interval of message consume retry for orderly consume. + Default: `1000`. -#### RocketMQ Provider Properties +==== RocketMQ Provider Properties The following properties are available for RocketMQ producers only and must be prefixed with `spring.cloud.stream.rocketmq.bindings..producer.`. diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc index de969003..38c79c50 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc @@ -111,4 +111,4 @@ NOTE: Group-id must be created within a namespace. Access-key and secret-key are the AK/SK of your Alibaba Cloud account. If you deploy you applications on EDAS, then you do not need to fill in this information. Otherwise please go to https://usercenter.console.aliyun.com/#/manage/ak[Security Information] to get your AccessKeys. -Domain-name is not mandatory. You can refer to https://help.aliyun.com/document_detail/35359.html[SchedulerX Documentation] for details. \ No newline at end of file +Domain-name is not mandatory. You can refer to https://help.aliyun.com/document_detail/35359.html[SchedulerX Documentation] for details. diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc index dcb3b575..e0a5622a 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc @@ -1,6 +1,6 @@ == Spring Cloud Alibaba Sentinel -### Introduction of Sentinel +=== Introduction of Sentinel As microservices become popular, the stability of service calls is becoming increasingly important. https://github.com/alibaba/Sentinel[Sentinel] takes "flow" as the breakthrough point, and works on multiple fields including flow control, circuit breaking and load protection to protect service reliability. @@ -12,7 +12,7 @@ https://github.com/alibaba/Sentinel[Sentinel] has the following features: * *Extensive Open-Source Ecosystem*: Sentinel provides out-of-box modules that can be easily integrated with other open-source frameworks/libraries, such as Spring Cloud, Dubbo, and gRPC. To use Sentinel, you only need to introduce the related dependency and make a few simple configurations. * *Sound SPI Extensions*: Sentinel provides easy-to-use and sound SPI extension interfaces. You can customize logics with the SPI extensions quickly, for example, you can define your own rule management, or adapt to specific data sources. -### How to Use Sentinel +=== How to Use Sentinel If you want to use Sentinel in your project, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alibaba-sentinel`. @@ -76,7 +76,7 @@ public class TestController { } ``` -##### Sentinel Dashboard +===== Sentinel Dashboard Sentinel dashboard is a lightweight console that provides functions such as machine discovery, single-server resource monitoring, overview of cluster resource data, as well as rule management. To use these features, you only need to complete a few steps. @@ -87,7 +87,7 @@ image::https://github.com/alibaba/Sentinel/wiki/image/dashboard.png[] To use the Sentinel dashboard, simply complete the following 3 steps. -###### Get the Dashboard +====== Get the Dashboard You can download the latest dashboard JAR file from the https://github.com/alibaba/Sentinel/releases[Release Page]. @@ -97,7 +97,7 @@ You can also get the latest source code to build your own Sentinel dashboard: * Run the following command to package the code into a FatJar: `mvn clean package` -###### Start the Dashboard +====== Start the Dashboard Sentinel dashboard is a standard SpringBoot application, and you can run the JAR file in the Spring Boot mode. @@ -107,7 +107,7 @@ java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject If there is conflict with the 8080 port, you can use `-Dserver.port=new port` to define a new port. -#### Configure the Dashboard +==== Configure the Dashboard .application.yml [source,yaml] @@ -124,7 +124,7 @@ The port number specified in `spring.cloud.sentinel.transport.port` will start a For more information about Sentinel dashboard, please refer to https://github.com/alibaba/Sentinel/wiki/%E6%8E%A7%E5%88%B6%E5%8F%B0[Sentinel Dashboard]. -### OpenFeign Support +=== OpenFeign Support Sentinel is compatible with the https://github.com/OpenFeign/feign[OpenFeign] component. To use it, in addition to introducing the `sentinel-starter` dependency, complete the following 2 steps: @@ -142,7 +142,7 @@ This is a simple usage of `FeignClient`: ```java @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class) public interface EchoService { - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); } @@ -165,7 +165,7 @@ NOTE: The resource name policy in the corresponding interface of Feign is:http The corresponding resource name of the `echo` method in the `EchoService` interface is `GET:http://service-provider/echo/{str}`. -### RestTemplate Support +=== RestTemplate Support Spring Cloud Alibaba Sentinel supports the protection of `RestTemplate` service calls using Sentinel. To do this, you need to add the `@SentinelRestTemplate` annotation when constructing the `RestTemplate` bean. @@ -209,7 +209,7 @@ Sentinel RestTemplate provides two granularities for resource rate limiting: NOTE: Take Http GET `https://www.taobao.com/test` as an example. The corresponding resource names have two levels of granularities, `GET:https://www.taobao.com` and `GET:https://www.taobao.com/test`. -### Dynamic Data Source Support +=== Dynamic Data Source Support `SentinelProperties` provide `datasource` attribute to configure datasource. @@ -255,9 +255,9 @@ NOTE: XML format is not supported by default. To make it effective, you need to To learn more about how dynamic data sources work in Sentinel, refer to https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95[Dynamic Rule Extension]. -### Support Zuul +=== Support Zuul -https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流] +Refer https://github.com/alibaba/Sentinel/wiki/API-Gateway-Flow-Control[API Gateway Flow Control] If you want to use Sentinel Starter with Zuul, you need to add the `spring-cloud-alibaba-sentinel-gateway` dependency, and you need to add the `spring-cloud-starter-netflix-zuul` dependency to let Zuul AutoConfiguration class in the gateway module takes effect: @@ -278,9 +278,9 @@ If you want to use Sentinel Starter with Zuul, you need to add the `spring-cloud ``` -### Support Spring Cloud Gateway +=== Support Spring Cloud Gateway -https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流] +Refer https://github.com/alibaba/Sentinel/wiki/API-Gateway-Flow-Control[API Gateway Flow Control] If you want to use Sentinel Starter with Spring Cloud Gateway, you need to add the `spring-cloud-alibaba-sentinel-gateway` dependency and add the `spring-cloud-starter-gateway` dependency to let Spring Cloud Gateway AutoConfiguration class in the module takes effect: @@ -301,7 +301,9 @@ If you want to use Sentinel Starter with Spring Cloud Gateway, you need to add t ``` -### Sentinel Endpoint +include::circuitbreaker-sentinel.adoc[] + +=== Sentinel Endpoint Sentinel provides an Endpoint internally with a corresponding endpoint id of `sentinel`. @@ -404,7 +406,7 @@ The followings shows how a service instance accesses the Endpoint: } ---- -### Configuration +=== Configuration The following table shows that when there are corresponding bean types in `ApplicationContext`, some actions will be taken: @@ -447,4 +449,4 @@ The following table shows all the configurations of Spring Cloud Alibaba Sentine |=== -NOTE: These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations. \ No newline at end of file +NOTE: These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations. diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc index e91bb73f..f6308fb0 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc @@ -207,4 +207,4 @@ public class SmsUpMessageListener } ---- -More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here]. \ No newline at end of file +More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here]. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java index f992365e..2433f227 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/DubboMetadataEndpointAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,6 +15,8 @@ */ package com.alibaba.cloud.dubbo.actuate; +import com.alibaba.cloud.dubbo.actuate.endpoint.DubboRestMetadataEndpoint; + import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.autoconfigure.web.ManagementContextConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -24,8 +25,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; -import com.alibaba.cloud.dubbo.actuate.endpoint.DubboRestMetadataEndpoint; - /** * Dubbo Metadata Endpoints Auto-{@link Configuration} * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java index e04e246d..2403a05a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/actuate/endpoint/DubboRestMetadataEndpoint.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,13 +15,13 @@ */ package com.alibaba.cloud.dubbo.actuate.endpoint; -import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; +import com.alibaba.cloud.dubbo.service.DubboMetadataService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; -import com.alibaba.cloud.dubbo.service.DubboMetadataService; +import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; /** * Dubbo Rest Metadata {@link Endpoint} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java index 23dcf34f..87ac0449 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/annotation/DubboTransported.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,8 +15,6 @@ */ package com.alibaba.cloud.dubbo.annotation; -import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_RETRIES; - import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; @@ -32,6 +29,8 @@ import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.client.RestTemplate; +import static org.apache.dubbo.rpc.cluster.Constants.DEFAULT_RETRIES; + /** * {@link DubboTransported @DubboTransported} annotation indicates that the traditional * Spring Cloud Service-to-Service call is transported by Dubbo under the hood, there are diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java index 5165e4b5..5e867386 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboLoadBalancedRestTemplateAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -14,33 +13,14 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.autoconfigure; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; - -import org.springframework.beans.factory.BeanClassLoaderAware; -import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.config.BeanDefinition; -import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; -import org.springframework.boot.autoconfigure.AutoConfigureAfter; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.context.event.ApplicationStartedEvent; -import org.springframework.cloud.client.loadbalancer.LoadBalanced; -import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; -import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer; -import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.event.EventListener; -import org.springframework.core.env.Environment; -import org.springframework.core.type.MethodMetadata; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.util.CollectionUtils; -import org.springframework.web.client.RestTemplate; +import java.util.Optional; import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.client.loadbalancer.DubboMetadataInitializerInterceptor; @@ -50,9 +30,33 @@ import com.alibaba.cloud.dubbo.metadata.resolver.DubboTransportedAttributesResol import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import org.springframework.beans.factory.BeanClassLoaderAware; +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.annotation.AnnotatedBeanDefinition; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.config.BeanDefinition; +import org.springframework.beans.factory.config.ConfigurableListableBeanFactory; +import org.springframework.boot.autoconfigure.AutoConfigureAfter; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.cloud.client.loadbalancer.LoadBalanced; +import org.springframework.cloud.client.loadbalancer.LoadBalancerInterceptor; +import org.springframework.cloud.client.loadbalancer.RestTemplateCustomizer; +import org.springframework.cloud.client.loadbalancer.RetryLoadBalancerInterceptor; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.event.ContextRefreshedEvent; +import org.springframework.context.event.EventListener; +import org.springframework.core.env.Environment; +import org.springframework.core.type.MethodMetadata; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.lang.Nullable; +import org.springframework.util.CollectionUtils; +import org.springframework.web.client.RestTemplate; + /** * Dubbo Auto-{@link Configuration} for {@link LoadBalanced @LoadBalanced} - * {@link RestTemplate} + * {@link RestTemplate}. * * @author Mercy */ @@ -60,8 +64,8 @@ import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; @ConditionalOnClass(name = { "org.springframework.web.client.RestTemplate" }) @AutoConfigureAfter(name = { "org.springframework.cloud.client.loadbalancer.LoadBalancerAutoConfiguration" }) -public class DubboLoadBalancedRestTemplateAutoConfiguration - implements BeanClassLoaderAware, SmartInitializingSingleton { +public class DubboLoadBalancedRestTemplateAutoConfiguration implements + BeanClassLoaderAware, ApplicationContextAware, SmartInitializingSingleton { private static final Class DUBBO_TRANSPORTED_CLASS = DubboTransported.class; @@ -93,11 +97,14 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration @Autowired(required = false) private Map restTemplates = Collections.emptyMap(); + @Nullable + private ApplicationContext applicationContext; + private ClassLoader classLoader; /** * The {@link ClientHttpRequestInterceptor} bean that may be - * {@link LoadBalancerInterceptor} or {@link RetryLoadBalancerInterceptor} + * {@link LoadBalancerInterceptor} or {@link RetryLoadBalancerInterceptor}. */ private ClientHttpRequestInterceptor loadBalancerInterceptorBean; @@ -113,28 +120,31 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration * {@link LoadBalanced @LoadBalanced} and {@link LoadBalanced @LoadBalanced} when * Spring Boot application started (after the callback of * {@link SmartInitializingSingleton} beans or - * {@link RestTemplateCustomizer#customize(RestTemplate) customization}) + * {@link RestTemplateCustomizer#customize(RestTemplate) customization}). + * @param event spring event */ - @EventListener(ApplicationStartedEvent.class) - public void adaptRestTemplates() { + @EventListener(ContextRefreshedEvent.class) + public void adaptRestTemplates(ContextRefreshedEvent event) { - DubboTransportedAttributesResolver attributesResolver = new DubboTransportedAttributesResolver( - environment); + if (event.getApplicationContext() == this.applicationContext) { - for (Map.Entry entry : restTemplates.entrySet()) { - String beanName = entry.getKey(); - Map dubboTranslatedAttributes = getDubboTranslatedAttributes( - beanName, attributesResolver); - if (!CollectionUtils.isEmpty(dubboTranslatedAttributes)) { - adaptRestTemplate(entry.getValue(), dubboTranslatedAttributes); + DubboTransportedAttributesResolver attributesResolver = new DubboTransportedAttributesResolver( + environment); + + for (Map.Entry entry : restTemplates.entrySet()) { + String beanName = entry.getKey(); + Map dubboTranslatedAttributes = getDubboTranslatedAttributes( + beanName, attributesResolver); + if (!CollectionUtils.isEmpty(dubboTranslatedAttributes)) { + adaptRestTemplate(entry.getValue(), dubboTranslatedAttributes); + } } } } /** * Gets the annotation attributes {@link RestTemplate} bean being annotated - * {@link DubboTransported @DubboTransported} - * + * {@link DubboTransported @DubboTransported}. * @param beanName the bean name of {@link LoadBalanced @LoadBalanced} * {@link RestTemplate} * @param attributesResolver {@link DubboTransportedAttributesResolver} @@ -148,10 +158,10 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration AnnotatedBeanDefinition annotatedBeanDefinition = (AnnotatedBeanDefinition) beanDefinition; MethodMetadata factoryMethodMetadata = annotatedBeanDefinition .getFactoryMethodMetadata(); - attributes = factoryMethodMetadata != null - ? factoryMethodMetadata - .getAnnotationAttributes(DUBBO_TRANSPORTED_CLASS_NAME) - : Collections.emptyMap(); + attributes = factoryMethodMetadata != null ? Optional + .ofNullable(factoryMethodMetadata + .getAnnotationAttributes(DUBBO_TRANSPORTED_CLASS_NAME)) + .orElse(attributes) : Collections.emptyMap(); } return attributesResolver.resolve(attributes); } @@ -159,7 +169,6 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration /** * Adapt the instance of {@link DubboTransporterInterceptor} to the * {@link LoadBalancerInterceptor} Bean. - * * @param restTemplate {@link LoadBalanced @LoadBalanced} {@link RestTemplate} Bean * @param dubboTranslatedAttributes the annotation dubboTranslatedAttributes * {@link RestTemplate} bean being annotated @@ -192,4 +201,9 @@ public class DubboLoadBalancedRestTemplateAutoConfiguration this.classLoader = classLoader; } + @Override + public void setApplicationContext(ApplicationContext applicationContext) { + this.applicationContext = applicationContext; + } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java index f39aa5fb..0ebbbdf3 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboMetadataAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -17,8 +16,21 @@ package com.alibaba.cloud.dubbo.autoconfigure; import java.util.Collection; +import java.util.Optional; import java.util.function.Supplier; +import com.alibaba.cloud.dubbo.metadata.DubboProtocolConfigSupplier; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.metadata.repository.MetadataServiceInstanceSelector; +import com.alibaba.cloud.dubbo.metadata.resolver.DubboServiceBeanMetadataResolver; +import com.alibaba.cloud.dubbo.metadata.resolver.MetadataResolver; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +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; import org.apache.dubbo.config.spring.context.event.ServiceBeanExportedEvent; @@ -32,18 +44,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.event.ContextClosedEvent; import org.springframework.context.event.EventListener; - -import com.alibaba.cloud.dubbo.metadata.DubboProtocolConfigSupplier; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.metadata.resolver.DubboServiceBeanMetadataResolver; -import com.alibaba.cloud.dubbo.metadata.resolver.MetadataResolver; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; -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.springframework.util.CollectionUtils; /** * Spring Boot Auto-Configuration class for Dubbo Metadata @@ -70,6 +71,14 @@ public class DubboMetadataAutoConfiguration { return new DubboServiceBeanMetadataResolver(contract); } + @Bean + @ConditionalOnMissingBean + public MetadataServiceInstanceSelector metadataServiceInstanceSelector() { + return serviceInstances -> CollectionUtils.isEmpty(serviceInstances) + ? Optional.empty() + : serviceInstances.stream().findAny(); + } + @Bean public Supplier dubboProtocolConfigSupplier( ObjectProvider> protocols) { diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java index 0f282bf3..7429f561 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboOpenFeignAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,7 +15,10 @@ */ package com.alibaba.cloud.dubbo.autoconfigure; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.openfeign.TargeterBeanPostProcessor; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -24,10 +26,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.openfeign.TargeterBeanPostProcessor; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME; /** * Dubbo Feign Auto-{@link Configuration Configuration} @@ -40,6 +39,9 @@ import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; @Configuration public class DubboOpenFeignAutoConfiguration { + /** + * OpenFeign Targeter class name. + */ public static final String TARGETER_CLASS_NAME = "org.springframework.cloud.openfeign.Targeter"; @Bean diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java index 70d992dc..08823ffd 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,6 +15,14 @@ */ package com.alibaba.cloud.dubbo.autoconfigure; +import com.alibaba.cloud.dubbo.env.DubboCloudProperties; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import com.alibaba.cloud.dubbo.service.parameter.PathVariableServiceParameterResolver; +import com.alibaba.cloud.dubbo.service.parameter.RequestBodyServiceParameterResolver; +import com.alibaba.cloud.dubbo.service.parameter.RequestHeaderServiceParameterResolver; +import com.alibaba.cloud.dubbo.service.parameter.RequestParamServiceParameterResolver; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -26,14 +33,6 @@ import org.springframework.context.annotation.Primary; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertyResolver; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; -import com.alibaba.cloud.dubbo.service.parameter.PathVariableServiceParameterResolver; -import com.alibaba.cloud.dubbo.service.parameter.RequestBodyServiceParameterResolver; -import com.alibaba.cloud.dubbo.service.parameter.RequestHeaderServiceParameterResolver; -import com.alibaba.cloud.dubbo.service.parameter.RequestParamServiceParameterResolver; - /** * Spring Boot Auto-Configuration class for Dubbo Service * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java index db22da91..82b8805d 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceDiscoveryAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,13 +15,6 @@ */ package com.alibaba.cloud.dubbo.autoconfigure; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceDiscoveryAutoConfiguration.CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME; -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 org.springframework.util.StringUtils.hasText; - import java.util.Collection; import java.util.LinkedList; import java.util.List; @@ -34,6 +26,20 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.function.Predicate; import java.util.stream.Stream; +import com.alibaba.cloud.dubbo.env.DubboCloudProperties; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.registry.AbstractSpringCloudRegistry; +import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent; +import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; +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; import org.apache.curator.framework.listen.Listenable; import org.apache.curator.framework.listen.ListenerContainer; @@ -41,16 +47,15 @@ import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.TreeCache; import org.apache.curator.framework.recipes.cache.TreeCacheEvent; import org.apache.curator.framework.recipes.cache.TreeCacheListener; - import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.NotifyListener; - import org.apache.zookeeper.Watcher; import org.aspectj.lang.annotation.After; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; @@ -74,18 +79,12 @@ import org.springframework.scheduling.TaskScheduler; import org.springframework.util.AntPathMatcher; import org.springframework.util.ReflectionUtils; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.registry.AbstractSpringCloudRegistry; -import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent; -import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -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 static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceDiscoveryAutoConfiguration.CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME; +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 org.springframework.util.StringUtils.hasText; /** * Dubbo Service Discovery Auto {@link Configuration} (after @@ -106,10 +105,19 @@ import com.netflix.discovery.shared.Applications; DubboServiceRegistrationAutoConfiguration.class }) public class DubboServiceDiscoveryAutoConfiguration { + /** + * ZookeeperDiscoveryAutoConfiguration. + */ public static final String ZOOKEEPER_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.zookeeper.discovery.ZookeeperDiscoveryAutoConfiguration"; + /** + * ConsulDiscoveryClientConfiguration. + */ public static final String CONSUL_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "org.springframework.cloud.consul.discovery.ConsulDiscoveryClientConfiguration"; + /** + * NacosDiscoveryAutoConfiguration. + */ public static final String NACOS_DISCOVERY_AUTO_CONFIGURATION_CLASS_NAME = "com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration"; private final DubboServiceMetadataRepository dubboServiceMetadataRepository; @@ -506,8 +514,8 @@ public class DubboServiceDiscoveryAutoConfiguration { */ private final Set listeningServices; - NacosConfiguration(NacosDiscoveryProperties nacosDiscoveryProperties) { - this.namingService = nacosDiscoveryProperties.namingServiceInstance(); + NacosConfiguration(NacosNamingManager nacosNamingManager) { + this.namingService = nacosNamingManager.getNamingService(); this.listeningServices = new ConcurrentSkipListSet<>(); } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java index 6031edce..49cda2c2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,22 +15,23 @@ */ package com.alibaba.cloud.dubbo.autoconfigure; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME; -import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.ADDRESS; -import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL; -import static org.springframework.util.ObjectUtils.isEmpty; - import java.util.Collection; import java.util.List; import java.util.Map; +import com.alibaba.cloud.dubbo.autoconfigure.condition.MissingSpringCloudRegistryConfigPropertyCondition; +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; import org.apache.dubbo.config.spring.ServiceBean; - import org.aspectj.lang.annotation.Aspect; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.aop.support.AopUtils; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; @@ -53,12 +53,11 @@ import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Import; import org.springframework.context.event.EventListener; -import com.alibaba.cloud.dubbo.autoconfigure.condition.MissingSpringCloudRegistryConfigPropertyCondition; -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 static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; +import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.EUREKA_CLIENT_AUTO_CONFIGURATION_CLASS_NAME; +import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.ADDRESS; +import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL; +import static org.springframework.util.ObjectUtils.isEmpty; /** * Dubbo Service Registration Auto-{@link Configuration} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java index 9c8e209c..40194719 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationNonWebApplicationAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,17 +15,18 @@ */ package com.alibaba.cloud.dubbo.autoconfigure; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.ZOOKEEPER_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; - 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; - import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; + import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; @@ -43,9 +43,8 @@ import org.springframework.cloud.zookeeper.serviceregistry.ServiceInstanceRegist import org.springframework.context.annotation.Configuration; import org.springframework.context.event.EventListener; -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 static com.alibaba.cloud.dubbo.autoconfigure.DubboServiceRegistrationAutoConfiguration.CONSUL_AUTO_SERVICE_AUTO_CONFIGURATION_CLASS_NAME; +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 diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java index 3aa14cd7..40c34046 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/autoconfigure/condition/MissingSpringCloudRegistryConfigPropertyCondition.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,11 +15,10 @@ */ package com.alibaba.cloud.dubbo.autoconfigure.condition; -import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL; -import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; - import java.util.Map; +import com.alibaba.cloud.dubbo.registry.SpringCloudRegistry; + import org.springframework.boot.autoconfigure.condition.ConditionOutcome; import org.springframework.boot.autoconfigure.condition.SpringBootCondition; import org.springframework.context.annotation.Condition; @@ -29,7 +27,8 @@ import org.springframework.core.env.ConfigurableEnvironment; import org.springframework.core.type.AnnotatedTypeMetadata; import org.springframework.util.StringUtils; -import com.alibaba.cloud.dubbo.registry.SpringCloudRegistry; +import static com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory.PROTOCOL; +import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; /** * Missing {@link SpringCloudRegistry} Property {@link Condition} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java index 27fc1c94..268bd665 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponse.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java index 561515f7..fa299200 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboClientHttpResponseFactory.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -19,17 +18,17 @@ package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; import java.util.List; +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; import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.converter.HttpMessageConverter; -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; - /** * Dubbo {@link ClientHttpResponse} Factory * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java index 96a3e6c8..38353a77 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboHttpOutputMessage.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java index 53bc6a3f..56e21263 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboMetadataInitializerInterceptor.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -19,13 +18,13 @@ package com.alibaba.cloud.dubbo.client.loadbalancer; import java.io.IOException; import java.net.URI; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; + import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.ClientHttpResponse; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; - /** * Dubbo Metadata {@link ClientHttpRequestInterceptor} Initializing Interceptor executes * intercept before {@link DubboTransporterInterceptor} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java index 4d73112d..d6dc608a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/client/loadbalancer/DubboTransporterInterceptor.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,13 +15,20 @@ */ package com.alibaba.cloud.dubbo.client.loadbalancer; -import static org.springframework.web.util.UriComponentsBuilder.fromUri; - import java.io.IOException; import java.net.URI; import java.util.List; import java.util.Map; +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; @@ -37,14 +43,7 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.PathMatcher; import org.springframework.web.util.UriComponents; -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 static org.springframework.web.util.UriComponentsBuilder.fromUri; /** * Dubbo Transporter {@link ClientHttpRequestInterceptor} implementation diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java index e9c747cf..a2f07cef 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/context/DubboServiceRegistrationApplicationContextInitializer.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,11 +15,11 @@ */ package com.alibaba.cloud.dubbo.context; +import com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory; + import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; -import com.alibaba.cloud.dubbo.registry.SpringCloudRegistryFactory; - /** * The Dubbo services will be registered as the specified Spring cloud applications that * will not be considered normal ones, but only are used to Dubbo's service discovery even diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java index b9d33c37..c93a656a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboCloudProperties.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,16 +15,16 @@ */ package com.alibaba.cloud.dubbo.env; -import static org.springframework.util.StringUtils.commaDelimitedListToStringArray; -import static org.springframework.util.StringUtils.hasText; -import static org.springframework.util.StringUtils.trimAllWhitespace; - import java.util.Collections; import java.util.LinkedHashSet; import java.util.Set; import org.springframework.boot.context.properties.ConfigurationProperties; +import static org.springframework.util.StringUtils.commaDelimitedListToStringArray; +import static org.springframework.util.StringUtils.hasText; +import static org.springframework.util.StringUtils.trimAllWhitespace; + /** * Dubbo Cloud {@link ConfigurationProperties Properties} * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java index 90eae069..97df11b5 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/env/DubboNonWebApplicationEnvironmentPostProcessor.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,15 +15,13 @@ */ package com.alibaba.cloud.dubbo.env; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.apache.dubbo.config.spring.util.PropertySourcesUtils.getSubProperties; - import java.util.HashMap; import java.util.Map; import java.util.Properties; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.boot.SpringApplication; import org.springframework.boot.WebApplicationType; import org.springframework.boot.env.EnvironmentPostProcessor; @@ -36,6 +33,9 @@ import org.springframework.core.env.PropertySource; 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; + /** * Dubbo {@link WebApplicationType#NONE Non-Web Application} * {@link EnvironmentPostProcessor} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java index 4484a580..a36666df 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/ByteArrayHttpInputMessage.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java index 183c4096..0c75cea2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/DefaultHttpRequest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,8 +15,6 @@ */ package com.alibaba.cloud.dubbo.http; -import static org.springframework.web.util.UriComponentsBuilder.fromPath; - import java.net.URI; import java.util.List; import java.util.Map; @@ -29,6 +26,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.web.util.UriComponentsBuilder; +import static org.springframework.web.util.UriComponentsBuilder.fromPath; + /** * Default {@link HttpRequest} implementation * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java index 11af6767..32b67efb 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/HttpServerRequest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java index 3348bd69..efc7bb77 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/MutableHttpServerRequest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,8 +15,6 @@ */ package com.alibaba.cloud.dubbo.http; -import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; - import java.io.IOException; import java.io.InputStream; import java.net.URI; @@ -29,6 +26,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; import org.springframework.util.MultiValueMap; +import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; + /** * Mutable {@link HttpServerRequest} implementation * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java index 67d2f30b..a4076b25 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/converter/HttpMessageConverterHolder.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java index 4bc1c281..cc4994d0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java index 60e8939f..67b75957 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java index fe50e187..e34aa953 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,12 +15,12 @@ */ package com.alibaba.cloud.dubbo.http.matcher; -import static org.springframework.util.StringUtils.trimWhitespace; - import org.springframework.http.HttpRequest; import org.springframework.util.ObjectUtils; import org.springframework.util.StringUtils; +import static org.springframework.util.StringUtils.trimWhitespace; + /** * The some source code is scratched from * org.springframework.web.servlet.mvc.condition.AbstractNameValueExpression diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java index 2e634732..1ad2fa89 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/CompositeHttpRequestMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java index e34c394a..b63ea2ed 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java index 1f2e80cf..ce00f66e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java index aa160e29..c97b4c24 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestConsumersMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java index 8ad427e4..34ca0419 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestHeadersMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java index d53536b9..65ef03de 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java index d520f792..5500d4c6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,8 +15,6 @@ */ package com.alibaba.cloud.dubbo.http.matcher; -import static org.springframework.http.HttpMethod.resolve; - import java.util.Collection; import java.util.LinkedHashSet; import java.util.Set; @@ -26,6 +23,8 @@ import org.springframework.http.HttpMethod; import org.springframework.http.HttpRequest; import org.springframework.util.StringUtils; +import static org.springframework.http.HttpMethod.resolve; + /** * {@link HttpRequest} {@link HttpMethod methods} {@link HttpRequestMatcher matcher} * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java index 01cafdfd..81c9c685 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java index 1d2a2264..9d92654f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestPathMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java index ea949aed..d35445f4 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestProducesMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java index 5f33de34..5638614a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/MediaTypeExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java index bbf3a96a..644c4939 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/NameValueExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java index 555d1d57..de7d97a4 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,12 +15,12 @@ */ package com.alibaba.cloud.dubbo.http.matcher; -import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; - import org.springframework.http.HttpRequest; import org.springframework.util.MultiValueMap; import org.springframework.util.ObjectUtils; +import static com.alibaba.cloud.dubbo.http.util.HttpUtils.getParameters; + /** * Parses and matches a single param expression to a request. *

diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java index 7b9cfe3f..79b08fd2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpression.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java index 0385bd34..a0a62483 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/matcher/RequestMetadataMatcher.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,10 +15,10 @@ */ package com.alibaba.cloud.dubbo.http.matcher; -import static com.alibaba.cloud.dubbo.http.util.HttpUtils.toNameAndValues; - import com.alibaba.cloud.dubbo.metadata.RequestMetadata; +import static com.alibaba.cloud.dubbo.http.util.HttpUtils.toNameAndValues; + /** * {@link RequestMetadata} {@link HttpRequestMatcher} implementation * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java index e27b0df6..374ec949 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpMessageConverterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,14 +15,16 @@ */ package com.alibaba.cloud.dubbo.http.util; -import static java.util.Collections.unmodifiableList; - import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; +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; @@ -35,9 +36,7 @@ import org.springframework.http.server.ServletServerHttpResponse; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; -import com.alibaba.cloud.dubbo.http.converter.HttpMessageConverterHolder; -import com.alibaba.cloud.dubbo.metadata.RequestMetadata; -import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; +import static java.util.Collections.unmodifiableList; /** * {@link HttpMessageConverter} Resolver diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java index 30620cc5..337993cf 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/http/util/HttpUtils.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,10 +15,6 @@ */ package com.alibaba.cloud.dubbo.http.util; -import static org.springframework.util.StringUtils.delimitedListToStringArray; -import static org.springframework.util.StringUtils.hasText; -import static org.springframework.util.StringUtils.trimAllWhitespace; - import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; @@ -35,6 +30,10 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import static org.springframework.util.StringUtils.delimitedListToStringArray; +import static org.springframework.util.StringUtils.hasText; +import static org.springframework.util.StringUtils.trimAllWhitespace; + /** * Http Utilities class * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java index 3b8257b1..bc093720 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboProtocolConfigSupplier.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,9 +15,6 @@ */ package com.alibaba.cloud.dubbo.metadata; -import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; -import static org.springframework.util.CollectionUtils.isEmpty; - import java.util.Collection; import java.util.Iterator; import java.util.function.Supplier; @@ -27,6 +23,9 @@ import org.apache.dubbo.config.ProtocolConfig; import org.springframework.beans.factory.ObjectProvider; +import static org.apache.dubbo.common.constants.CommonConstants.DEFAULT_PROTOCOL; +import static org.springframework.util.CollectionUtils.isEmpty; + /** * Dubbo's {@link ProtocolConfig} {@link Supplier} * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java index b02094b9..b4d6b618 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboRestServiceMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java index 6ce0e24c..98ccbc53 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/DubboTransportedMethodMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java index 5fbc3d20..69dbd524 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java index 56b79b27..1e26c28e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/MethodParameterMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java index 6f2a88f3..1d847d18 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RequestMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,9 +15,6 @@ */ package com.alibaba.cloud.dubbo.metadata; -import static com.alibaba.cloud.dubbo.http.util.HttpUtils.normalizePath; -import static org.springframework.http.MediaType.parseMediaTypes; - import java.util.ArrayList; import java.util.Collection; import java.util.Collections; @@ -31,16 +27,18 @@ import java.util.Objects; import java.util.Set; import java.util.SortedMap; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; +import feign.RequestTemplate; + import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import com.fasterxml.jackson.annotation.JsonIgnore; -import com.fasterxml.jackson.annotation.JsonProperty; - -import feign.RequestTemplate; +import static com.alibaba.cloud.dubbo.http.util.HttpUtils.normalizePath; +import static org.springframework.http.MediaType.parseMediaTypes; /** * Request Metadata @@ -74,8 +72,7 @@ public class RequestMetadata { } /** - * Get the best matched {@link RequestMetadata} via specified {@link RequestMetadata} - * + * Get the best matched {@link RequestMetadata} via specified {@link RequestMetadata}. * @param requestMetadataMap the source of {@link NavigableMap} * @param requestMetadata the match object * @return if not matched, return null diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java index fceec4e6..3846b629 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/RestMethodMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -22,13 +21,13 @@ import java.util.List; import java.util.Map; import java.util.Objects; -import org.springframework.core.ResolvableType; - import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; +import org.springframework.core.ResolvableType; + /** - * Method Request Metadata + * Method Request Metadata. * * @author Mercy */ diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java index e0c93d69..963edb09 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/ServiceRestMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -22,7 +21,7 @@ import java.util.Set; import com.fasterxml.jackson.annotation.JsonInclude; /** - * Service Rest Metadata + * Service Rest Metadata. * * @author Mercy * @see RestMethodMetadata diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java index 2c48be6d..f8f04c97 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/DubboServiceMetadataRepository.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,20 +15,6 @@ */ package com.alibaba.cloud.dubbo.metadata.repository; -import static com.alibaba.cloud.dubbo.env.DubboCloudProperties.ALL_DUBBO_SERVICES; -import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; -import static java.lang.String.format; -import static java.lang.String.valueOf; -import static java.util.Collections.emptyList; -import static java.util.Collections.emptySet; -import static java.util.Collections.unmodifiableList; -import static java.util.Collections.unmodifiableMap; -import static java.util.Collections.unmodifiableSet; -import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.springframework.util.CollectionUtils.isEmpty; -import static org.springframework.util.StringUtils.hasText; - import java.util.Collections; import java.util.LinkedHashMap; import java.util.LinkedHashSet; @@ -42,10 +27,23 @@ import java.util.stream.Stream; import javax.annotation.PostConstruct; -import org.apache.dubbo.common.URL; +import com.alibaba.cloud.dubbo.env.DubboCloudProperties; +import com.alibaba.cloud.dubbo.http.matcher.RequestMetadataMatcher; +import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; +import com.alibaba.cloud.dubbo.metadata.RequestMetadata; +import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; +import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent; +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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; @@ -60,18 +58,19 @@ import org.springframework.stereotype.Repository; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; -import com.alibaba.cloud.dubbo.env.DubboCloudProperties; -import com.alibaba.cloud.dubbo.http.matcher.RequestMetadataMatcher; -import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; -import com.alibaba.cloud.dubbo.metadata.RequestMetadata; -import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; -import com.alibaba.cloud.dubbo.registry.event.SubscribedServicesChangedEvent; -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 static com.alibaba.cloud.dubbo.env.DubboCloudProperties.ALL_DUBBO_SERVICES; +import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; +import static java.lang.String.format; +import static java.lang.String.valueOf; +import static java.util.Collections.emptyList; +import static java.util.Collections.emptySet; +import static java.util.Collections.unmodifiableList; +import static java.util.Collections.unmodifiableMap; +import static java.util.Collections.unmodifiableSet; +import static org.apache.dubbo.common.constants.CommonConstants.APPLICATION_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.springframework.util.CollectionUtils.isEmpty; +import static org.springframework.util.StringUtils.hasText; /** * Dubbo Service Metadata {@link Repository} @@ -89,13 +88,13 @@ public class DubboServiceMetadataRepository /** * The {@link URL URLs} property name of {@link DubboMetadataService} : - * "dubbo.metadata-service.urls" + * "dubbo.metadata-service.urls". */ public static final String DUBBO_METADATA_SERVICE_URLS_PROPERTY_NAME = DUBBO_METADATA_SERVICE_PREFIX + "urls"; /** - * The {@link String#format(String, Object...) pattern} of dubbo protocols port + * The {@link String#format(String, Object...) pattern} of dubbo protocols port. */ public static final String DUBBO_PROTOCOLS_PORT_PROPERTY_NAME_PATTERN = "dubbo.protocols.%s.port"; @@ -104,17 +103,19 @@ public class DubboServiceMetadataRepository private final ObjectMapper objectMapper = new ObjectMapper(); /** - * Monitor object for synchronization + * Monitor object for synchronization. */ private final Object monitor = new Object(); + /** - * A {@link Set} of service names that had been initialized + * A {@link Set} of service names that had been initialized. */ private final Set initializedServices = new LinkedHashSet<>(); + /** * All exported {@link URL urls} {@link Map} whose key is the return value of * {@link URL#getServiceKey()} method and value is the {@link List} of {@link URL - * URLs} + * URLs}. */ private final MultiValueMap allExportedURLs = new LinkedMultiValueMap<>(); @@ -123,7 +124,7 @@ public class DubboServiceMetadataRepository /** * The subscribed {@link URL urls} {@link Map} of {@link DubboMetadataService}, whose * key is the return value of {@link URL#getServiceKey()} method and value is the - * {@link List} of {@link URL URLs} + * {@link List} of {@link URL URLs}. */ private final MultiValueMap subscribedDubboMetadataServiceURLs = new LinkedMultiValueMap<>(); @@ -146,8 +147,10 @@ public class DubboServiceMetadataRepository // =================================== REST Metadata // ================================== // private volatile Set subscribedServices = emptySet(); + /** - * Key is application name Value is Map + * Key is application name Value is Map<RequestMetadata, + * DubboRestServiceMetadata>. */ private Map> dubboRestServiceMetadataRepository = newHashMap(); @@ -166,6 +169,9 @@ public class DubboServiceMetadataRepository @Autowired private DiscoveryClient discoveryClient; + @Autowired + private MetadataServiceInstanceSelector metadataServiceInstanceSelector; + @Autowired private JSONUtils jsonUtils; @@ -200,9 +206,8 @@ public class DubboServiceMetadataRepository } /** - * Initialize {@link #subscribedServices the subscribed services} - * - * @return + * Initialize {@link #subscribedServices the subscribed services}. + * @return stream of subscribed services */ @PostConstruct public Stream initSubscribedServices() { @@ -254,7 +259,7 @@ public class DubboServiceMetadataRepository } /** - * Initialize the metadata + * Initialize the metadata. */ private void initializeMetadata() { doGetSubscribedServices().forEach(this::initializeMetadata); @@ -264,7 +269,8 @@ public class DubboServiceMetadataRepository } /** - * Initialize the metadata of Dubbo Services + * Initialize the metadata of Dubbo Services. + * @param serviceName service of name */ public void initializeMetadata(String serviceName) { synchronized (monitor) { @@ -282,9 +288,7 @@ public class DubboServiceMetadataRepository serviceName); } - // Keep the order in following invocations initSubscribedDubboMetadataService(serviceName); - initDubboRestServiceMetadataRepository(serviceName); // mark this service name having been initialized initializedServices.add(serviceName); } @@ -292,8 +296,17 @@ public class DubboServiceMetadataRepository } /** - * Get the metadata {@link Map} of {@link DubboMetadataService} - * + * Remove the metadata of Dubbo Services if no there is no service instance. + * @param serviceName the service name + */ + public void removeInitializedService(String serviceName) { + synchronized (monitor) { + initializedServices.remove(serviceName); + } + } + + /** + * Get the metadata {@link Map} of {@link DubboMetadataService}. * @return non-null read-only {@link Map} */ public Map getDubboMetadataServiceMetadata() { @@ -333,8 +346,7 @@ public class DubboServiceMetadataRepository } /** - * Get the property name of Dubbo Protocol - * + * Get the property name of Dubbo Protocol. * @param protocol Dubbo Protocol * @return non-null */ @@ -343,8 +355,7 @@ public class DubboServiceMetadataRepository } /** - * Publish the {@link Set} of {@link ServiceRestMetadata} - * + * Publish the {@link Set} of {@link ServiceRestMetadata}. * @param serviceRestMetadataSet the {@link Set} of {@link ServiceRestMetadata} */ public void publishServiceRestMetadata( @@ -357,8 +368,7 @@ public class DubboServiceMetadataRepository } /** - * Get the {@link Set} of {@link ServiceRestMetadata} - * + * Get the {@link Set} of {@link ServiceRestMetadata}. * @return non-null read-only {@link Set} */ public Set getServiceRestMetadata() { @@ -387,10 +397,9 @@ public class DubboServiceMetadataRepository } /** - * The specified service is subscribe or not - * + * The specified service is subscribe or not. * @param serviceName the service name - * @return + * @return subscribe or not */ public boolean isSubscribedService(String serviceName) { return doGetSubscribedServices().contains(serviceName); @@ -422,7 +431,6 @@ public class DubboServiceMetadataRepository /** * Get all exported {@link URL urls}. - * * @return non-null read-only */ public Map> getAllExportedUrls() { @@ -430,8 +438,7 @@ public class DubboServiceMetadataRepository } /** - * Get all exported {@link URL#getServiceKey() service keys} - * + * Get all exported {@link URL#getServiceKey() service keys}. * @return non-null read-only */ public Set getAllServiceKeys() { @@ -440,8 +447,7 @@ public class DubboServiceMetadataRepository /** * Get the {@link URL urls} that {@link DubboMetadataService} exported by the - * specified {@link ServiceInstance} - * + * specified {@link ServiceInstance}. * @param serviceInstance {@link ServiceInstance} * @return the mutable {@link URL urls} */ @@ -466,8 +472,7 @@ public class DubboServiceMetadataRepository } /** - * Initialize the specified service's {@link ServiceRestMetadata} - * + * Initialize the specified service's {@link ServiceRestMetadata}. * @param serviceName the service name */ protected void initDubboRestServiceMetadataRepository(String serviceName) { @@ -512,8 +517,7 @@ public class DubboServiceMetadataRepository /** * Get a {@link DubboRestServiceMetadata} by the specified service name if - * {@link RequestMetadata} matched - * + * {@link RequestMetadata} matched. * @param serviceName service name * @param requestMetadata {@link RequestMetadata} to be matched * @return {@link DubboRestServiceMetadata} if matched, or null @@ -565,7 +569,7 @@ public class DubboServiceMetadataRepository if (object == null) { if (logger.isWarnEnabled()) { logger.warn( - "DubboServiceMetadata can't be found in the Spring application [%s] and %s", + "DubboServiceMetadata can't be found in the Spring application [{}] and {}", serviceName, requestMetadata); } } @@ -609,7 +613,7 @@ public class DubboServiceMetadataRepository } protected void initSubscribedDubboMetadataService(String serviceName) { - discoveryClient.getInstances(serviceName).stream().findAny() + metadataServiceInstanceSelector.choose(discoveryClient.getInstances(serviceName)) .map(this::getDubboMetadataServiceURLs) .ifPresent(dubboMetadataServiceURLs -> { dubboMetadataServiceURLs.forEach(dubboMetadataServiceURL -> { @@ -625,6 +629,7 @@ public class DubboServiceMetadataRepository } }); }); + initDubboRestServiceMetadataRepository(serviceName); } private void initSubscribedDubboMetadataServiceURL(URL dubboMetadataServiceURL) { @@ -640,9 +645,15 @@ public class DubboServiceMetadataRepository dubboMetadataConfigServiceProxy.initProxy(serviceName, version); } + public void removeMetadata(String serviceName) { + dubboRestServiceMetadataRepository.remove(serviceName); + subscribedDubboMetadataServiceURLs.remove(serviceName); + } + @Override public void setApplicationEventPublisher( ApplicationEventPublisher applicationEventPublisher) { this.applicationEventPublisher = applicationEventPublisher; } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java new file mode 100644 index 00000000..1ba6fb44 --- /dev/null +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/repository/MetadataServiceInstanceSelector.java @@ -0,0 +1,38 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.metadata.repository; + +import java.util.List; +import java.util.Optional; + +import org.springframework.cloud.client.ServiceInstance; + +/** + * metadata service instance selector. + * + * @author liuxx + */ +public interface MetadataServiceInstanceSelector { + + /** + * choose a service instance to get metadata. + * @param serviceInstances all service instance + * @return the service instance to get metadata + */ + 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-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java index ce5c0d30..dfb1b97c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboServiceBeanMetadataResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -27,6 +26,13 @@ import java.util.Set; import java.util.stream.Collectors; 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; +import feign.Util; import org.apache.dubbo.common.URL; import org.apache.dubbo.config.spring.ServiceBean; @@ -36,14 +42,6 @@ import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.SmartInitializingSingleton; import org.springframework.util.ClassUtils; -import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; -import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; - -import feign.Contract; -import feign.Feign; -import feign.MethodMetadata; -import feign.Util; - /** * The metadata resolver for {@link Feign} for {@link ServiceBean Dubbo Service Bean} in * the provider side. @@ -61,7 +59,7 @@ public class DubboServiceBeanMetadataResolver private ClassLoader classLoader; /** - * Feign Contracts + * Feign Contracts. */ private Collection contracts; @@ -155,9 +153,8 @@ public class DubboServiceBeanMetadataResolver * Select feign contract methods *

* extract some code from - * {@link Contract.BaseContract#parseAndValidatateMetadata(java.lang.Class)} - * - * @param targetType + * {@link Contract.BaseContract#parseAndValidatateMetadata(java.lang.Class)}. + * @param targetType class of type * @return non-null */ private List selectFeignContractMethods(Class targetType) { diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java index aafd94ca..40569b31 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedAttributesResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,14 +15,14 @@ */ package com.alibaba.cloud.dubbo.metadata.resolver; -import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; - import java.util.LinkedHashMap; import java.util.Map; +import com.alibaba.cloud.dubbo.annotation.DubboTransported; + import org.springframework.core.env.PropertyResolver; -import com.alibaba.cloud.dubbo.annotation.DubboTransported; +import static org.springframework.core.annotation.AnnotationUtils.getAnnotationAttributes; /** * {@link DubboTransported} annotation attributes resolver diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java index 8ef05379..16004926 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,17 +15,12 @@ */ package com.alibaba.cloud.dubbo.metadata.resolver; -import static feign.Feign.configKey; - import java.lang.reflect.Method; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; -import org.springframework.core.annotation.AnnotationUtils; -import org.springframework.core.env.PropertyResolver; - import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.metadata.DubboTransportedMethodMetadata; import com.alibaba.cloud.dubbo.metadata.MethodMetadata; @@ -34,6 +28,11 @@ import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import feign.Contract; +import org.springframework.core.annotation.AnnotationUtils; +import org.springframework.core.env.PropertyResolver; + +import static feign.Feign.configKey; + /** * {@link MethodMetadata} Resolver for the {@link DubboTransported} annotated classes or * methods in client side. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java index 3938d8b8..114b7a1f 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/metadata/resolver/MetadataResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -18,31 +17,30 @@ package com.alibaba.cloud.dubbo.metadata.resolver; import java.util.Set; -import org.apache.dubbo.config.spring.ServiceBean; - import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; +import org.apache.dubbo.config.spring.ServiceBean; + /** - * The REST metadata resolver + * The REST metadata resolver. * * @author Mercy */ public interface MetadataResolver { /** - * Resolve the {@link ServiceRestMetadata} {@link Set set} from {@link ServiceBean} - * + * Resolve the {@link ServiceRestMetadata} {@link Set set} from {@link ServiceBean}. * @param serviceBean {@link ServiceBean} * @return non-null {@link Set} */ Set resolveServiceRestMetadata(ServiceBean serviceBean); /** - * Resolve {@link RestMethodMetadata} {@link Set set} from {@link Class target type} - * + * Resolve {@link RestMethodMetadata} {@link Set set} from {@link Class target type}. * @param targetType {@link Class target type} * @return non-null {@link Set} */ Set resolveMethodRestMetadata(Class targetType); + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java index 3242dc85..c4d6c0ea 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/DubboInvocationHandler.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,19 +15,19 @@ */ package com.alibaba.cloud.dubbo.openfeign; -import static org.apache.dubbo.common.utils.PojoUtils.realize; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; 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; -import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContext; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; +import static org.apache.dubbo.common.utils.PojoUtils.realize; /** * Dubbo {@link GenericService} for {@link InvocationHandler} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java index e2fb23bf..6c3a957b 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/FeignMethodMetadata.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -18,10 +17,10 @@ package com.alibaba.cloud.dubbo.openfeign; import java.lang.reflect.Method; -import org.apache.dubbo.rpc.service.GenericService; - import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; +import org.apache.dubbo.rpc.service.GenericService; + /** * Feign {@link Method} Metadata * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java index e1d0c9d9..da173a07 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterBeanPostProcessor.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,20 +15,20 @@ */ package com.alibaba.cloud.dubbo.openfeign; -import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME; -import static java.lang.reflect.Proxy.newProxyInstance; -import static org.springframework.util.ClassUtils.getUserClass; -import static org.springframework.util.ClassUtils.isPresent; -import static org.springframework.util.ClassUtils.resolveClassName; +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.config.BeanPostProcessor; import org.springframework.core.env.Environment; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceExecutionContextFactory; -import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import static com.alibaba.cloud.dubbo.autoconfigure.DubboOpenFeignAutoConfiguration.TARGETER_CLASS_NAME; +import static java.lang.reflect.Proxy.newProxyInstance; +import static org.springframework.util.ClassUtils.getUserClass; +import static org.springframework.util.ClassUtils.isPresent; +import static org.springframework.util.ClassUtils.resolveClassName; /** * org.springframework.cloud.openfeign.Targeter {@link BeanPostProcessor} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java index c2b335d5..3e99ac77 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/openfeign/TargeterInvocationHandler.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,21 +15,12 @@ */ package com.alibaba.cloud.dubbo.openfeign; -import static java.lang.reflect.Proxy.newProxyInstance; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.HashMap; import java.util.Map; -import org.apache.dubbo.rpc.service.GenericService; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.openfeign.FeignContext; -import org.springframework.core.env.Environment; - import com.alibaba.cloud.dubbo.annotation.DubboTransported; import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; import com.alibaba.cloud.dubbo.metadata.DubboTransportedMethodMetadata; @@ -44,6 +34,14 @@ import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; import feign.Contract; import feign.Target; +import org.apache.dubbo.rpc.service.GenericService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.cloud.openfeign.FeignContext; +import org.springframework.core.env.Environment; + +import static java.lang.reflect.Proxy.newProxyInstance; /** * org.springframework.cloud.openfeign.Targeter {@link InvocationHandler} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java index 922553ab..1299980a 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/AbstractSpringCloudRegistry.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -14,8 +13,36 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry; +import java.util.Collection; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.function.Function; +import java.util.stream.Collectors; + +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import com.alibaba.cloud.dubbo.service.DubboMetadataService; +import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; +import com.alibaba.cloud.dubbo.util.JSONUtils; +import org.apache.dubbo.common.URL; +import org.apache.dubbo.registry.NotifyListener; +import org.apache.dubbo.registry.RegistryFactory; +import org.apache.dubbo.registry.support.FailbackRegistry; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.cloud.client.ServiceInstance; +import org.springframework.cloud.client.discovery.DiscoveryClient; +import org.springframework.context.ApplicationListener; +import org.springframework.context.ConfigurableApplicationContext; +import org.springframework.util.CollectionUtils; + import static java.util.Arrays.asList; import static java.util.Collections.emptyList; import static org.apache.dubbo.common.URLBuilder.from; @@ -28,57 +55,31 @@ import static org.apache.dubbo.common.constants.RegistryConstants.EMPTY_PROTOCOL import static org.apache.dubbo.registry.Constants.ADMIN_PROTOCOL; import static org.springframework.util.StringUtils.hasText; -import java.util.Collection; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.function.Function; -import java.util.stream.Collectors; - -import org.apache.dubbo.common.URL; -import org.apache.dubbo.registry.NotifyListener; -import org.apache.dubbo.registry.RegistryFactory; -import org.apache.dubbo.registry.support.FailbackRegistry; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; -import org.springframework.context.ApplicationListener; -import org.springframework.context.ConfigurableApplicationContext; -import org.springframework.util.CollectionUtils; - -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.registry.event.ServiceInstancesChangedEvent; -import com.alibaba.cloud.dubbo.service.DubboMetadataService; -import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; -import com.alibaba.cloud.dubbo.util.JSONUtils; - /** * Abstract Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration - * abstraction, whose protocol is "spring-cloud" + * abstraction, whose protocol is "spring-cloud". * * @author Mercy */ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { /** - * The parameter name of {@link #servicesLookupInterval} + * The parameter name of {@link #servicesLookupInterval}. */ public static final String SERVICES_LOOKUP_INTERVAL_PARAM_NAME = "dubbo.services.lookup.interval"; protected static final String DUBBO_METADATA_SERVICE_CLASS_NAME = DubboMetadataService.class .getName(); + /** - * Caches the IDs of {@link ApplicationListener} + * Caches the IDs of {@link ApplicationListener}. */ private static final Set registerListeners = new HashSet<>(); protected final Logger logger = LoggerFactory.getLogger(getClass()); /** - * The interval in second of lookup service names(only for Dubbo-OPS) + * The interval in second of lookup service names(only for Dubbo-OPS). */ private final long servicesLookupInterval; @@ -90,12 +91,15 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { private final JSONUtils jsonUtils; + private final DubboGenericServiceFactory dubboGenericServiceFactory; + private final ConfigurableApplicationContext applicationContext; public AbstractSpringCloudRegistry(URL url, DiscoveryClient discoveryClient, DubboServiceMetadataRepository dubboServiceMetadataRepository, DubboMetadataServiceProxy dubboMetadataConfigServiceProxy, - JSONUtils jsonUtils, ConfigurableApplicationContext applicationContext) { + JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory, + ConfigurableApplicationContext applicationContext) { super(url); this.servicesLookupInterval = url .getParameter(SERVICES_LOOKUP_INTERVAL_PARAM_NAME, 60L); @@ -103,6 +107,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { this.repository = dubboServiceMetadataRepository; this.dubboMetadataConfigServiceProxy = dubboMetadataConfigServiceProxy; this.jsonUtils = jsonUtils; + this.dubboGenericServiceFactory = dubboGenericServiceFactory; this.applicationContext = applicationContext; } @@ -129,8 +134,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { } /** - * The sub-type should implement to register - * + * The sub-type should implement to register. * @param url {@link URL} */ protected abstract void doRegister0(URL url); @@ -144,8 +148,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { } /** - * The sub-type should implement to unregister - * + * The sub-type should implement to unregister. * @param url {@link URL} */ protected abstract void doUnregister0(URL url); @@ -173,8 +176,7 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { /** * Register a {@link ApplicationListener listener} for - * {@link ServiceInstancesChangedEvent} - * + * {@link ServiceInstancesChangedEvent}. * @param url {@link URL} * @param listener {@link NotifyListener} */ @@ -215,6 +217,34 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { generateId(url), serviceName); } + List allSubscribedURLs = new LinkedList<>(); + + Collection serviceInstances = serviceInstancesFunction + .apply(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 " + + "available , please make sure the further impact", + serviceName, url.getServiceKey()); + } + /** + * URLs with {@link RegistryConstants#EMPTY_PROTOCOL} + */ + allSubscribedURLs.addAll(emptyURLs(url)); + if (logger.isDebugEnabled()) { + logger.debug("The subscribed URL[{}] will notify all URLs : {}", url, + allSubscribedURLs); + } + listener.notify(allSubscribedURLs); + return; + } + DubboMetadataService dubboMetadataService = dubboMetadataConfigServiceProxy .getProxy(serviceName); @@ -239,50 +269,30 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { return; } - Collection serviceInstances = serviceInstancesFunction - .apply(serviceName); + List exportedURLs = getExportedURLs(dubboMetadataService, url); - List allSubscribedURLs = new LinkedList<>(); - - if (CollectionUtils.isEmpty(serviceInstances)) { - if (logger.isWarnEnabled()) { - logger.warn( - "There is no instance from service[name : {}], and then Dubbo Service[key : {}] will not be " - + "available , please make sure the further impact", - serviceName, url.getServiceKey()); - } - /** - * URLs with {@link RegistryConstants#EMPTY_PROTOCOL} - */ - allSubscribedURLs.addAll(emptyURLs(url)); - } - else { - List exportedURLs = getExportedURLs(dubboMetadataService, url); - - for (URL exportedURL : exportedURLs) { - String protocol = exportedURL.getProtocol(); - List subscribedURLs = new LinkedList<>(); - serviceInstances.forEach(serviceInstance -> { - Integer port = repository.getDubboProtocolPort(serviceInstance, - protocol); - String host = serviceInstance.getHost(); - if (port == null) { - if (logger.isWarnEnabled()) { - logger.warn( - "The protocol[{}] port of Dubbo service instance[host : {}] " - + "can't be resolved", - protocol, host); - } + for (URL exportedURL : exportedURLs) { + String protocol = exportedURL.getProtocol(); + List subscribedURLs = new LinkedList<>(); + serviceInstances.forEach(serviceInstance -> { + Integer port = repository.getDubboProtocolPort(serviceInstance, protocol); + String host = serviceInstance.getHost(); + if (port == null) { + if (logger.isWarnEnabled()) { + logger.warn( + "The protocol[{}] port of Dubbo service instance[host : {}] " + + "can't be resolved", + protocol, host); } - else { - URL subscribedURL = new URL(protocol, host, port, - exportedURL.getParameters()); - subscribedURLs.add(subscribedURL); - } - }); + } + else { + URL subscribedURL = new URL(protocol, host, port, + exportedURL.getParameters()); + subscribedURLs.add(subscribedURL); + } + }); - allSubscribedURLs.addAll(subscribedURLs); - } + allSubscribedURLs.addAll(subscribedURLs); } if (logger.isDebugEnabled()) { @@ -345,8 +355,8 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { @Override public final void doUnsubscribe(URL url, NotifyListener listener) { - if (isAdminURL(url)) { - } + // if (isAdminURL(url)) { + // } } @Override @@ -361,4 +371,5 @@ public abstract class AbstractSpringCloudRegistry extends FailbackRegistry { protected boolean isDubboMetadataServiceURL(URL url) { return DUBBO_METADATA_SERVICE_CLASS_NAME.equals(url.getServiceInterface()); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java index 8789e80f..f08f7df9 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DelegatingRegistration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -32,7 +31,7 @@ class DelegatingRegistration implements Registration { private final ServiceInstance delegate; - public DelegatingRegistration(ServiceInstance delegate) { + DelegatingRegistration(ServiceInstance delegate) { this.delegate = delegate; } @@ -70,4 +69,5 @@ class DelegatingRegistration implements Registration { public String getScheme() { return delegate.getScheme(); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java index 33ed52d5..3131f229 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/DubboServiceRegistrationEventPublishingAspect.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,17 +15,18 @@ */ 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; + import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; -import com.alibaba.cloud.dubbo.registry.event.ServiceInstancePreRegisteredEvent; -import com.alibaba.cloud.dubbo.registry.event.ServiceInstanceRegisteredEvent; - /** * Dubbo Service Registration Event-Publishing Aspect * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java index be9039ae..fe732dab 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistry.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -14,21 +13,22 @@ * 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.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; +import com.alibaba.cloud.dubbo.util.JSONUtils; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.RegistryFactory; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.context.ConfigurableApplicationContext; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; -import com.alibaba.cloud.dubbo.util.JSONUtils; - /** * Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose - * protocol is "spring-cloud" + * protocol is "spring-cloud". * * @author Mercy */ @@ -39,9 +39,11 @@ public class SpringCloudRegistry extends AbstractSpringCloudRegistry { public SpringCloudRegistry(URL url, DiscoveryClient discoveryClient, DubboServiceMetadataRepository dubboServiceMetadataRepository, DubboMetadataServiceProxy dubboMetadataConfigServiceProxy, - JSONUtils jsonUtils, ConfigurableApplicationContext applicationContext) { + JSONUtils jsonUtils, DubboGenericServiceFactory dubboGenericServiceFactory, + ConfigurableApplicationContext applicationContext) { super(url, discoveryClient, dubboServiceMetadataRepository, - dubboMetadataConfigServiceProxy, jsonUtils, applicationContext); + dubboMetadataConfigServiceProxy, jsonUtils, dubboGenericServiceFactory, + applicationContext); this.dubboServiceMetadataRepository = dubboServiceMetadataRepository; } @@ -54,4 +56,5 @@ public class SpringCloudRegistry extends AbstractSpringCloudRegistry { protected void doUnregister0(URL url) { dubboServiceMetadataRepository.unexportURL(url); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java index ca0e1dc1..c3a9fe89 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/SpringCloudRegistryFactory.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -14,10 +13,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.alibaba.cloud.dubbo.registry; -import static java.lang.System.getProperty; - +import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; +import com.alibaba.cloud.dubbo.service.DubboGenericServiceFactory; +import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; +import com.alibaba.cloud.dubbo.util.JSONUtils; import org.apache.dubbo.common.URL; import org.apache.dubbo.registry.Registry; import org.apache.dubbo.registry.RegistryFactory; @@ -25,13 +27,11 @@ import org.apache.dubbo.registry.RegistryFactory; import org.springframework.cloud.client.discovery.DiscoveryClient; import org.springframework.context.ConfigurableApplicationContext; -import com.alibaba.cloud.dubbo.metadata.repository.DubboServiceMetadataRepository; -import com.alibaba.cloud.dubbo.service.DubboMetadataServiceProxy; -import com.alibaba.cloud.dubbo.util.JSONUtils; +import static java.lang.System.getProperty; /** * Dubbo {@link RegistryFactory} uses Spring Cloud Service Registration abstraction, whose - * protocol is "spring-cloud" + * protocol is "spring-cloud". * * @author Mercy * @see RegistryFactory @@ -39,8 +39,14 @@ import com.alibaba.cloud.dubbo.util.JSONUtils; */ public class SpringCloudRegistryFactory implements RegistryFactory { + /** + * Spring Cloud Protocol. + */ public static String PROTOCOL = "spring-cloud"; + /** + * Spring Cloud Address. + */ public static String ADDRESS = "localhost"; private static String SERVICES_LOOKUP_SCHEDULER_THREAD_NAME_PREFIX = getProperty( @@ -57,6 +63,8 @@ public class SpringCloudRegistryFactory implements RegistryFactory { private JSONUtils jsonUtils; + private DubboGenericServiceFactory dubboGenericServiceFactory; + private volatile boolean initialized = false; public SpringCloudRegistryFactory() { @@ -77,6 +85,8 @@ public class SpringCloudRegistryFactory implements RegistryFactory { this.dubboMetadataConfigServiceProxy = applicationContext .getBean(DubboMetadataServiceProxy.class); this.jsonUtils = applicationContext.getBean(JSONUtils.class); + this.dubboGenericServiceFactory = applicationContext + .getBean(DubboGenericServiceFactory.class); } @Override @@ -84,6 +94,7 @@ public class SpringCloudRegistryFactory implements RegistryFactory { init(); return new SpringCloudRegistry(url, discoveryClient, dubboServiceMetadataRepository, dubboMetadataConfigServiceProxy, - jsonUtils, applicationContext); + jsonUtils, dubboGenericServiceFactory, applicationContext); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java index 1821ebda..fee5a742 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancePreRegisteredEvent.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java index 0e5a0a2a..7c6c0742 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstanceRegisteredEvent.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java index 2123b485..2f997ef0 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/ServiceInstancesChangedEvent.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,8 +15,6 @@ */ package com.alibaba.cloud.dubbo.registry.event; -import static java.util.Collections.unmodifiableCollection; - import java.util.Collection; import org.springframework.cloud.client.ServiceInstance; @@ -25,6 +22,8 @@ import org.springframework.context.ApplicationEvent; import org.springframework.context.event.ApplicationEventMulticaster; import org.springframework.context.event.SimpleApplicationEventMulticaster; +import static java.util.Collections.unmodifiableCollection; + /** * An event raised after the {@link ServiceInstance instances} of one service has been * changed. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java index 384d8a1c..9ad31d16 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/registry/event/SubscribedServicesChangedEvent.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -39,7 +38,6 @@ public class SubscribedServicesChangedEvent extends ApplicationEvent { /** * Create a new ApplicationEvent. - * * @param source the object on which the event initially occurred (never {@code null}) * @param oldSubscribedServices the subscribed services before changed * @param newSubscribedServices the subscribed services after changed diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java index 53c7fd6d..8be35973 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContext.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java index 8d61b2fd..da94b258 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceExecutionContextFactory.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -23,15 +22,15 @@ import java.util.Map; import javax.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.annotation.AnnotationAwareOrderComparator; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; import com.alibaba.cloud.dubbo.metadata.MethodMetadata; import com.alibaba.cloud.dubbo.metadata.MethodParameterMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; import com.alibaba.cloud.dubbo.service.parameter.DubboGenericServiceParameterResolver; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.annotation.AnnotationAwareOrderComparator; + /** * {@link DubboGenericServiceExecutionContext} Factory * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java index b96ce36c..2acffbd2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboGenericServiceFactory.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -14,31 +13,31 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -package com.alibaba.cloud.dubbo.service; -import static java.util.Collections.emptyMap; -import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; -import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; -import static org.springframework.util.StringUtils.commaDelimitedListToStringArray; +package com.alibaba.cloud.dubbo.service; import java.beans.PropertyEditorSupport; import java.util.Collection; +import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.annotation.PreDestroy; +import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; +import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; import org.apache.dubbo.common.URL; import org.apache.dubbo.common.utils.CollectionUtils; import org.apache.dubbo.config.RegistryConfig; import org.apache.dubbo.config.spring.ReferenceBean; import org.apache.dubbo.rpc.service.GenericService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.MutablePropertyValues; import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; @@ -46,11 +45,13 @@ import org.springframework.beans.propertyeditors.StringTrimmerEditor; import org.springframework.util.StringUtils; import org.springframework.validation.DataBinder; -import com.alibaba.cloud.dubbo.metadata.DubboRestServiceMetadata; -import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; +import static java.util.Collections.emptyMap; +import static org.apache.dubbo.common.constants.CommonConstants.GROUP_KEY; +import static org.apache.dubbo.common.constants.CommonConstants.VERSION_KEY; +import static org.springframework.util.StringUtils.commaDelimitedListToStringArray; /** - * Dubbo {@link GenericService} Factory + * Dubbo {@link GenericService} Factory. * * @author Mercy */ @@ -58,7 +59,7 @@ public class DubboGenericServiceFactory { private final Logger logger = LoggerFactory.getLogger(getClass()); - private final ConcurrentMap> cache = new ConcurrentHashMap<>(); + private final ConcurrentMap> cache = new ConcurrentHashMap<>(); @Autowired private ObjectProvider> registryConfigs; @@ -97,12 +98,13 @@ public class DubboGenericServiceFactory { Integer key = Objects.hash(interfaceName, version, group, dubboTranslatedAttributes); - return cache.computeIfAbsent(key, k -> { + return cache.computeIfAbsent(group + key, k -> { ReferenceBean referenceBean = new ReferenceBean<>(); referenceBean.setGeneric(true); referenceBean.setInterface(interfaceName); referenceBean.setVersion(version); referenceBean.setGroup(group); + referenceBean.setCheck(false); bindReferenceBean(referenceBean, dubboTranslatedAttributes); return referenceBean; }); @@ -150,7 +152,17 @@ public class DubboGenericServiceFactory { @PreDestroy public void destroy() { destroyReferenceBeans(); - cache.values(); + cache.clear(); + } + + public synchronized void destroy(String serviceName) { + Set removeGroups = new HashSet<>(cache.keySet()); + for (String key : removeGroups) { + if (key.contains(serviceName)) { + ReferenceBean referenceBean = cache.remove(key); + referenceBean.destroy(); + } + } } private void destroyReferenceBeans() { diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java index 134bb028..6c766c59 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataService.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -20,11 +19,11 @@ import java.util.List; 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; -import com.alibaba.cloud.dubbo.metadata.ServiceRestMetadata; - /** * Dubbo Metadata Service is a core interface for service subscribers, it must keep the * stable of structure in every evolution , makes sure all subscribers' compatibility. diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java index d8a248e2..87654159 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceExporter.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -25,9 +24,9 @@ import org.apache.dubbo.common.URL; import org.apache.dubbo.config.ApplicationConfig; import org.apache.dubbo.config.ProtocolConfig; import org.apache.dubbo.config.ServiceConfig; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java index ca4b05f6..d9bc957e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceInvocationHandler.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -21,12 +20,11 @@ import java.lang.reflect.Method; import java.util.stream.Stream; import org.apache.dubbo.rpc.service.GenericService; - import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** - * {@link DubboMetadataService} {@link InvocationHandler} + * {@link DubboMetadataService} {@link InvocationHandler}. * * @author Mercy */ @@ -36,7 +34,7 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler { private final GenericService genericService; - public DubboMetadataServiceInvocationHandler(String serviceName, String version, + DubboMetadataServiceInvocationHandler(String serviceName, String version, DubboGenericServiceFactory dubboGenericServiceFactory) { this.genericService = dubboGenericServiceFactory.create(serviceName, DubboMetadataService.class, version); @@ -62,4 +60,5 @@ class DubboMetadataServiceInvocationHandler implements InvocationHandler { return Stream.of(parameterTypes).map(Class::getName) .toArray(length -> new String[length]); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java index 21c019c2..fbe283f2 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/DubboMetadataServiceProxy.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,23 +15,25 @@ */ package com.alibaba.cloud.dubbo.service; -import static java.lang.reflect.Proxy.newProxyInstance; - import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.DisposableBean; +import static java.lang.reflect.Proxy.newProxyInstance; + /** - * The proxy of {@link DubboMetadataService} + * The proxy of {@link DubboMetadataService}. * * @author Mercy */ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, DisposableBean { private final DubboGenericServiceFactory dubboGenericServiceFactory; + private final Map dubboMetadataServiceCache = new ConcurrentHashMap<>(); + private ClassLoader classLoader; public DubboMetadataServiceProxy( @@ -41,8 +42,7 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab } /** - * Initializes {@link DubboMetadataService}'s Proxy - * + * Initializes {@link DubboMetadataService}'s Proxy. * @param serviceName the service name * @param version the service version * @return a {@link DubboMetadataService} proxy @@ -53,8 +53,16 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab } /** - * Get a proxy instance of {@link DubboMetadataService} via the specified service name - * + * Remove {@link DubboMetadataService}'s Proxy by service name. + * @param serviceName the service name + */ + public void removeProxy(String serviceName) { + dubboMetadataServiceCache.remove(serviceName); + } + + /** + * Get a proxy instance of {@link DubboMetadataService} via the specified service + * name. * @param serviceName the service name * @return a {@link DubboMetadataService} proxy */ @@ -73,8 +81,8 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab } /** - * New a proxy instance of {@link DubboMetadataService} via the specified service name - * + * New a proxy instance of {@link DubboMetadataService} via the specified service + * name. * @param serviceName the service name * @param version the service version * @return a {@link DubboMetadataService} proxy @@ -85,4 +93,5 @@ public class DubboMetadataServiceProxy implements BeanClassLoaderAware, Disposab new DubboMetadataServiceInvocationHandler(serviceName, version, dubboGenericServiceFactory)); } + } diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java index b4d8cc20..3b167f80 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/IntrospectiveDubboMetadataService.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,26 +15,26 @@ */ package com.alibaba.cloud.dubbo.service; -import static java.util.Collections.unmodifiableMap; -import static org.springframework.util.CollectionUtils.isEmpty; - import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; -import org.apache.dubbo.common.URL; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; - 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; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; + +import static java.util.Collections.unmodifiableMap; +import static org.springframework.util.CollectionUtils.isEmpty; + /** * Introspective {@link DubboMetadataService} implementation * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java index 4d63363e..8f677895 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractDubboGenericServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,15 +15,15 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import static org.springframework.context.ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME; -import static org.springframework.util.ClassUtils.resolveClassName; - import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.core.convert.ConversionService; import org.springframework.format.support.DefaultFormattingConversionService; +import static org.springframework.context.ConfigurableApplicationContext.CONVERSION_SERVICE_BEAN_NAME; +import static org.springframework.util.ClassUtils.resolveClassName; + /** * Abstract {@link DubboGenericServiceParameterResolver} implementation * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java index 50fc7b76..179d78e5 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/AbstractNamedValueServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,19 +15,19 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import static org.springframework.util.ObjectUtils.isEmpty; - import java.util.Collection; import java.util.Collections; import java.util.Map; -import org.springframework.util.CollectionUtils; -import org.springframework.util.MultiValueMap; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; import com.alibaba.cloud.dubbo.metadata.MethodParameterMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; +import org.springframework.util.CollectionUtils; +import org.springframework.util.MultiValueMap; + +import static org.springframework.util.ObjectUtils.isEmpty; + /** * Abstract HTTP Names Value {@link DubboGenericServiceParameterResolver Dubbo * GenericService Parameter Resolver} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java index 9fc4a609..3805ee9e 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/DubboGenericServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,14 +15,14 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import org.apache.dubbo.rpc.service.GenericService; - -import org.springframework.core.Ordered; - 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 * @@ -33,8 +32,10 @@ public interface DubboGenericServiceParameterResolver extends Ordered { /** * Resolves a method parameter into an argument value from a given request. - * - * @return + * @param restMethodMetadata method request metadata + * @param methodParameterMetadata metadata of method + * @param request Http server request + * @return the result of resolve */ Object resolve(RestMethodMetadata restMethodMetadata, MethodParameterMetadata methodParameterMetadata, HttpServerRequest request); diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java index 0bf093d3..bda4f044 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/PathVariableServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,10 +15,10 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import org.springframework.util.MultiValueMap; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; +import org.springframework.util.MultiValueMap; + /** * HTTP Request Path Variable {@link DubboGenericServiceParameterResolver Dubbo * GenericService Parameter Resolver} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java index 7e3fa88e..eb35ac28 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestBodyServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -22,18 +21,18 @@ import java.util.Objects; import javax.annotation.PostConstruct; -import org.springframework.beans.factory.ObjectProvider; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.autoconfigure.http.HttpMessageConverters; -import org.springframework.http.converter.HttpMessageConverter; -import org.springframework.http.converter.HttpMessageNotReadableException; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; import com.alibaba.cloud.dubbo.http.converter.HttpMessageConverterHolder; import com.alibaba.cloud.dubbo.http.util.HttpMessageConverterResolver; import com.alibaba.cloud.dubbo.metadata.MethodParameterMetadata; import com.alibaba.cloud.dubbo.metadata.RestMethodMetadata; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.http.HttpMessageConverters; +import org.springframework.http.converter.HttpMessageConverter; +import org.springframework.http.converter.HttpMessageNotReadableException; + /** * HTTP Request Body {@link DubboGenericServiceParameterResolver} * diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java index 4656ad01..62b44eb6 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestHeaderServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,10 +15,10 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import org.springframework.util.MultiValueMap; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; +import org.springframework.util.MultiValueMap; + /** * HTTP Request Header {@link DubboGenericServiceParameterResolver Dubbo GenericService * Parameter Resolver} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java index 6ec3cdc1..3524ae2c 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/service/parameter/RequestParamServiceParameterResolver.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,10 +15,10 @@ */ package com.alibaba.cloud.dubbo.service.parameter; -import org.springframework.util.MultiValueMap; - import com.alibaba.cloud.dubbo.http.HttpServerRequest; +import org.springframework.util.MultiValueMap; + /** * HTTP Request Parameter {@link DubboGenericServiceParameterResolver Dubbo GenericService * Parameter Resolver} diff --git a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java index 94071d03..4ec45392 100644 --- a/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java +++ b/spring-cloud-alibaba-dubbo/src/main/java/com/alibaba/cloud/dubbo/util/JSONUtils.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -24,15 +23,14 @@ import java.util.stream.Collectors; import javax.annotation.PostConstruct; -import org.apache.dubbo.common.URL; - -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.StringUtils; - import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; +import org.apache.dubbo.common.URL; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.util.StringUtils; /** * JSON Utilities class diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java index 22dc2e02..2ee01446 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/autoconfigure/DubboServiceRegistrationAutoConfigurationTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java index 5bdb881b..3a13282e 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractHttpRequestMatcherTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java index dcdc92ed..34e0ccad 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractMediaTypeExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,14 +15,15 @@ */ package com.alibaba.cloud.dubbo.http.matcher; +import java.lang.reflect.Constructor; + import org.junit.Assert; import org.junit.Test; + import org.springframework.beans.BeanUtils; import org.springframework.core.ResolvableType; import org.springframework.http.MediaType; -import java.lang.reflect.Constructor; - /** * {@link AbstractMediaTypeExpression} Test * @@ -31,41 +31,45 @@ import java.lang.reflect.Constructor; */ public abstract class AbstractMediaTypeExpressionTest { - protected T createExpression(String expression) { - ResolvableType resolvableType = ResolvableType.forType(getClass().getGenericSuperclass()); - Class firstGenericType = (Class) resolvableType.resolveGeneric(0); - Constructor constructor = null; - try { - constructor = firstGenericType.getDeclaredConstructor(String.class); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - return BeanUtils.instantiateClass(constructor, expression); - } + protected T createExpression(String expression) { + ResolvableType resolvableType = ResolvableType + .forType(getClass().getGenericSuperclass()); + Class firstGenericType = (Class) resolvableType.resolveGeneric(0); + Constructor constructor = null; + try { + constructor = firstGenericType.getDeclaredConstructor(String.class); + } + catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + return BeanUtils.instantiateClass(constructor, expression); + } - @Test - public void testGetMediaTypeAndNegated() { - // Normal - AbstractMediaTypeExpression expression = createExpression(MediaType.APPLICATION_JSON_VALUE); - Assert.assertEquals(MediaType.APPLICATION_JSON, expression.getMediaType()); - Assert.assertFalse(expression.isNegated()); + @Test + public void testGetMediaTypeAndNegated() { + // Normal + AbstractMediaTypeExpression expression = createExpression( + MediaType.APPLICATION_JSON_VALUE); + Assert.assertEquals(MediaType.APPLICATION_JSON, expression.getMediaType()); + Assert.assertFalse(expression.isNegated()); - // Negated - expression = createExpression("!" + MediaType.APPLICATION_JSON_VALUE); - Assert.assertEquals(MediaType.APPLICATION_JSON, expression.getMediaType()); - Assert.assertTrue(expression.isNegated()); - } + // Negated + expression = createExpression("!" + MediaType.APPLICATION_JSON_VALUE); + Assert.assertEquals(MediaType.APPLICATION_JSON, expression.getMediaType()); + Assert.assertTrue(expression.isNegated()); + } - @Test - public void testEqualsAndHashCode() { - Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE), createExpression(MediaType.APPLICATION_JSON_VALUE)); - Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode(), - createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode()); - } + @Test + public void testEqualsAndHashCode() { + Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE), + createExpression(MediaType.APPLICATION_JSON_VALUE)); + Assert.assertEquals(createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode(), + createExpression(MediaType.APPLICATION_JSON_VALUE).hashCode()); + } - @Test - public void testCompareTo() { - Assert.assertEquals(0, - createExpression(MediaType.APPLICATION_JSON_VALUE).compareTo(createExpression(MediaType.APPLICATION_JSON_VALUE))); - } + @Test + public void testCompareTo() { + Assert.assertEquals(0, createExpression(MediaType.APPLICATION_JSON_VALUE) + .compareTo(createExpression(MediaType.APPLICATION_JSON_VALUE))); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpressionTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpressionTest.java index 336d8843..3f85dccf 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/AbstractNameValueExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,13 +15,14 @@ */ package com.alibaba.cloud.dubbo.http.matcher; +import java.lang.reflect.Constructor; + import org.junit.Assert; import org.junit.Test; + import org.springframework.beans.BeanUtils; import org.springframework.core.ResolvableType; -import java.lang.reflect.Constructor; - /** * {@link AbstractNameValueExpression} Test * @@ -30,48 +30,53 @@ import java.lang.reflect.Constructor; */ public abstract class AbstractNameValueExpressionTest { - protected T createExpression(String expression) { - ResolvableType resolvableType = ResolvableType.forType(getClass().getGenericSuperclass()); - Class firstGenericType = (Class) resolvableType.resolveGeneric(0); - Constructor constructor = null; - try { - constructor = firstGenericType.getDeclaredConstructor(String.class); - } catch (NoSuchMethodException e) { - throw new RuntimeException(e); - } - return BeanUtils.instantiateClass(constructor, expression); - } + protected T createExpression(String expression) { + ResolvableType resolvableType = ResolvableType + .forType(getClass().getGenericSuperclass()); + Class firstGenericType = (Class) resolvableType.resolveGeneric(0); + Constructor constructor = null; + try { + constructor = firstGenericType.getDeclaredConstructor(String.class); + } + catch (NoSuchMethodException e) { + throw new RuntimeException(e); + } + return BeanUtils.instantiateClass(constructor, expression); + } - @Test - public void testGetNameAndValue() { - // Normal Name and value - AbstractNameValueExpression expression = createExpression("a=1"); - Assert.assertEquals("a", expression.getName()); - Assert.assertFalse(expression.isNegated()); + @Test + public void testGetNameAndValue() { + // Normal Name and value + AbstractNameValueExpression expression = createExpression("a=1"); + Assert.assertEquals("a", expression.getName()); + Assert.assertFalse(expression.isNegated()); - expression = createExpression("a=1"); - Assert.assertEquals("a", expression.getName()); - Assert.assertEquals("1", expression.getValue()); - Assert.assertFalse(expression.isNegated()); + expression = createExpression("a=1"); + Assert.assertEquals("a", expression.getName()); + Assert.assertEquals("1", expression.getValue()); + Assert.assertFalse(expression.isNegated()); - // Negated Name - expression = createExpression("!a"); - Assert.assertEquals("a", expression.getName()); - Assert.assertTrue(expression.isNegated()); + // Negated Name + expression = createExpression("!a"); + Assert.assertEquals("a", expression.getName()); + Assert.assertTrue(expression.isNegated()); - expression = createExpression("a!=1"); - Assert.assertEquals("a", expression.getName()); - Assert.assertEquals("1", expression.getValue()); - Assert.assertTrue(expression.isNegated()); - } + expression = createExpression("a!=1"); + Assert.assertEquals("a", expression.getName()); + Assert.assertEquals("1", expression.getValue()); + Assert.assertTrue(expression.isNegated()); + } - @Test - public void testEqualsAndHashCode() { - Assert.assertEquals(createExpression("a"), createExpression("a")); - Assert.assertEquals(createExpression("a").hashCode(), createExpression("a").hashCode()); - Assert.assertEquals(createExpression("a=1"), createExpression("a = 1 ")); - Assert.assertEquals(createExpression("a=1").hashCode(), createExpression("a = 1 ").hashCode()); - Assert.assertNotEquals(createExpression("a"), createExpression("b")); - Assert.assertNotEquals(createExpression("a").hashCode(), createExpression("b").hashCode()); - } + @Test + public void testEqualsAndHashCode() { + Assert.assertEquals(createExpression("a"), createExpression("a")); + Assert.assertEquals(createExpression("a").hashCode(), + createExpression("a").hashCode()); + Assert.assertEquals(createExpression("a=1"), createExpression("a = 1 ")); + Assert.assertEquals(createExpression("a=1").hashCode(), + createExpression("a = 1 ").hashCode()); + Assert.assertNotEquals(createExpression("a"), createExpression("b")); + Assert.assertNotEquals(createExpression("a").hashCode(), + createExpression("b").hashCode()); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpressionTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpressionTest.java index 144332c8..ba86a6b8 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ConsumeMediaTypeExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -18,6 +17,7 @@ package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Assert; import org.junit.Test; + import org.springframework.http.MediaType; /** @@ -25,21 +25,22 @@ import org.springframework.http.MediaType; * * @author Mercy */ -public class ConsumeMediaTypeExpressionTest extends AbstractMediaTypeExpressionTest { +public class ConsumeMediaTypeExpressionTest + extends AbstractMediaTypeExpressionTest { - @Test - public void testMatch() { - ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE); + @Test + public void testMatch() { + ConsumeMediaTypeExpression expression = createExpression(MediaType.ALL_VALUE); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); - expression = createExpression(MediaType.APPLICATION_JSON_VALUE); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + expression = createExpression(MediaType.APPLICATION_JSON_VALUE); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); - expression = createExpression(MediaType.APPLICATION_JSON_VALUE + ";q=0.7"); - Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); + expression = createExpression(MediaType.APPLICATION_JSON_VALUE + ";q=0.7"); + Assert.assertTrue(expression.match(MediaType.APPLICATION_JSON_UTF8)); - expression = createExpression(MediaType.TEXT_HTML_VALUE); - Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON_UTF8)); - } + expression = createExpression(MediaType.TEXT_HTML_VALUE); + Assert.assertFalse(expression.match(MediaType.APPLICATION_JSON_UTF8)); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java index 69ff08ab..54bcefd6 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HeaderExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -18,6 +17,7 @@ package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Assert; import org.junit.Test; + import org.springframework.http.HttpRequest; import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; @@ -27,34 +27,35 @@ import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; * * @author Mercy */ -public class HeaderExpressionTest extends AbstractNameValueExpressionTest { +public class HeaderExpressionTest + extends AbstractNameValueExpressionTest { - @Test - public void testIsCaseSensitiveName() { - Assert.assertFalse(createExpression("a=1").isCaseSensitiveName()); - Assert.assertFalse(createExpression("a=!1").isCaseSensitiveName()); - Assert.assertFalse(createExpression("b=1").isCaseSensitiveName()); - } + @Test + public void testIsCaseSensitiveName() { + Assert.assertFalse(createExpression("a=1").isCaseSensitiveName()); + Assert.assertFalse(createExpression("a=!1").isCaseSensitiveName()); + Assert.assertFalse(createExpression("b=1").isCaseSensitiveName()); + } - @Test - public void testMatch() { + @Test + public void testMatch() { - HeaderExpression expression = createExpression("a=1"); - HttpRequest request = builder().build(); + HeaderExpression expression = createExpression("a=1"); + HttpRequest request = builder().build(); - Assert.assertFalse(expression.match(request)); + Assert.assertFalse(expression.match(request)); - request = builder().header("a", "").build(); - Assert.assertFalse(expression.match(request)); + request = builder().header("a", "").build(); + Assert.assertFalse(expression.match(request)); - request = builder().header("a", "2").build(); - Assert.assertFalse(expression.match(request)); + request = builder().header("a", "2").build(); + Assert.assertFalse(expression.match(request)); - request = builder().header("", "1").build(); - Assert.assertFalse(expression.match(request)); + request = builder().header("", "1").build(); + Assert.assertFalse(expression.match(request)); - request = builder().header("a", "1").build(); - Assert.assertTrue(expression.match(request)); - } + request = builder().header("a", "1").build(); + Assert.assertTrue(expression.match(request)); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java index 1da5db43..4f11e8c2 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestMethodsMatcherTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,34 +15,38 @@ */ package com.alibaba.cloud.dubbo.http.matcher; -import org.junit.Assert; -import org.springframework.http.HttpMethod; - import java.util.Arrays; import java.util.HashSet; +import org.junit.Assert; + +import org.springframework.http.HttpMethod; + /** * {@link HttpRequestMethodsMatcher} Test * * @author Mercy */ -public class HttpRequestMethodsMatcherTest extends AbstractHttpRequestMatcherTest { +public class HttpRequestMethodsMatcherTest + extends AbstractHttpRequestMatcherTest { - HttpRequestMethodsMatcher matcher = new HttpRequestMethodsMatcher("GET"); + HttpRequestMethodsMatcher matcher = new HttpRequestMethodsMatcher("GET"); - @Override - public void testEqualsAndHashCode() { - Assert.assertEquals(new HashSet<>(Arrays.asList(HttpMethod.GET)), matcher.getMethods()); - } + @Override + public void testEqualsAndHashCode() { + Assert.assertEquals(new HashSet<>(Arrays.asList(HttpMethod.GET)), + matcher.getMethods()); + } - @Override - public void testGetContent() { - Assert.assertEquals(new HashSet<>(Arrays.asList(HttpMethod.GET)), matcher.getContent()); - } + @Override + public void testGetContent() { + Assert.assertEquals(new HashSet<>(Arrays.asList(HttpMethod.GET)), + matcher.getContent()); + } - @Override - public void testGetToStringInfix() { - Assert.assertEquals(" || ", matcher.getToStringInfix()); - } + @Override + public void testGetToStringInfix() { + Assert.assertEquals(" || ", matcher.getToStringInfix()); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java index 38146434..bbc20182 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/HttpRequestParamsMatcherTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,11 +15,12 @@ */ package com.alibaba.cloud.dubbo.http.matcher; +import java.net.URI; + import org.junit.Assert; import org.junit.Test; -import org.springframework.mock.http.client.MockClientHttpRequest; -import java.net.URI; +import org.springframework.mock.http.client.MockClientHttpRequest; /** * {@link HttpRequestParamsMatcher} Test @@ -29,68 +29,68 @@ import java.net.URI; */ public class HttpRequestParamsMatcherTest { -// @Test -// public void testGetParams() { -// -// HttpRequestParamsMatcher matcher = new HttpRequestParamsMatcher( -// "a ", -// "a =1", -// "b = 2", -// "b = 3 ", -// " c = 4 ", -// " d" -// ); -// -// Map> params = matcher.getParams(); -// Assert.assertEquals(4, params.size()); -// Assert.assertTrue(params.containsKey("a")); -// Assert.assertTrue(params.containsKey("b")); -// Assert.assertTrue(params.containsKey("c")); -// Assert.assertTrue(params.containsKey("d")); -// Assert.assertFalse(params.containsKey("e")); -// -// List values = params.get("a"); -// Assert.assertEquals(2, values.size()); -// Assert.assertEquals("", values.get(0)); -// Assert.assertEquals("1", values.get(1)); -// -// values = params.get("b"); -// Assert.assertEquals(2, values.size()); -// Assert.assertEquals("2", values.get(0)); -// Assert.assertEquals("3", values.get(1)); -// -// values = params.get("c"); -// Assert.assertEquals(1, values.size()); -// Assert.assertEquals("4", values.get(0)); -// -// values = params.get("d"); -// Assert.assertEquals(1, values.size()); -// Assert.assertEquals("", values.get(0)); -// } + // @Test + // public void testGetParams() { + // + // HttpRequestParamsMatcher matcher = new HttpRequestParamsMatcher( + // "a ", + // "a =1", + // "b = 2", + // "b = 3 ", + // " c = 4 ", + // " d" + // ); + // + // Map> params = matcher.getParams(); + // Assert.assertEquals(4, params.size()); + // Assert.assertTrue(params.containsKey("a")); + // Assert.assertTrue(params.containsKey("b")); + // Assert.assertTrue(params.containsKey("c")); + // Assert.assertTrue(params.containsKey("d")); + // Assert.assertFalse(params.containsKey("e")); + // + // List values = params.get("a"); + // Assert.assertEquals(2, values.size()); + // Assert.assertEquals("", values.get(0)); + // Assert.assertEquals("1", values.get(1)); + // + // values = params.get("b"); + // Assert.assertEquals(2, values.size()); + // Assert.assertEquals("2", values.get(0)); + // Assert.assertEquals("3", values.get(1)); + // + // values = params.get("c"); + // Assert.assertEquals(1, values.size()); + // Assert.assertEquals("4", values.get(0)); + // + // values = params.get("d"); + // Assert.assertEquals(1, values.size()); + // Assert.assertEquals("", values.get(0)); + // } - @Test - public void testEquals() { + @Test + public void testEquals() { - HttpRequestParamsMatcher matcher = new HttpRequestParamsMatcher("a ", "a = 1"); + HttpRequestParamsMatcher matcher = new HttpRequestParamsMatcher("a ", "a = 1"); - MockClientHttpRequest request = new MockClientHttpRequest(); + MockClientHttpRequest request = new MockClientHttpRequest(); - request.setURI(URI.create("http://dummy/?a")); - Assert.assertTrue(matcher.match(request)); - request.setURI(URI.create("http://dummy/?a&a=1")); - Assert.assertTrue(matcher.match(request)); + request.setURI(URI.create("http://dummy/?a")); + Assert.assertTrue(matcher.match(request)); + request.setURI(URI.create("http://dummy/?a&a=1")); + Assert.assertTrue(matcher.match(request)); - matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2"); - request.setURI(URI.create("http://dummy/?a&a=1&b")); - Assert.assertTrue(matcher.match(request)); - request.setURI(URI.create("http://dummy/?a&a=1&b&b=2")); - Assert.assertTrue(matcher.match(request)); + matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2"); + request.setURI(URI.create("http://dummy/?a&a=1&b")); + Assert.assertTrue(matcher.match(request)); + request.setURI(URI.create("http://dummy/?a&a=1&b&b=2")); + Assert.assertTrue(matcher.match(request)); - matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2", "b = 3 "); - request.setURI(URI.create("http://dummy/?a&a=1&b&b=2&b=3")); - Assert.assertTrue(matcher.match(request)); + matcher = new HttpRequestParamsMatcher("a ", "a =1", "b", "b=2", "b = 3 "); + request.setURI(URI.create("http://dummy/?a&a=1&b&b=2&b=3")); + Assert.assertTrue(matcher.match(request)); - request.setURI(URI.create("http://dummy/?d=1")); - Assert.assertFalse(matcher.match(request)); - } + 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-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java index f512bdd9..2351748b 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ParamExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -18,6 +17,7 @@ package com.alibaba.cloud.dubbo.http.matcher; import org.junit.Assert; import org.junit.Test; + import org.springframework.http.HttpRequest; import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; @@ -27,34 +27,35 @@ import static com.alibaba.cloud.dubbo.http.DefaultHttpRequest.builder; * * @author Mercy */ -public class ParamExpressionTest extends AbstractNameValueExpressionTest { +public class ParamExpressionTest + extends AbstractNameValueExpressionTest { - @Test - public void testIsCaseSensitiveName() { - Assert.assertTrue(createExpression("a=1").isCaseSensitiveName()); - Assert.assertTrue(createExpression("a=!1").isCaseSensitiveName()); - Assert.assertTrue(createExpression("b=1").isCaseSensitiveName()); - } + @Test + public void testIsCaseSensitiveName() { + Assert.assertTrue(createExpression("a=1").isCaseSensitiveName()); + Assert.assertTrue(createExpression("a=!1").isCaseSensitiveName()); + Assert.assertTrue(createExpression("b=1").isCaseSensitiveName()); + } - @Test - public void testMatch() { + @Test + public void testMatch() { - ParamExpression expression = createExpression("a=1"); - HttpRequest request = builder().build(); + ParamExpression expression = createExpression("a=1"); + HttpRequest request = builder().build(); - Assert.assertFalse(expression.match(request)); + Assert.assertFalse(expression.match(request)); - request = builder().param("a", "").build(); - Assert.assertFalse(expression.match(request)); + request = builder().param("a", "").build(); + Assert.assertFalse(expression.match(request)); - request = builder().param("a", "2").build(); - Assert.assertFalse(expression.match(request)); + request = builder().param("a", "2").build(); + Assert.assertFalse(expression.match(request)); - request = builder().param("", "1").build(); - Assert.assertFalse(expression.match(request)); + request = builder().param("", "1").build(); + Assert.assertFalse(expression.match(request)); - request = builder().param("a", "1").build(); - Assert.assertTrue(expression.match(request)); - } + request = builder().param("a", "1").build(); + Assert.assertTrue(expression.match(request)); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java index 1df8fdd8..274a2933 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/matcher/ProduceMediaTypeExpressionTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,25 +15,29 @@ */ package com.alibaba.cloud.dubbo.http.matcher; +import java.util.Arrays; + import org.junit.Assert; import org.junit.Test; -import org.springframework.http.MediaType; -import java.util.Arrays; +import org.springframework.http.MediaType; /** * {@link ProduceMediaTypeExpression} Test * * @author Mercy */ -public class ProduceMediaTypeExpressionTest extends AbstractMediaTypeExpressionTest { +public class ProduceMediaTypeExpressionTest + extends AbstractMediaTypeExpressionTest { - @Test - public void testMatch() { - ProduceMediaTypeExpression expression = createExpression(MediaType.APPLICATION_JSON_VALUE); - Assert.assertTrue(expression.match(Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON))); + @Test + public void testMatch() { + ProduceMediaTypeExpression expression = createExpression( + MediaType.APPLICATION_JSON_VALUE); + Assert.assertTrue(expression.match( + Arrays.asList(MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON))); - expression = createExpression(MediaType.APPLICATION_JSON_VALUE); - Assert.assertFalse(expression.match(Arrays.asList(MediaType.APPLICATION_XML))); - } + 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-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java index 322d6e1f..ef2f8669 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/http/util/HttpUtilsTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -26,16 +25,16 @@ import org.junit.Test; */ public class HttpUtilsTest { - @Test - public void testEncodeAndDecode() { + @Test + public void testEncodeAndDecode() { - String whitespace = " "; + String whitespace = " "; - String encodedValue = HttpUtils.encode(" "); + String encodedValue = HttpUtils.encode(" "); - String decodedValue = HttpUtils.decode(encodedValue); + String decodedValue = HttpUtils.decode(encodedValue); - Assert.assertEquals(whitespace, decodedValue); - } + Assert.assertEquals(whitespace, decodedValue); + } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java index 84992422..c0741e3a 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/RequestMetadataTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,13 +15,13 @@ */ package com.alibaba.cloud.dubbo.metadata; -import org.junit.Assert; -import org.junit.Test; - import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; +import org.junit.Assert; +import org.junit.Test; + /** * {@link RequestMetadata} Test * @@ -30,107 +29,108 @@ import java.util.Set; */ public class RequestMetadataTest { - private String method = "GET"; + private String method = "GET"; - private String url = "/param"; + private String url = "/param"; - private Set paramNames = new LinkedHashSet<>(Arrays.asList("a", "b", "c")); + private Set paramNames = new LinkedHashSet<>(Arrays.asList("a", "b", "c")); - private Set headerNames = new LinkedHashSet<>(Arrays.asList("d", "e", "f")); + private Set headerNames = new LinkedHashSet<>(Arrays.asList("d", "e", "f")); - @Test - public void testEqualsAndHashCodeAndCompareTo() { + @Test + public void testEqualsAndHashCodeAndCompareTo() { - RequestMetadata metadata = new RequestMetadata(); - RequestMetadata metadata2 = new RequestMetadata(); + RequestMetadata metadata = new RequestMetadata(); + RequestMetadata metadata2 = new RequestMetadata(); - Assert.assertEquals(metadata, metadata2); - Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); + Assert.assertEquals(metadata, metadata2); + Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); - metadata.setMethod(method); - metadata2.setMethod(method); + metadata.setMethod(method); + metadata2.setMethod(method); - Assert.assertEquals(metadata, metadata2); - Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); + Assert.assertEquals(metadata, metadata2); + Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); - metadata.setPath(url); - metadata2.setPath(url); + metadata.setPath(url); + metadata2.setPath(url); - Assert.assertEquals(metadata, metadata2); - Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); + Assert.assertEquals(metadata, metadata2); + Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); - metadata.addParam("a", "1").addParam("b", "2").addParam("c", "3"); - metadata2.addParam("a", "1a").addParam("b", "2b").addParam("c", "3c"); + metadata.addParam("a", "1").addParam("b", "2").addParam("c", "3"); + metadata2.addParam("a", "1a").addParam("b", "2b").addParam("c", "3c"); - Assert.assertEquals(metadata, metadata2); - Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); + Assert.assertEquals(metadata, metadata2); + Assert.assertEquals(metadata.hashCode(), metadata2.hashCode()); - metadata.addHeader("d", "1").addHeader("e", "2").addHeader("f", "3"); - metadata2.addHeader("d", "1").addHeader("e", "2"); + metadata.addHeader("d", "1").addHeader("e", "2").addHeader("f", "3"); + metadata2.addHeader("d", "1").addHeader("e", "2"); - Assert.assertNotEquals(metadata, metadata2); - Assert.assertNotEquals(metadata.hashCode(), metadata2.hashCode()); - } + Assert.assertNotEquals(metadata, metadata2); + Assert.assertNotEquals(metadata.hashCode(), metadata2.hashCode()); + } -// @Test -// public void testBestMatch() { -// -// NavigableMap requestMetadataMap = new TreeMap<>(); -// -// RequestMetadata metadata = new RequestMetadata(); -// metadata.setMethod(method); -// -// RequestMetadata metadata1 = new RequestMetadata(); -// metadata1.setMethod(method); -// metadata1.setPath(url); -// -// RequestMetadata metadata2 = new RequestMetadata(); -// metadata2.setMethod(method); -// metadata2.setPath(url); -// metadata2.setParams(paramNames); -// -// RequestMetadata metadata3 = new RequestMetadata(); -// metadata3.setMethod(method); -// metadata3.setPath(url); -// metadata3.setParams(paramNames); -// metadata3.setHeaders(headerNames); -// -// requestMetadataMap.put(metadata, metadata); -// requestMetadataMap.put(metadata1, metadata1); -// requestMetadataMap.put(metadata2, metadata2); -// requestMetadataMap.put(metadata3, metadata3); -// -// RequestMetadata result = getBestMatch(requestMetadataMap, metadata); -// Assert.assertEquals(result, metadata); -// -// result = getBestMatch(requestMetadataMap, metadata1); -// Assert.assertEquals(result, metadata1); -// -// result = getBestMatch(requestMetadataMap, metadata2); -// Assert.assertEquals(result, metadata2); -// -// result = getBestMatch(requestMetadataMap, metadata3); -// Assert.assertEquals(result, metadata3); -// -// // REDO -// requestMetadataMap.clear(); -// -// requestMetadataMap.put(metadata1, metadata1); -// -// result = getBestMatch(requestMetadataMap, metadata2); -// Assert.assertEquals(metadata1, result); -// -// requestMetadataMap.put(metadata2, metadata2); -// -// result = getBestMatch(requestMetadataMap, metadata3); -// Assert.assertEquals(metadata2, result); -// -// result = getBestMatch(requestMetadataMap, new RequestMetadata()); -// Assert.assertNull(result); -// -// result = getBestMatch(requestMetadataMap, metadata); -// Assert.assertNull(result); -// -// } + // @Test + // public void testBestMatch() { + // + // NavigableMap requestMetadataMap = new + // TreeMap<>(); + // + // RequestMetadata metadata = new RequestMetadata(); + // metadata.setMethod(method); + // + // RequestMetadata metadata1 = new RequestMetadata(); + // metadata1.setMethod(method); + // metadata1.setPath(url); + // + // RequestMetadata metadata2 = new RequestMetadata(); + // metadata2.setMethod(method); + // metadata2.setPath(url); + // metadata2.setParams(paramNames); + // + // RequestMetadata metadata3 = new RequestMetadata(); + // metadata3.setMethod(method); + // metadata3.setPath(url); + // metadata3.setParams(paramNames); + // metadata3.setHeaders(headerNames); + // + // requestMetadataMap.put(metadata, metadata); + // requestMetadataMap.put(metadata1, metadata1); + // requestMetadataMap.put(metadata2, metadata2); + // requestMetadataMap.put(metadata3, metadata3); + // + // RequestMetadata result = getBestMatch(requestMetadataMap, metadata); + // Assert.assertEquals(result, metadata); + // + // result = getBestMatch(requestMetadataMap, metadata1); + // Assert.assertEquals(result, metadata1); + // + // result = getBestMatch(requestMetadataMap, metadata2); + // Assert.assertEquals(result, metadata2); + // + // result = getBestMatch(requestMetadataMap, metadata3); + // Assert.assertEquals(result, metadata3); + // + // // REDO + // requestMetadataMap.clear(); + // + // requestMetadataMap.put(metadata1, metadata1); + // + // result = getBestMatch(requestMetadataMap, metadata2); + // Assert.assertEquals(metadata1, result); + // + // requestMetadataMap.put(metadata2, metadata2); + // + // result = getBestMatch(requestMetadataMap, metadata3); + // Assert.assertEquals(metadata2, result); + // + // result = getBestMatch(requestMetadataMap, new RequestMetadata()); + // Assert.assertNull(result); + // + // result = getBestMatch(requestMetadataMap, metadata); + // Assert.assertNull(result); + // + // } } diff --git a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java index b1cc3a74..95699a2d 100644 --- a/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java +++ b/spring-cloud-alibaba-dubbo/src/test/java/com/alibaba/cloud/dubbo/metadata/resolver/DubboTransportedMethodMetadataResolverTest.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,16 +15,18 @@ */ 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; -import com.alibaba.cloud.dubbo.annotation.DubboTransported; -import com.alibaba.cloud.dubbo.metadata.DubboTransportedMethodMetadata; + import org.springframework.cloud.openfeign.support.SpringMvcContract; import org.springframework.mock.env.MockEnvironment; -import java.util.Set; - /** * {@link DubboTransportedMethodMetadataResolver} Test * @@ -33,27 +34,28 @@ import java.util.Set; */ public class DubboTransportedMethodMetadataResolverTest { - private DubboTransportedMethodMetadataResolver resolver; + private DubboTransportedMethodMetadataResolver resolver; - private MockEnvironment environment; + private MockEnvironment environment; - @Before - public void init() { - environment = new MockEnvironment(); - resolver = new DubboTransportedMethodMetadataResolver(environment, new SpringMvcContract()); - } + @Before + public void init() { + environment = new MockEnvironment(); + resolver = new DubboTransportedMethodMetadataResolver(environment, + new SpringMvcContract()); + } - @Test - public void testResolve() { - Set metadataSet = resolver.resolveDubboTransportedMethodMetadataSet(TestDefaultService.class); - Assert.assertEquals(1, metadataSet.size()); - } + @Test + public void testResolve() { + Set metadataSet = resolver + .resolveDubboTransportedMethodMetadataSet(TestDefaultService.class); + Assert.assertEquals(1, metadataSet.size()); + } + @DubboTransported + interface TestDefaultService { - @DubboTransported - interface TestDefaultService { + String test(String message); - String test(String message); - - } + } } 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 index 585b6c29..308e9839 100644 --- a/spring-cloud-alibaba-examples/acm-example/acm-local-example/pom.xml +++ b/spring-cloud-alibaba-examples/acm-example/acm-local-example/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.BUILD-SNAPSHOT ../../pom.xml 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 index 5508b881..74abd424 100644 --- 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 @@ -18,6 +18,7 @@ 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; 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 index cef37d38..7f3c1187 100644 --- 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 @@ -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.BUILD-SNAPSHOT ../../pom.xml 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 index 45018514..efe964b5 100644 --- 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 @@ -18,6 +18,7 @@ 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; 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 index a815be0b..ac697b88 100644 --- 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 @@ -1,4 +1,4 @@ -spring.application.name=ribbon-consumer +spring.application.name=feign-consumer server.port=18083 # The following configuration can be omitted. spring.cloud.alicloud.ans.server-list=127.0.0.1 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 index d7ccafb2..8827d2b4 100644 --- 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 @@ -18,6 +18,7 @@ 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; 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 index 30bc0998..1430df9e 100644 --- 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 @@ -18,6 +18,7 @@ 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; diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md index b0fe443c..2c9441f3 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme-zh.md @@ -43,12 +43,10 @@ 1. 直接下载:[Nacos Server 下载页](https://github.com/alibaba/nacos/releases) 2. 源码构建:进入 Nacos [Github 项目页面](https://github.com/alibaba/nacos),将代码 git clone 到本地自行编译打包,[参考此文档](https://nacos.io/zh-cn/docs/quick-start.html)。 - - 2. 启动 Server,进入下载到本地并解压完成后的文件夹(使用源码构建的方式则进入编译打包好的文件夹),再进去其相对文件夹 nacos/bin,并对照操作系统实际情况执行如下命令。[详情参考此文档](https://nacos.io/zh-cn/docs/quick-start.html)。 1. Linux/Unix/Mac 操作系统,执行命令 `sh startup.sh -m standalone` - 1. Windows 操作系统,执行命令 `cmd startup.cmd` + 2. Windows 操作系统,执行命令 `cmd startup.cmd` 3. 在命令行执行如下命令,向 Nacos Server 中添加一条配置。 diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md index ede9a328..b415bf8c 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-config-example/readme.md @@ -42,12 +42,10 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl 1. Download: Download Nacos Server [download page](https://github.com/alibaba/nacos/releases) 2. Build from source code: Get source code by git clone git@github.com:alibaba/Nacos.git from Github Nacos and build your code. See [build reference](https://nacos.io/en-us/docs/quick-start.html) for details. - - 2. Unzip the downloaded file and go to the nacos/bin folder(), And according to the actual situation of the operating system, execute the following command。[see reference for more detail](https://nacos.io/en-us/docs/quick-start.html)。 1. Linux/Unix/Mac , execute `sh startup.sh -m standalone` - 1. Windows , execute `cmd startup.cmd` + 2. Windows , execute `cmd startup.cmd` 3. Execute the following command to add a configuration to Nacos Server. 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 176c2709..e65a171a 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,5 +1,14 @@ package com.alibaba.cloud.examples; +import java.io.IOException; +import java.io.StringReader; +import java.util.Properties; +import java.util.concurrent.Executor; + +import com.alibaba.cloud.nacos.NacosConfigManager; +import com.alibaba.nacos.api.config.listener.Listener; + +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; @@ -11,11 +20,10 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** - * @author xiaojing + * @author xiaojing, Jianwei Mao */ @SpringBootApplication public class Application { - public static void main(String[] args) { SpringApplication.run(Application.class, args); } @@ -27,13 +35,47 @@ class SampleRunner implements ApplicationRunner { @Value("${user.name}") String userName; - @Value("${user.age}") + @Value("${user.age:25}") int userAge; + @Autowired + private NacosConfigManager nacosConfigManager; + @Override public void run(ApplicationArguments args) throws Exception { - System.out.println(userName); - System.out.println(userAge); + System.out.println( + String.format("Initial username=%s, userAge=%d", userName, userAge)); + + nacosConfigManager.getConfigService().addListener( + "nacos-config-example.properties", "DEFAULT_GROUP", new Listener() { + + /** + * Callback with latest config data. + * + * For example, config data in Nacos is: + * + * user.name=Nacos user.age=25 + * + * @param configInfo latest config data for specific dataId in Nacos + * server + */ + @Override + public void receiveConfigInfo(String configInfo) { + Properties properties = new Properties(); + try { + properties.load(new StringReader(configInfo)); + } + catch (IOException e) { + e.printStackTrace(); + } + System.out.println("config changed: " + properties); + } + + @Override + public Executor getExecutor() { + return null; + } + }); } } @@ -44,7 +86,7 @@ class SampleController { @Value("${user.name}") String userName; - @Value("${user.age}") + @Value("${user.age:25}") int age; @RequestMapping("/user") 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 2542d6d5..deef9a9b 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,5 +1,9 @@ package com.alibaba.cloud.examples; +import com.alibaba.cloud.examples.ConsumerApplication.EchoService; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; +import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlCleaner; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; @@ -7,15 +11,11 @@ import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.cloud.openfeign.FeignClient; 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.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.examples.ConsumerApplication.EchoService; -import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; - /** * @author xiaojing */ @@ -26,6 +26,7 @@ public class ConsumerApplication { @LoadBalanced @Bean + @SentinelRestTemplate(urlCleanerClass = UrlCleaner.class, urlCleaner = "clean") public RestTemplate restTemplate() { return new RestTemplate(); } @@ -43,17 +44,17 @@ public class ConsumerApplication { @FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class) public interface EchoService { - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); - @RequestMapping(value = "/divide", method = RequestMethod.GET) + @GetMapping(value = "/divide") String divide(@RequestParam("a") Integer a, @RequestParam("b") Integer b); default String divide(Integer a) { return divide(a, 0); } - @RequestMapping(value = "/notFound", method = RequestMethod.GET) + @GetMapping(value = "/notFound") String notFound(); } 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 f22f1a21..214fe52e 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,5 +1,7 @@ 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.PathVariable; @@ -9,8 +11,6 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.examples.ConsumerApplication.EchoService; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md index e241b3d7..2140c5ea 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme-zh.md @@ -35,7 +35,7 @@ @RestController class EchoController { - @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{string}") public String echo(@PathVariable String string) { return string; } @@ -70,7 +70,7 @@ ### 验证 #### 查询服务 -在浏览器输入此地址 `http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=service-provider`,并点击跳转,可以看到服务节点已经成功注册到 Nacos Server。 +在浏览器输入此地址 `http://127.0.0.1:8848/nacos/v1/ns/catalog/instances?serviceName=service-provider&clusterName=DEFAULT&pageSize=10&pageNo=1&namespaceId=`,并点击跳转,可以看到服务节点已经成功注册到 Nacos Server。 ![查询服务](https://cdn.nlark.com/lark/0/2018/png/54319/1536986288092-5cf96af9-9a26-466b-85f6-39ad1d92dfdc.png) @@ -102,7 +102,7 @@ Nacos Discovery Starter 默认集成了 Ribbon ,所以对于使用了 Ribbon @FeignClient(name = "service-provider") public interface EchoService { - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); } @@ -120,11 +120,11 @@ Nacos Discovery Starter 默认集成了 Ribbon ,所以对于使用了 Ribbon @Autowired private EchoService echoService; - @RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } - @RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } diff --git a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md index cff28427..86469101 100644 --- a/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md +++ b/spring-cloud-alibaba-examples/nacos-example/nacos-discovery-example/readme.md @@ -34,7 +34,7 @@ Before we start the demo, let's learn how to connect Nacos Config to a Spring Cl @RestController class EchoController { - @RequestMapping(value = "/echo/{string}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{string}") public String echo(@PathVariable String string) { return string; } @@ -105,7 +105,7 @@ The code of `nacos-discovery-consumer-example` project will be analyzed below, d @FeignClient(name = "service-provider") public interface EchoService { - @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); } @@ -123,11 +123,11 @@ The code of `nacos-discovery-consumer-example` project will be analyzed below, d @Autowired private EchoService echoService; - @RequestMapping(value = "/echo-rest/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } - @RequestMapping(value = "/echo-feign/{str}", method = RequestMethod.GET) + @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } diff --git a/spring-cloud-alibaba-examples/oss-example/readme-zh.md b/spring-cloud-alibaba-examples/oss-example/readme-zh.md index 2f06449e..4385636f 100644 --- a/spring-cloud-alibaba-examples/oss-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/oss-example/readme-zh.md @@ -128,7 +128,7 @@ Spring Boot 应用支持通过 Endpoint 来暴露相关信息,OSS Starter 也 Spring Boot1.x 可以通过访问 http://127.0.0.1:18084/oss 来查看 OSS Endpoint 的信息。 -Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/acutator/oss 来访问。 +Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/actuator/oss 来访问。 Endpoint 内部会显示所有的 OSSClient 配置信息,以及该 OSSClient 对应的 Bucket 列表。 diff --git a/spring-cloud-alibaba-examples/oss-example/readme.md b/spring-cloud-alibaba-examples/oss-example/readme.md index 3d002d72..76e7f899 100644 --- a/spring-cloud-alibaba-examples/oss-example/readme.md +++ b/spring-cloud-alibaba-examples/oss-example/readme.md @@ -114,7 +114,7 @@ You can verify results on the OSS console when you finish uploading or downloadi ## Endpoint -OSS starter also supports the implmentation of Spring Boot acutator endpoints. +OSS starter also supports the implementation of Spring Boot actuator endpoints. **Prerequisite:** @@ -127,7 +127,7 @@ 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/acutator/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. 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 index 9dd6907f..932497ed 100644 --- 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 @@ -2,6 +2,8 @@ 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; @@ -9,8 +11,6 @@ import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; -import com.aliyun.oss.OSS; - /** * OSS Application * 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 index c1c9d261..901e2779 100644 --- 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 @@ -2,7 +2,11 @@ package com.alibaba.cloud.examples; 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; @@ -10,10 +14,6 @@ import org.springframework.util.StreamUtils; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; -import com.aliyun.oss.OSS; -import com.aliyun.oss.common.utils.IOUtils; -import com.aliyun.oss.model.OSSObject; - /** * OSS Controller * diff --git a/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md b/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md index 34a15959..ec27f69e 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/rocketmq-example/readme-zh.md @@ -60,7 +60,7 @@ public class RocketMQApplication { 配置 Binding 信息: ```properties # 配置rocketmq的nameserver地址 -spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876 +spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876 # 定义name为output的binding spring.cloud.stream.bindings.output.destination=test-topic spring.cloud.stream.bindings.output.content-type=application/json @@ -125,7 +125,7 @@ server.port=28081 配置信息如下: ```properties -spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876 +spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876 spring.cloud.stream.bindings.output.destination=test-topic spring.cloud.stream.bindings.output.content-type=application/json diff --git a/spring-cloud-alibaba-examples/rocketmq-example/readme.md b/spring-cloud-alibaba-examples/rocketmq-example/readme.md index 27387905..dc9490c6 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/readme.md +++ b/spring-cloud-alibaba-examples/rocketmq-example/readme.md @@ -56,7 +56,7 @@ public class RocketMQApplication { Configure Binding: ```properties # configure the nameserver of rocketmq -spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876 +spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876 # configure the output binding named output spring.cloud.stream.bindings.output.destination=test-topic spring.cloud.stream.bindings.output.content-type=application/json @@ -121,7 +121,7 @@ And using two input bindings to subscribe messages. see the configuration below: ```properties -spring.cloud.stream.rocketmq.binder.namesrv-addr=127.0.0.1:9876 +spring.cloud.stream.rocketmq.binder.name-server=127.0.0.1:9876 spring.cloud.stream.bindings.output.destination=test-topic spring.cloud.stream.bindings.output.content-type=application/json 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 ddfcdbd5..caf9f357 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,5 +1,7 @@ package com.alibaba.cloud.examples; +import com.alibaba.cloud.examples.RocketMQConsumerApplication.MySink; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; @@ -11,8 +13,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.core.ParameterizedTypeReference; import org.springframework.messaging.SubscribableChannel; -import com.alibaba.cloud.examples.RocketMQConsumerApplication.MySink; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/pom.xml b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/pom.xml index 139f1003..4918bbca 100644 --- a/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/pom.xml +++ b/spring-cloud-alibaba-examples/rocketmq-example/rocketmq-produce-example/pom.xml @@ -32,6 +32,13 @@ spring-boot-starter-actuator + + org.springframework.cloud + spring-cloud-stream-binder-kafka + 2.0.3.RELEASE + + + 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 6ac8389e..0037ab06 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,5 +1,7 @@ package com.alibaba.cloud.examples; +import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; @@ -10,8 +12,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.integration.support.MessageBuilder; import org.springframework.messaging.MessageChannel; -import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; - /** * @author Jim */ 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 79fec70e..8c54454a 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 @@ -3,8 +3,11 @@ package com.alibaba.cloud.examples; import java.util.stream.Collectors; import java.util.stream.Stream; +import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; + import org.apache.rocketmq.common.message.MessageConst; import org.apache.rocketmq.spring.support.RocketMQHeaders; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.messaging.Message; import org.springframework.messaging.MessageHeaders; @@ -12,8 +15,6 @@ import org.springframework.messaging.support.MessageBuilder; import org.springframework.stereotype.Service; import org.springframework.util.MimeTypeUtils; -import com.alibaba.cloud.examples.RocketMQProduceApplication.MySource; - /** * @author Jim */ 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 f2b3b6b6..7894ac0f 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 @@ -19,6 +19,7 @@ package com.alibaba.cloud.examples; import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener; import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState; + import org.springframework.messaging.Message; /** 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 index 31d0ffa2..1f910e03 100644 --- 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 @@ -16,12 +16,12 @@ package com.alibaba.cloud.examples; -import org.springframework.beans.factory.annotation.Autowired; - 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 */ 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 7a47c75f..0f221020 100644 --- a/spring-cloud-alibaba-examples/seata-example/account-service/pom.xml +++ b/spring-cloud-alibaba-examples/seata-example/account-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.BUILD-SNAPSHOT ../../pom.xml 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 46c2e33a..00bad6db 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 @@ -17,14 +17,13 @@ package com.alibaba.cloud.examples; import java.util.Random; +import io.seata.core.context.RootContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.jdbc.core.JdbcTemplate; -import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.springframework.web.bind.annotation.RestController; -import io.seata.core.context.RootContext; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RestController; /** * @author xiaojing @@ -45,7 +44,7 @@ public class AccountController { this.random = new Random(); } - @RequestMapping(value = "/account", method = RequestMethod.POST, produces = "application/json") + @PostMapping(value = "/account", produces = "application/json") public String account(String userId, int money) { LOGGER.info("Account Service ... xid: " + RootContext.getXID()); 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 f22071bb..d30e9667 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 @@ -17,16 +17,16 @@ package com.alibaba.cloud.examples; import java.sql.SQLException; +import com.alibaba.druid.pool.DruidDataSource; + +import io.seata.rm.datasource.DataSourceProxy; + import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; -import com.alibaba.druid.pool.DruidDataSource; - -import io.seata.rm.datasource.DataSourceProxy; - /** * @author xiaojing */ 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 index fd3d304f..0777ae8a 100644 --- 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 @@ -4,7 +4,7 @@ transport { #NIO NATIVE server = "NIO" #enable heartbeat - heartbeat = true + heartbeat = false #thread factory for netty thread-factory { boss-thread-prefix = "NettyBoss" @@ -28,7 +28,7 @@ transport { } service { #vgroup->rgroup - vgroup_mapping.account-service-fescar-service-group = "default" + vgroup_mapping.account-service-seata-service-group = "default" #only support single node default.grouplist = "127.0.0.1:8091" #degrade current not support @@ -46,17 +46,22 @@ client { 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" } -## metrics settings -metrics { - enabled = false - registry-type = "compact" - # multi exporters use comma divided - exporter-list = "prometheus" - exporter-prometheus-port = 9898 +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 index 6dbeb22b..b98f5704 100644 --- 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 @@ -4,7 +4,7 @@ registry { nacos { serverAddr = "localhost" - namespace = "public" + namespace = "" cluster = "default" } eureka { @@ -50,8 +50,7 @@ config { nacos { serverAddr = "localhost" - namespace = "public" - cluster = "default" + namespace = "" } consul { serverAddr = "127.0.0.1:8500" 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 8b4ab39d..96ca752f 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 @@ -16,8 +16,13 @@ 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; + import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -29,11 +34,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.examples.BusinessApplication.OrderService; -import com.alibaba.cloud.examples.BusinessApplication.StorageService; - -import io.seata.spring.annotation.GlobalTransactional; - /** * @author xiaojing */ 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 index a766d498..a6e431bc 100644 --- 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 @@ -4,7 +4,7 @@ transport { #NIO NATIVE server = "NIO" #enable heartbeat - heartbeat = true + heartbeat = false #thread factory for netty thread-factory { boss-thread-prefix = "NettyBoss" @@ -28,7 +28,7 @@ transport { } service { #vgroup->rgroup - vgroup_mapping.business-service-fescar-service-group = "default" + vgroup_mapping.business-service-seata-service-group = "default" #only support single node default.grouplist = "127.0.0.1:8091" #degrade current not support @@ -46,17 +46,22 @@ client { 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" } -## metrics settings -metrics { - enabled = false - registry-type = "compact" - # multi exporters use comma divided - exporter-list = "prometheus" - exporter-prometheus-port = 9898 +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 index 6dbeb22b..b98f5704 100644 --- 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 @@ -4,7 +4,7 @@ registry { nacos { serverAddr = "localhost" - namespace = "public" + namespace = "" cluster = "default" } eureka { @@ -50,8 +50,7 @@ config { nacos { serverAddr = "localhost" - namespace = "public" - cluster = "default" + namespace = "" } consul { serverAddr = "127.0.0.1:8500" 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 e3a260e2..9f517e1b 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 @@ -17,16 +17,16 @@ package com.alibaba.cloud.examples; import java.sql.SQLException; +import com.alibaba.druid.pool.DruidDataSource; + +import io.seata.rm.datasource.DataSourceProxy; + import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; -import com.alibaba.druid.pool.DruidDataSource; - -import io.seata.rm.datasource.DataSourceProxy; - /** * @author xiaojing */ 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 3060a7b7..66d3ea68 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 @@ -21,8 +21,10 @@ import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.Random; +import io.seata.core.context.RootContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; @@ -38,8 +40,6 @@ import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import io.seata.core.context.RootContext; - /** * @author xiaojing */ 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 index 536cc785..89f55344 100644 --- 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 @@ -4,7 +4,7 @@ transport { #NIO NATIVE server = "NIO" #enable heartbeat - heartbeat = true + heartbeat = false #thread factory for netty thread-factory { boss-thread-prefix = "NettyBoss" @@ -28,7 +28,7 @@ transport { } service { #vgroup->rgroup - vgroup_mapping.order-service-fescar-service-group = "default" + vgroup_mapping.order-service-seata-service-group = "default" #only support single node default.grouplist = "127.0.0.1:8091" #degrade current not support @@ -46,17 +46,22 @@ client { 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" } -## metrics settings -metrics { - enabled = false - registry-type = "compact" - # multi exporters use comma divided - exporter-list = "prometheus" - exporter-prometheus-port = 9898 +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 index 6dbeb22b..b98f5704 100644 --- 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 @@ -4,7 +4,7 @@ registry { nacos { serverAddr = "localhost" - namespace = "public" + namespace = "" cluster = "default" } eureka { @@ -50,8 +50,7 @@ config { nacos { serverAddr = "localhost" - namespace = "public" - cluster = "default" + namespace = "" } consul { serverAddr = "127.0.0.1:8500" diff --git a/spring-cloud-alibaba-examples/seata-example/readme-zh.md b/spring-cloud-alibaba-examples/seata-example/readme-zh.md index cc18b559..2723de58 100644 --- a/spring-cloud-alibaba-examples/seata-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/seata-example/readme-zh.md @@ -99,12 +99,16 @@ CREATE TABLE `account_tbl` ( 点击这个页面 [https://github.com/seata/seata/releases](https://github.com/seata/seata/releases),下载最新版本的 Seata Server 端. -进入解压之后的 bin 目录,执行如下命令来启动 +进入解压之后的 bin 目录,执行如下命令来启动, 所有启动参数为可选项。 ```$shell -sh seata-server.sh -p $LISTEN_PORT -m $MODE(file or db) +sh seata-server.sh -p $LISTEN_PORT -m $MODE(file or db) -h $HOST -e $ENV ``` - +-p seata-server 监听服务端口号 +-m 存储模式,可选值:file、db。file 用于单点模式,db用于ha模式,当使用db存储模式,需要修改配置中store配置节点的数据库配置,同时在数据库中初始化[global_table、branch_table和 +lock_table](https://github.com/seata/seata/blob/develop/server/src/main/resources/db_store.sql) +-h 用于解决seata-server和业务侧跨网络问题,其配置的host值直接显示到注册中心的服务可用地址host,当跨网络时这里需要配置为公网IP或NATIP,若都在同一局域网则无需配置 +-e 用于解决多环境配置中心隔离问题 在这个示例中,采用如下命令来启动 Seata Server ```$shell 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 b862b26a..5799b2f9 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 @@ -18,16 +18,16 @@ package com.alibaba.cloud.examples; import java.sql.SQLException; +import com.alibaba.druid.pool.DruidDataSource; + +import io.seata.rm.datasource.DataSourceProxy; + import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; -import com.alibaba.druid.pool.DruidDataSource; - -import io.seata.rm.datasource.DataSourceProxy; - /** * @author xiaojing */ 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 44092bdf..ea835168 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 @@ -16,16 +16,16 @@ package com.alibaba.cloud.examples; +import io.seata.core.context.RootContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.jdbc.core.JdbcTemplate; 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; -import io.seata.core.context.RootContext; - /** * @author xiaojing */ 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 index 90cb0ede..2915b99c 100644 --- 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 @@ -4,7 +4,7 @@ transport { #NIO NATIVE server = "NIO" #enable heartbeat - heartbeat = true + heartbeat = false #thread factory for netty thread-factory { boss-thread-prefix = "NettyBoss" @@ -28,7 +28,7 @@ transport { } service { #vgroup->rgroup - vgroup_mapping.storage-service-fescar-service-group = "default" + vgroup_mapping.storage-service-seata-service-group = "default" #only support single node default.grouplist = "127.0.0.1:8091" #degrade current not support @@ -46,17 +46,22 @@ client { 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" } -## metrics settings -metrics { - enabled = false - registry-type = "compact" - # multi exporters use comma divided - exporter-list = "prometheus" - exporter-prometheus-port = 9898 +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 index 6dbeb22b..b98f5704 100644 --- 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 @@ -4,7 +4,7 @@ registry { nacos { serverAddr = "localhost" - namespace = "public" + namespace = "" cluster = "default" } eureka { @@ -50,8 +50,7 @@ config { nacos { serverAddr = "localhost" - namespace = "public" - cluster = "default" + namespace = "" } consul { serverAddr = "127.0.0.1:8500" 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 1551bedb..c5ad01e8 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,11 +1,11 @@ package com.alibaba.cloud.examples; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; - import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; import com.alibaba.csp.sentinel.slots.block.BlockException; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; + /** * @author fangjian */ 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 7dea70ee..fda03fe6 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,13 +1,13 @@ package com.alibaba.cloud.examples; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; +import com.alibaba.csp.sentinel.datasource.Converter; + import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; -import com.alibaba.csp.sentinel.datasource.Converter; - /** * @author xiaojing */ 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 9d8f41ad..60191187 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,13 +1,13 @@ 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.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; -import com.alibaba.csp.sentinel.annotation.SentinelResource; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme-zh.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme-zh.md index ed647521..ca7459db 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme-zh.md @@ -6,9 +6,9 @@ [Sentinel](https://github.com/alibaba/Sentinel) 是阿里巴巴开源的分布式系统的流量防卫组件,Sentinel 把流量作为切入点,从流量控制,熔断降级,系统负载保护等多个维度保护服务的稳定性。 -[Dubbo](http://dubbo.apache.org/)是一款高性能Java RPC框架,有对应的[SpringBoot工程](https://github.com/apache/incubator-dubbo-spring-boot-project)。 +[Dubbo](http://dubbo.apache.org/)是一款高性能Java RPC框架,有对应的[SpringBoot工程](https://github.com/apache/dubbo-spring-boot-project)。 -本项目专注于Sentinel与Dubbo的整合,关于Sentinel的更多特性可以查看[sentinel-core-example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example)。 +本项目专注于Sentinel与Dubbo的整合,关于Sentinel的更多特性可以查看[sentinel-core-example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example)。 ## 示例 @@ -66,7 +66,7 @@ Provider端在application.properties文件中定义dubbo相关的配置,比如 `sentinel-dubbo-api`模块中定义了FooService服务,内容如下: - package FooService; + package com.alibaba.cloud.examples; public interface FooService { String hello(String name); } @@ -93,7 +93,7 @@ Consumer端在服务调用之前,先定义限流规则。 `sentinel-dubbo-api`模块中定义了FooService服务,内容如下: - package FooService; + package com.alibaba.cloud.examples; public interface FooService { String hello(String name); } diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme.md b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme.md index 4686e1b1..9d22f71a 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme.md +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/readme.md @@ -7,7 +7,7 @@ This example illustrates how to use Sentinel starter to implement flow control f [Dubbo](http://dubbo.apache.org/) is a high-performance, java based open source RPC framework. -This example focus on the integration of Sentinel and Dubbo. You can see more features on [sentinel-core-example](https://github.com/spring-cloud-incubator/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example). +This example focus on the integration of Sentinel and Dubbo. You can see more features on [sentinel-core-example](https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples/sentinel-example/sentinel-core-example). ## Demo @@ -64,7 +64,7 @@ Define some configs of dubbo in `application.properties` in provider side, like `sentinel-dubbo-api` define a service named FooService: - package FooService; + package com.alibaba.cloud.examples; public interface FooService { String hello(String name); } @@ -91,7 +91,7 @@ We will configure flow control rules before service invocation in consumer side. `sentinel-dubbo-api` define a service named FooService: - package FooService; + package com.alibaba.cloud.examples; public interface FooService { String hello(String name); } 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 f6063631..905957bf 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 @@ -25,6 +25,7 @@ com.alibaba.cloud sentinel-dubbo-api + ${project.version} diff --git a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/src/main/java/com/alibaba/cloud/examples/SentinelDubboConsumerApp.java b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/src/main/java/com/alibaba/cloud/examples/SentinelDubboConsumerApp.java index d8a6d404..c49052fb 100644 --- a/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/src/main/java/com/alibaba/cloud/examples/SentinelDubboConsumerApp.java +++ b/spring-cloud-alibaba-examples/sentinel-example/sentinel-dubbo-example/sentinel-dubbo-consumer-example/src/main/java/com/alibaba/cloud/examples/SentinelDubboConsumerApp.java @@ -2,17 +2,17 @@ package com.alibaba.cloud.examples; import java.util.Collections; +import com.alibaba.csp.sentinel.slots.block.RuleConstant; +import com.alibaba.csp.sentinel.slots.block.SentinelRpcException; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; + import org.springframework.boot.WebApplicationType; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; -import com.alibaba.csp.sentinel.slots.block.RuleConstant; -import com.alibaba.csp.sentinel.slots.block.SentinelRpcException; -import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; -import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; - /** * @author fangjian */ 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 77897920..22425383 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 @@ -25,6 +25,7 @@ com.alibaba.cloud sentinel-dubbo-api + ${project.version} 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 6ccf9130..a5da97d5 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 @@ -16,7 +16,9 @@ package com.alibaba.cloud.examples; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; + +import reactor.core.publisher.Mono; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -24,9 +26,7 @@ import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.ServerWebExchange; -import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; - -import reactor.core.publisher.Mono; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author Jim 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 8e2f4efc..8ff27269 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 @@ -19,9 +19,6 @@ package com.alibaba.cloud.examples; import java.util.List; import java.util.Set; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition; import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; @@ -31,6 +28,9 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import reactor.core.publisher.Mono; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + /** * @author Jim */ 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 4c0225ce..b136f882 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 @@ -16,7 +16,9 @@ package com.alibaba.cloud.examples; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; +import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; + +import reactor.core.publisher.Mono; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -25,9 +27,7 @@ import org.springframework.http.MediaType; import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.server.ServerWebExchange; -import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler; - -import reactor.core.publisher.Mono; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author Jim 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 7ad45c14..213a2ec3 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 @@ -16,15 +16,15 @@ package com.alibaba.cloud.examples; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - 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.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + /** * @author Jim */ 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 73d9ef5a..3af8104a 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 @@ -19,9 +19,6 @@ package com.alibaba.cloud.examples; import java.util.List; import java.util.Set; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.RestController; - import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition; import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule; @@ -29,6 +26,9 @@ 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 org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RestController; + /** * @author Jim */ 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 7393707e..96164f10 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 @@ -18,13 +18,13 @@ package com.alibaba.cloud.examples; import javax.servlet.http.HttpServletRequest; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.RequestOriginParser; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.BlockResponse; import com.alibaba.csp.sentinel.adapter.gateway.zuul.fallback.ZuulBlockFallbackProvider; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + /** * @author Jim */ diff --git a/spring-cloud-alibaba-examples/sms-example/readme-zh.md b/spring-cloud-alibaba-examples/sms-example/readme-zh.md index 8a4afbad..69076551 100644 --- a/spring-cloud-alibaba-examples/sms-example/readme-zh.md +++ b/spring-cloud-alibaba-examples/sms-example/readme-zh.md @@ -306,7 +306,7 @@ Spring Boot 应用支持通过 Endpoint 来暴露相关信息,SMS Starter 也 Spring Boot1.x 可以通过访问 http://127.0.0.1:18084/sms-info 来查看 SMS Endpoint 的信息。 -Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/acutator/sms-info 来访问。 +Spring Boot2.x 可以通过访问 http://127.0.0.1:18084/actuator/sms-info 来访问。 Endpoint 内部会显示最近 20 条单个短信发送的记录和批量短信发送的记录,以及当前短信消息的配置信息(包括是**SmsReport** 还是 **SmsUp**,**队列名称**,以及对应的 **MessageListener** )。 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 index aa732d66..56bfe1df 100644 --- 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 @@ -2,13 +2,6 @@ package com.alibaba.cloud.examples; import java.util.List; -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; - import com.alibaba.alicloud.sms.ISmsService; import com.aliyun.mns.model.Message; @@ -21,6 +14,13 @@ 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 { 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 index 22d1f65f..d77d4390 100644 --- 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 @@ -3,10 +3,10 @@ package com.alibaba.cloud.examples; import java.util.LinkedList; import java.util.List; -import org.springframework.stereotype.Component; - import com.aliyun.mns.model.Message; +import org.springframework.stereotype.Component; + /** * @author 如果需要监听短信是否被对方成功接收,只需实现这个接口并初始化一个 Spring Bean 即可。 */ 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 index 7f743564..dbd9d693 100644 --- 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 @@ -1,9 +1,9 @@ package com.alibaba.cloud.examples; -import org.springframework.stereotype.Component; - import com.aliyun.mns.model.Message; +import org.springframework.stereotype.Component; + /** * @author 如果发送的短信需要接收对方回复的状态消息,只需实现该接口并初始化一个 Spring Bean 即可。 */ 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 809ebc7d..2981dbef 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,12 +15,16 @@ */ package com.alibaba.cloud.dubbo.bootstrap; -import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; - import java.util.HashMap; import java.util.Map; +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; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.ApplicationRunner; @@ -41,10 +44,7 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.client.RestTemplate; -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 static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; /** * Dubbo Spring Cloud Consumer Bootstrap 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 94b4b750..1424019c 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 d254196d..2a9c30de 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 e30a4cb3..87292db0 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,9 +15,6 @@ */ package com.alibaba.cloud.dubbo.service; -import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; -import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE; - import java.util.HashMap; import java.util.Map; @@ -37,6 +33,9 @@ import org.apache.dubbo.config.annotation.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; +import static org.springframework.util.MimeTypeUtils.APPLICATION_JSON_VALUE; + /** * Default {@link RestService} * 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 18f859af..55c40c4d 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 d254196d..2a9c30de 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 cdbefcd8..708c0921 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,14 +15,13 @@ */ package com.alibaba.cloud.dubbo.service; -import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; - import java.util.HashMap; import java.util.Map; import org.apache.dubbo.config.annotation.Service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @@ -33,6 +31,8 @@ import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import static com.alibaba.cloud.dubbo.util.LoggerUtils.log; + /** * Spring MVC {@link RestService} * 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 1bfe4b91..d916e473 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 14055cd3..5349356c 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 81df4787..1798f5f2 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 31c9af2c..b09577fc 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 6a8eee88..2626481b 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,6 +15,9 @@ */ package com.alibaba.cloud.examples.rocketmq; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -28,9 +30,6 @@ import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.ObjectMapper; - /** * RocketMQ Bus Spring Application * 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 2c9dae87..3805094e 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, 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 9979e190..d5fb804d 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,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java b/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java index 0548ff60..618da23c 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/NacosConfigServerAutoConfiguration.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,6 +15,8 @@ */ package com.alibaba.cloud.nacos.config.server; +import com.alibaba.cloud.nacos.config.server.environment.NacosEnvironmentRepository; + import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.cloud.config.server.EnableConfigServer; @@ -24,8 +25,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.config.server.environment.NacosEnvironmentRepository; - /** * Nacos Config Server Auto-Configuration * 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-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java index 694f1b1b..8f5b5310 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java +++ b/spring-cloud-alibaba-nacos-config-server/src/main/java/com/alibaba/cloud/nacos/config/server/environment/NacosEnvironmentRepository.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, @@ -16,20 +15,20 @@ */ package com.alibaba.cloud.nacos.config.server.environment; -import static com.alibaba.nacos.config.server.constant.Constants.DEFAULT_GROUP; - import java.io.IOException; import java.io.StringReader; import java.util.Properties; +import com.alibaba.nacos.config.server.model.ConfigInfo; +import com.alibaba.nacos.config.server.service.PersistService; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.config.environment.Environment; import org.springframework.cloud.config.environment.PropertySource; import org.springframework.cloud.config.server.environment.EnvironmentRepository; import org.springframework.util.StringUtils; -import com.alibaba.nacos.config.server.model.ConfigInfo; -import com.alibaba.nacos.config.server.service.PersistService; +import static com.alibaba.nacos.config.server.constant.Constants.DEFAULT_GROUP; /** * Nacos {@link EnvironmentRepository} 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-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java index d37b81d0..a1222f39 100644 --- a/spring-cloud-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java +++ b/spring-cloud-alibaba-nacos-config-server/src/test/java/com/alibaba/cloud/nacos/config/server/bootstrap/NacosConfigServerBootstrap.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java index cab15a4e..72271dd0 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigAutoConfiguration.java @@ -16,16 +16,16 @@ package com.alibaba.cloud.nacos; +import com.alibaba.cloud.nacos.refresh.NacosContextRefresher; +import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; +import com.alibaba.cloud.nacos.refresh.NacosRefreshProperties; + import org.springframework.beans.factory.BeanFactoryUtils; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.refresh.NacosContextRefresher; -import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; -import com.alibaba.cloud.nacos.refresh.NacosRefreshProperties; - /** * @author juven.xuxb */ @@ -41,8 +41,12 @@ public class NacosConfigAutoConfiguration { return BeanFactoryUtils.beanOfTypeIncludingAncestors(context.getParent(), NacosConfigProperties.class); } - NacosConfigProperties nacosConfigProperties = new NacosConfigProperties(); - return nacosConfigProperties; + return new NacosConfigProperties(); + } + + @Bean + public NacosConfigManager nacosConfigManager() { + return new NacosConfigManager(); } @Bean @@ -57,10 +61,10 @@ public class NacosConfigAutoConfiguration { @Bean public NacosContextRefresher nacosContextRefresher( - NacosConfigProperties nacosConfigProperties, + NacosConfigManager nacosConfigManager, NacosRefreshProperties nacosRefreshProperties, NacosRefreshHistory refreshHistory) { return new NacosContextRefresher(nacosRefreshProperties, refreshHistory, - nacosConfigProperties.configServiceInstance()); + nacosConfigManager.getConfigService()); } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java index 081464cd..980126a5 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigBootstrapConfiguration.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.nacos; +import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; + 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 com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; - /** * @author xiaojing */ @@ -36,10 +36,17 @@ public class NacosConfigBootstrapConfiguration { return new NacosConfigProperties(); } + @Bean + @ConditionalOnMissingBean + public NacosConfigManager nacosConfigManager() { + return new NacosConfigManager(); + } + @Bean public NacosPropertySourceLocator nacosPropertySourceLocator( + NacosConfigManager nacosConfigManager, NacosConfigProperties nacosConfigProperties) { - return new NacosPropertySourceLocator(nacosConfigProperties); + return new NacosPropertySourceLocator(nacosConfigManager, nacosConfigProperties); } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java new file mode 100644 index 00000000..abe6d872 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigManager.java @@ -0,0 +1,53 @@ +/* + * 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.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.springframework.beans.factory.annotation.Autowired; + +/** + * @author liaochuntao + */ +public class NacosConfigManager { + + private static ConfigService service = null; + + @Autowired + private NacosConfigProperties properties; + + public ConfigService getConfigService() { + if (Objects.isNull(service)) { + try { + service = NacosFactory + .createConfigService(properties.getConfigServiceProperties()); + properties.initConfigService(service); + } + catch (NacosException e) { + throw new NacosConnectionFailureException(properties.getServerAddr(), + e.getMessage(), e); + } + } + return service; + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java index 82ab1fac..411fb146 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/NacosConfigProperties.java @@ -16,44 +16,76 @@ package com.alibaba.cloud.nacos; -import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; -import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH; -import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; -import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; - import java.util.List; import java.util.Objects; import java.util.Properties; +import javax.annotation.PostConstruct; + +import com.alibaba.nacos.api.config.ConfigService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.springframework.boot.context.properties.ConfigurationProperties; -import com.alibaba.nacos.api.NacosFactory; -import com.alibaba.nacos.api.config.ConfigService; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; + +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_LONG_POLL_TIMEOUT; +import static com.alibaba.nacos.api.PropertyKeyConst.CONFIG_RETRY_TIME; +import static com.alibaba.nacos.api.PropertyKeyConst.CONTEXT_PATH; +import static com.alibaba.nacos.api.PropertyKeyConst.ENABLE_REMOTE_SYNC_CONFIG; +import static com.alibaba.nacos.api.PropertyKeyConst.ENCODE; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT; +import static com.alibaba.nacos.api.PropertyKeyConst.MAX_RETRY; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; /** - * nacos properties + * Nacos properties. * * @author leijuan * @author xiaojing * @author pbting + * @author lyuzb */ @ConfigurationProperties(NacosConfigProperties.PREFIX) public class NacosConfigProperties { + /** + * Prefix of {@link NacosConfigProperties}. + */ public static final String PREFIX = "spring.cloud.nacos.config"; private static final Logger log = LoggerFactory .getLogger(NacosConfigProperties.class); + @Autowired + private Environment environment; + + @PostConstruct + public void init() { + this.overrideFromEnv(); + } + + private void overrideFromEnv() { + if (StringUtils.isEmpty(this.getServerAddr())) { + String serverAddr = environment + .resolvePlaceholders("${spring.cloud.nacos.config.server-addr:}"); + if (StringUtils.isEmpty(serverAddr)) { + serverAddr = environment + .resolvePlaceholders("${spring.cloud.nacos.server-addr:}"); + } + this.setServerAddr(serverAddr); + } + } + /** - * nacos config server address + * nacos config server address. */ private String serverAddr; @@ -68,9 +100,10 @@ public class NacosConfigProperties { private String group = "DEFAULT_GROUP"; /** - * nacos config dataId prefix + * nacos config dataId prefix. */ private String prefix; + /** * the suffix of nacos config dataId, also the file extension of config content. */ @@ -81,6 +114,30 @@ public class NacosConfigProperties { */ private int timeout = 3000; + /** + * nacos maximum number of tolerable server reconnection errors. + */ + private String maxRetry; + + /** + * nacos get config long poll timeout. + */ + private String configLongPollTimeout; + + /** + * nacos get config failure retry time. + */ + private String configRetryTime; + + /** + * If you want to pull it yourself when the program starts to get the configuration + * for the first time, and the registered Listener is used for future configuration + * updates, you can keep the original code unchanged, just add the system parameter: + * enableRemoteSyncConfig = "true" ( But there is network overhead); therefore we + * recommend that you use {@link ConfigService#getConfigAndSignListener} directly. + */ + private boolean enableRemoteSyncConfig = false; + /** * endpoint for Nacos, the domain name of a service, through which the server address * can be dynamically obtained. @@ -108,10 +165,13 @@ public class NacosConfigProperties { private String contextPath; /** - * nacos config cluster name + * nacos config cluster name. */ private String clusterName; + /** + * nacos config dataId name. + */ private String name; /** @@ -174,6 +234,38 @@ public class NacosConfigProperties { this.timeout = timeout; } + public String getMaxRetry() { + return maxRetry; + } + + public void setMaxRetry(String maxRetry) { + this.maxRetry = maxRetry; + } + + public String getConfigLongPollTimeout() { + return configLongPollTimeout; + } + + public void setConfigLongPollTimeout(String configLongPollTimeout) { + this.configLongPollTimeout = configLongPollTimeout; + } + + public String getConfigRetryTime() { + return configRetryTime; + } + + public void setConfigRetryTime(String configRetryTime) { + this.configRetryTime = configRetryTime; + } + + public Boolean getEnableRemoteSyncConfig() { + return enableRemoteSyncConfig; + } + + public void setEnableRemoteSyncConfig(Boolean enableRemoteSyncConfig) { + this.enableRemoteSyncConfig = enableRemoteSyncConfig; + } + public String getEndpoint() { return endpoint; } @@ -262,15 +354,71 @@ public class NacosConfigProperties { this.name = name; } + /** + * @see NacosConfigManager#getConfigService() . + * @return ConfigService + */ + @Deprecated + public ConfigService configServiceInstance() { + return configService; + } + + public void initConfigService(ConfigService configService) { + this.configService = configService; + } + + public Properties getConfigServiceProperties() { + Properties properties = new Properties(); + properties.put(SERVER_ADDR, Objects.toString(this.serverAddr, "")); + properties.put(ENCODE, Objects.toString(this.encode, "")); + properties.put(NAMESPACE, Objects.toString(this.namespace, "")); + properties.put(ACCESS_KEY, Objects.toString(this.accessKey, "")); + properties.put(SECRET_KEY, Objects.toString(this.secretKey, "")); + properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, "")); + properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, "")); + properties.put(MAX_RETRY, Objects.toString(this.maxRetry, "")); + properties.put(CONFIG_LONG_POLL_TIMEOUT, + Objects.toString(this.configLongPollTimeout, "")); + properties.put(CONFIG_RETRY_TIME, Objects.toString(this.configRetryTime, "")); + properties.put(ENABLE_REMOTE_SYNC_CONFIG, + Objects.toString(this.enableRemoteSyncConfig, "")); + String endpoint = Objects.toString(this.endpoint, ""); + if (endpoint.contains(":")) { + int index = endpoint.indexOf(":"); + properties.put(ENDPOINT, endpoint.substring(0, index)); + properties.put(ENDPOINT_PORT, endpoint.substring(index + 1)); + } + else { + properties.put(ENDPOINT, endpoint); + } + return properties; + } + + @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 + '}'; + } + public static class Config { + /** - * the data id of extended configuration + * the data id of extended configuration. */ private String dataId; + /** - * the group of extended configuration, the default value is DEFAULT_GROUP + * the group of extended configuration, the default value is DEFAULT_GROUP. */ private String group = "DEFAULT_GROUP"; + /** * whether to support dynamic refresh, the default does not support . */ @@ -299,53 +447,7 @@ public class NacosConfigProperties { public void setRefresh(boolean refresh) { this.refresh = refresh; } + } - @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 + '}'; - } - - public ConfigService configServiceInstance() { - - if (null != configService) { - return configService; - } - - Properties properties = new Properties(); - properties.put(SERVER_ADDR, Objects.toString(this.serverAddr, "")); - properties.put(ENCODE, Objects.toString(this.encode, "")); - properties.put(NAMESPACE, Objects.toString(this.namespace, "")); - properties.put(ACCESS_KEY, Objects.toString(this.accessKey, "")); - properties.put(SECRET_KEY, Objects.toString(this.secretKey, "")); - properties.put(CONTEXT_PATH, Objects.toString(this.contextPath, "")); - properties.put(CLUSTER_NAME, Objects.toString(this.clusterName, "")); - - String endpoint = Objects.toString(this.endpoint, ""); - if (endpoint.contains(":")) { - int index = endpoint.indexOf(":"); - properties.put(ENDPOINT, endpoint.substring(0, index)); - properties.put(ENDPOINT_PORT, endpoint.substring(index + 1)); - } - else { - properties.put(ENDPOINT, endpoint); - } - - try { - configService = NacosFactory.createConfigService(properties); - return configService; - } - catch (Exception e) { - log.error("create config service error!properties={},e=,", this, e); - return null; - } - } } 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 index ea011b00..f7937336 100644 --- 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 @@ -16,11 +16,11 @@ 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; +import com.google.common.collect.Lists; /** * @author xiaojing @@ -34,9 +34,7 @@ public class NacosPropertySourceRepository { * @return all nacos properties from application context */ public static List getAll() { - List result = new ArrayList<>(); - result.addAll(NACOS_PROPERTY_SOURCE_REPOSITORY.values()); - return result; + return Lists.newArrayList(NACOS_PROPERTY_SOURCE_REPOSITORY.values()); } public static void collectNacosPropertySources( diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java index e10c9a30..9dbfe8bf 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceBuilder.java @@ -16,23 +16,22 @@ package com.alibaba.cloud.nacos.client; -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 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; - 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; + +import org.springframework.util.StringUtils; + /** * @author xiaojing * @author pbting @@ -83,24 +82,19 @@ public class NacosPropertySourceBuilder { String data = null; try { data = configService.getConfig(dataId, group, timeout); - if (!StringUtils.isEmpty(data)) { - log.info(String.format("Loading nacos data, dataId: '%s', group: '%s'", - dataId, group)); - - if (fileExtension.equalsIgnoreCase("properties")) { - Properties properties = new Properties(); - - properties.load(new StringReader(data)); - return properties; - } - else if (fileExtension.equalsIgnoreCase("yaml") - || fileExtension.equalsIgnoreCase("yml")) { - YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); - yamlFactory.setResources(new ByteArrayResource(data.getBytes())); - return yamlFactory.getObject(); - } - + if (StringUtils.isEmpty(data)) { + log.warn( + "Ignore the empty nacos configuration and get it based on dataId[{}] & group[{}]", + dataId, group); + return EMPTY_PROPERTIES; } + log.info(String.format( + "Loading nacos data, dataId: '%s', group: '%s', data: %s", dataId, + group, data)); + + Properties properties = NacosDataParserHandler.getInstance() + .parseNacosData(data, fileExtension); + return properties == null ? EMPTY_PROPERTIES : properties; } catch (NacosException e) { log.error("get data from Nacos error,dataId:{}, ", dataId, e); @@ -117,9 +111,9 @@ public class NacosPropertySourceBuilder { Enumeration keys = (Enumeration) properties.propertyNames(); while (keys.hasMoreElements()) { String key = keys.nextElement(); - Object value = properties.getProperty(key); + String value = properties.getProperty(key); if (value != null) { - result.put(key, ((String) value).trim()); + result.put(key, value.trim()); } else { result.put(key, null); diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java index 51541602..ee6e3952 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/client/NacosPropertySourceLocator.java @@ -16,23 +16,26 @@ package com.alibaba.cloud.nacos.client; -import java.util.Arrays; 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; + import org.springframework.cloud.bootstrap.config.PropertySourceLocator; import org.springframework.core.annotation.Order; import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; +import org.springframework.util.CollectionUtils; import org.springframework.util.StringUtils; -import com.alibaba.cloud.nacos.NacosConfigProperties; -import com.alibaba.cloud.nacos.NacosPropertySourceRepository; -import com.alibaba.cloud.nacos.refresh.NacosContextRefresher; -import com.alibaba.nacos.api.config.ConfigService; - /** * @author xiaojing * @author pbting @@ -42,25 +45,31 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { private static final Logger log = LoggerFactory .getLogger(NacosPropertySourceLocator.class); + private static final String NACOS_PROPERTY_SOURCE_NAME = "NACOS"; + private static final String SEP1 = "-"; + private static final String DOT = "."; + private static final String SHARED_CONFIG_SEPARATOR_CHAR = "[,]"; - private static final List SUPPORT_FILE_EXTENSION = Arrays.asList("properties", - "yaml", "yml"); private NacosPropertySourceBuilder nacosPropertySourceBuilder; private NacosConfigProperties nacosConfigProperties; - public NacosPropertySourceLocator(NacosConfigProperties nacosConfigProperties) { + private NacosConfigManager nacosConfigManager; + + public NacosPropertySourceLocator(NacosConfigManager nacosConfigManager, + NacosConfigProperties nacosConfigProperties) { + this.nacosConfigManager = nacosConfigManager; this.nacosConfigProperties = nacosConfigProperties; } @Override public PropertySource locate(Environment env) { - ConfigService configService = nacosConfigProperties.configServiceInstance(); + ConfigService configService = nacosConfigManager.getConfigService(); if (null == configService) { log.warn("no instance of config service found, can't load config from nacos"); @@ -99,14 +108,14 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { return; } - String[] sharedDataIdArry = sharedDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); - checkDataIdFileExtension(sharedDataIdArry); + String[] sharedDataIdArray = sharedDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); + checkDataIdFileExtension(sharedDataIdArray); - for (int i = 0; i < sharedDataIdArry.length; i++) { - String dataId = sharedDataIdArry[i]; + for (int i = 0; i < sharedDataIdArray.length; i++) { + String dataId = sharedDataIdArray[i]; String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1); - boolean isRefreshable = checkDataIdIsRefreshbable(refreshDataIds, - sharedDataIdArry[i]); + boolean isRefreshable = checkDataIdIsRefreshable(refreshDataIds, + sharedDataIdArray[i]); loadNacosDataIfPresent(compositePropertySource, dataId, "DEFAULT_GROUP", fileExtension, isRefreshable); @@ -114,18 +123,18 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { } private void loadExtConfiguration(CompositePropertySource compositePropertySource) { - if (nacosConfigProperties.getExtConfig() == null - || nacosConfigProperties.getExtConfig().isEmpty()) { + List extConfigs = nacosConfigProperties + .getExtConfig(); + + if (CollectionUtils.isEmpty(extConfigs)) { return; } - List extConfigs = nacosConfigProperties - .getExtConfig(); checkExtConfiguration(extConfigs); for (NacosConfigProperties.Config config : extConfigs) { String dataId = config.getDataId(); - String fileExtension = dataId.substring(dataId.lastIndexOf(".") + 1); + String fileExtension = dataId.substring(dataId.lastIndexOf(DOT) + 1); loadNacosDataIfPresent(compositePropertySource, dataId, config.getGroup(), fileExtension, config.isRefresh()); } @@ -137,7 +146,7 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { 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", + "the [ spring.cloud.nacos.config.ext-config[%s] ] must give a dataId", i)); } dataIds[i] = dataId; @@ -152,8 +161,13 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { String fileExtension = properties.getFileExtension(); String nacosGroup = properties.getGroup(); + // load directly once by default + loadNacosDataIfPresent(compositePropertySource, dataIdPrefix, nacosGroup, + fileExtension, true); + // load with suffix, which have a higher priority than the default loadNacosDataIfPresent(compositePropertySource, dataIdPrefix + DOT + fileExtension, nacosGroup, fileExtension, true); + // Loaded with profile, which have a higher priority than the suffix for (String profile : environment.getActiveProfiles()) { String dataId = dataIdPrefix + SEP1 + profile + DOT + fileExtension; loadNacosDataIfPresent(compositePropertySource, dataId, nacosGroup, @@ -164,56 +178,58 @@ public class NacosPropertySourceLocator implements PropertySourceLocator { private void loadNacosDataIfPresent(final CompositePropertySource composite, final String dataId, final String group, String fileExtension, boolean isRefreshable) { - if (NacosContextRefresher.getRefreshCount() != 0) { - NacosPropertySource ps; - if (!isRefreshable) { - ps = NacosPropertySourceRepository.getNacosPropertySource(dataId); - } - else { - ps = nacosPropertySourceBuilder.build(dataId, group, fileExtension, true); - } + if (null == dataId || dataId.trim().length() < 1) { + return; + } + if (null == group || group.trim().length() < 1) { + return; + } + NacosPropertySource propertySource = this.loadNacosPropertySource(dataId, group, + fileExtension, isRefreshable); + this.addFirstPropertySource(composite, propertySource, false); + } - composite.addFirstPropertySource(ps); + private NacosPropertySource loadNacosPropertySource(final String dataId, + final String group, String fileExtension, boolean isRefreshable) { + if (NacosContextRefresher.getRefreshCount() != 0) { + if (!isRefreshable) { + return NacosPropertySourceRepository.getNacosPropertySource(dataId); + } } - else { - NacosPropertySource ps = nacosPropertySourceBuilder.build(dataId, group, - fileExtension, isRefreshable); - composite.addFirstPropertySource(ps); + return nacosPropertySourceBuilder.build(dataId, group, fileExtension, + isRefreshable); + } + + /** + * Add the nacos configuration to the first place and maybe ignore the empty + * configuration. + */ + private void addFirstPropertySource(final CompositePropertySource composite, + NacosPropertySource nacosPropertySource, boolean ignoreEmpty) { + if (null == nacosPropertySource || null == composite) { + return; } + if (ignoreEmpty && nacosPropertySource.getSource().isEmpty()) { + return; + } + composite.addFirstPropertySource(nacosPropertySource); } private static void checkDataIdFileExtension(String[] dataIdArray) { - StringBuilder stringBuilder = new StringBuilder(); - for (int i = 0; i < dataIdArray.length; i++) { - boolean isLegal = false; - for (String fileExtension : SUPPORT_FILE_EXTENSION) { - if (dataIdArray[i].indexOf(fileExtension) > 0) { - isLegal = true; - break; - } - } - // add tips - if (!isLegal) { - stringBuilder.append(dataIdArray[i] + ","); - } - } - - if (stringBuilder.length() > 0) { - String result = stringBuilder.substring(0, stringBuilder.length() - 1); - throw new IllegalStateException(String.format( - "[%s] must contains file extension with properties|yaml|yml", - result)); + 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 checkDataIdIsRefreshbable(String refreshDataIds, - String sharedDataId) { - if (refreshDataIds == null || "".equals(refreshDataIds)) { + private boolean checkDataIdIsRefreshable(String refreshDataIds, String sharedDataId) { + if (StringUtils.isEmpty(refreshDataIds)) { return false; } - String[] refreshDataIdArry = refreshDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); - for (String refreshDataId : refreshDataIdArry) { + String[] refreshDataIdArray = refreshDataIds.split(SHARED_CONFIG_SEPARATOR_CHAR); + for (String refreshDataId : refreshDataIdArray) { if (refreshDataId.equals(sharedDataId)) { return true; } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java index 10b1e20a..3c7ae0e2 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureAnalyzer.java @@ -31,7 +31,10 @@ public class NacosConnectionFailureAnalyzer @Override protected FailureAnalysis analyze(Throwable rootFailure, NacosConnectionFailureException cause) { - return new FailureAnalysis("Application failed to connect to Nacos server", - "check your nacos server config", cause); + return new FailureAnalysis( + "Application failed to connect to Nacos server: \"" + + cause.getServerAddr() + "\"", + "Please check your Nacos server config", cause); } + } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java index f01458d4..2e9efd94 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/diagnostics/analyzer/NacosConnectionFailureException.java @@ -24,29 +24,21 @@ package com.alibaba.cloud.nacos.diagnostics.analyzer; */ public class NacosConnectionFailureException extends RuntimeException { - private final String domain; + private final String serverAddr; - private final String port; - - public NacosConnectionFailureException(String domain, String port, String message) { + public NacosConnectionFailureException(String serverAddr, String message) { super(message); - this.domain = domain; - this.port = port; + this.serverAddr = serverAddr; } - public NacosConnectionFailureException(String domain, String port, String message, + public NacosConnectionFailureException(String serverAddr, String message, Throwable cause) { super(message, cause); - this.domain = domain; - this.port = port; + this.serverAddr = serverAddr; } - String getDomain() { - return domain; - } - - String getPort() { - return port; + public String getServerAddr() { + return serverAddr; } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java index e42a5421..7241bb55 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpoint.java @@ -23,16 +23,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - import com.alibaba.cloud.nacos.NacosConfigProperties; import com.alibaba.cloud.nacos.NacosPropertySourceRepository; import com.alibaba.cloud.nacos.client.NacosPropertySource; import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; + /** - * Endpoint for Nacos, contains config data and refresh history + * Endpoint for Nacos, contains config data and refresh history. + * * @author xiaojing */ @Endpoint(id = "nacos-config") @@ -42,12 +43,8 @@ public class NacosConfigEndpoint { private final NacosRefreshHistory refreshHistory; - private ThreadLocal dateFormat = new ThreadLocal() { - @Override - protected DateFormat initialValue() { - return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); - } - }; + private ThreadLocal dateFormat = ThreadLocal + .withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")); public NacosConfigEndpoint(NacosConfigProperties properties, NacosRefreshHistory refreshHistory) { diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java index 2ebeeb5e..aae68ae5 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointAutoConfiguration.java @@ -16,6 +16,10 @@ package com.alibaba.cloud.nacos.endpoint; +import com.alibaba.cloud.nacos.NacosConfigManager; +import com.alibaba.cloud.nacos.NacosConfigProperties; +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.endpoint.annotation.Endpoint; @@ -25,9 +29,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; -import com.alibaba.cloud.nacos.NacosConfigProperties; -import com.alibaba.cloud.nacos.refresh.NacosRefreshHistory; - /** * @author xiaojing */ @@ -39,6 +40,9 @@ public class NacosConfigEndpointAutoConfiguration { @Autowired private NacosConfigProperties nacosConfigProperties; + @Autowired + private NacosConfigManager nacosConfigManager; + @Autowired private NacosRefreshHistory nacosRefreshHistory; @@ -51,7 +55,6 @@ public class NacosConfigEndpointAutoConfiguration { @Bean public NacosConfigHealthIndicator nacosConfigHealthIndicator() { - return new NacosConfigHealthIndicator(nacosConfigProperties, - 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-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java index 4954378c..bdbd56f9 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosConfigHealthIndicator.java @@ -16,58 +16,27 @@ package com.alibaba.cloud.nacos.endpoint; -import java.util.ArrayList; -import java.util.List; +import com.alibaba.nacos.api.config.ConfigService; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; -import org.springframework.util.StringUtils; - -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; /** * @author xiaojing */ public class NacosConfigHealthIndicator extends AbstractHealthIndicator { - private final NacosConfigProperties nacosConfigProperties; - - private final List dataIds; - private final ConfigService configService; - public NacosConfigHealthIndicator(NacosConfigProperties nacosConfigProperties, - ConfigService configService) { - this.nacosConfigProperties = nacosConfigProperties; + public NacosConfigHealthIndicator(ConfigService configService) { this.configService = configService; - - this.dataIds = new ArrayList<>(); - for (NacosPropertySource nacosPropertySource : NacosPropertySourceRepository - .getAll()) { - this.dataIds.add(nacosPropertySource.getDataId()); - } } @Override protected void doHealthCheck(Health.Builder builder) throws Exception { - for (String dataId : dataIds) { - try { - String config = configService.getConfig(dataId, - nacosConfigProperties.getGroup(), - nacosConfigProperties.getTimeout()); - if (StringUtils.isEmpty(config)) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, nacosConfigProperties.getGroup()), "config is empty"); - } - } - catch (Exception e) { - builder.down().withDetail(String.format("dataId: '%s', group: '%s'", - dataId, nacosConfigProperties.getGroup()), e.getMessage()); - } - } - builder.up().withDetail("dataIds", dataIds); + builder.up(); + + String status = configService.getServerStatus(); + builder.status(status); } } diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java new file mode 100644 index 00000000..626db91f --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/AbstractNacosDataParser.java @@ -0,0 +1,157 @@ +/* + * 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.Map; +import java.util.Properties; + +import com.alibaba.nacos.client.utils.StringUtils; + +/** + * @author zkz + */ +public abstract class AbstractNacosDataParser { + + protected static final String DOT = "."; + + protected static final String VALUE = "value"; + + private String extension; + + private AbstractNacosDataParser nextParser; + + protected AbstractNacosDataParser(String extension) { + if (StringUtils.isEmpty(extension)) { + throw new IllegalArgumentException("extension cannot be empty"); + } + this.extension = extension.toLowerCase(); + } + + /** + * Verify dataId extensions. + * @param extension file extension. json or xml or yml or yaml or properties + * @return valid or not + */ + public final boolean checkFileExtension(String extension) { + if (this.isLegal(extension.toLowerCase())) { + return true; + } + if (this.nextParser == null) { + return false; + } + return this.nextParser.checkFileExtension(extension); + + } + + /** + * Parsing nacos configuration content. + * @param data config data from Nacos + * @param extension file extension. json or xml or yml or yaml or properties + * @return result of Properties + * @throws IOException thrown if there is a problem parsing config. + */ + public final Properties parseNacosData(String data, String extension) + throws IOException { + if (extension == null || extension.length() < 1) { + throw new IllegalStateException("The file extension cannot be empty"); + } + if (this.isLegal(extension.toLowerCase())) { + return this.doParse(data); + } + if (this.nextParser == null) { + throw new IllegalStateException(getTips(extension)); + } + return this.nextParser.parseNacosData(data, extension); + } + + /** + * Core logic for parsing. + * @param data config from Nacos + * @return result of Properties + * @throws IOException thrown if there is a problem parsing config. + */ + protected abstract Properties doParse(String data) throws IOException; + + protected AbstractNacosDataParser setNextParser(AbstractNacosDataParser nextParser) { + this.nextParser = nextParser; + return this; + } + + public AbstractNacosDataParser addNextParser(AbstractNacosDataParser nextParser) { + if (this.nextParser == null) { + this.nextParser = nextParser; + } + else { + this.nextParser.addNextParser(nextParser); + } + return this; + } + + protected boolean isLegal(String extension) { + return this.extension.equalsIgnoreCase(extension) + || 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()) { + String key = entry.getKey(); + if (StringUtils.isBlank(key)) { + continue; + } + key = key.startsWith(DOT) ? key.replaceFirst("\\.", "") : key; + properties.put(key, entry.getValue()); + } + return properties; + } + + /** + * Reload the key ending in `value` if need. + */ + protected Map reloadMap(Map map) { + if (map == null || map.isEmpty()) { + return null; + } + Map result = new HashMap<>(map); + for (Map.Entry entry : map.entrySet()) { + String key = entry.getKey(); + if (key.contains(DOT)) { + int idx = key.lastIndexOf(DOT); + String suffix = key.substring(idx + 1); + if (VALUE.equalsIgnoreCase(suffix)) { + result.put(key.substring(0, idx), entry.getValue()); + } + } + } + return result; + } + + public static String getTips(String fileName) { + return String.format( + "[%s] must contains file extension with properties|yaml|yml|xml|json", + fileName); + } + +} 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 new file mode 100644 index 00000000..a4fbe327 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataJsonParser.java @@ -0,0 +1,93 @@ +/* + * 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.alibaba.nacos.client.utils.StringUtils; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +/** + * @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/NacosDataParserHandler.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java new file mode 100644 index 00000000..e40f7f24 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataParserHandler.java @@ -0,0 +1,88 @@ +/* + * 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.Properties; + +/** + * @author zkz + */ +public final class NacosDataParserHandler { + + private AbstractNacosDataParser parser; + + private NacosDataParserHandler() { + parser = this.createParser(); + } + + /** + * 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 + * @throws IOException thrown if there is a problem parsing config. + */ + public Properties parseNacosData(String data, String extension) throws IOException { + if (null == parser) { + parser = this.createParser(); + } + return parser.parseNacosData(data, extension); + } + + /** + * check the validity of file extensions in dataid. + * @param dataIdAry array of dataId + * @return dataId handle success or not + */ + public boolean checkDataId(String... dataIdAry) { + StringBuilder stringBuilder = new StringBuilder(); + for (String dataId : dataIdAry) { + int idx = dataId.lastIndexOf(AbstractNacosDataParser.DOT); + if (idx > 0 && idx < dataId.length() - 1) { + String extension = dataId.substring(idx + 1); + if (parser.checkFileExtension(extension)) { + break; + } + } + // add tips + stringBuilder.append(dataId).append(","); + } + if (stringBuilder.length() > 0) { + String result = stringBuilder.substring(0, stringBuilder.length() - 1); + throw new IllegalStateException(AbstractNacosDataParser.getTips(result)); + } + return true; + } + + private AbstractNacosDataParser createParser() { + return new NacosDataPropertiesParser().addNextParser(new NacosDataYamlParser()) + .addNextParser(new NacosDataXmlParser()) + .addNextParser(new NacosDataJsonParser()); + } + + public static NacosDataParserHandler getInstance() { + return ParserHandler.HANDLER; + } + + private static class ParserHandler { + + private static final NacosDataParserHandler HANDLER = new NacosDataParserHandler(); + + } + +} diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/SentinelDataSourceConstants.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java similarity index 57% rename from spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/SentinelDataSourceConstants.java rename to spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java index 5240ba26..f0599bd2 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/SentinelDataSourceConstants.java +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataPropertiesParser.java @@ -14,13 +14,25 @@ * limitations under the License. */ -package com.alibaba.cloud.sentinel.datasource; +package com.alibaba.cloud.nacos.parser; + +import java.io.IOException; +import java.io.StringReader; +import java.util.Properties; /** - * @author Jim + * @author zkz */ -public interface SentinelDataSourceConstants { +public class NacosDataPropertiesParser extends AbstractNacosDataParser { - String PROPERTY_PREFIX = "spring.cloud.sentinel"; + 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/parser/NacosDataXmlParser.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java new file mode 100644 index 00000000..f9e0173c --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataXmlParser.java @@ -0,0 +1,130 @@ +/* + * 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.HashMap; +import java.util.Map; +import java.util.Properties; + +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; + +import com.alibaba.nacos.client.utils.StringUtils; + +import org.w3c.dom.Document; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource; + +/** + * With relatively few usage scenarios, only simple parsing is performed to reduce jar + * dependencies. + * + * @author zkz + */ +public class NacosDataXmlParser extends AbstractNacosDataParser { + + public NacosDataXmlParser() { + super("xml"); + } + + @Override + protected Properties doParse(String data) throws IOException { + if (StringUtils.isEmpty(data)) { + return null; + } + Map map = parseXml2Map(data); + return this.generateProperties(this.reloadMap(map)); + } + + private Map parseXml2Map(String xml) throws IOException { + xml = xml.replaceAll("\\r", "").replaceAll("\\n", "").replaceAll("\\t", ""); + Map map = new HashMap<>(32); + try { + DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance() + .newDocumentBuilder(); + Document document = documentBuilder + .parse(new InputSource(new StringReader(xml))); + if (null == document) { + return null; + } + parseNodeList(document.getChildNodes(), map, ""); + } + catch (Exception e) { + throw new IOException("The xml content parse error.", e.getCause()); + } + return map; + } + + private void parseNodeList(NodeList nodeList, Map map, + String parentKey) { + if (nodeList == null || nodeList.getLength() < 1) { + return; + } + parentKey = parentKey == null ? "" : parentKey; + for (int i = 0; i < nodeList.getLength(); i++) { + Node node = nodeList.item(i); + String value = node.getNodeValue(); + value = value == null ? "" : value.trim(); + String name = node.getNodeName(); + name = name == null ? "" : name.trim(); + + if (StringUtils.isEmpty(name)) { + continue; + } + + String key = StringUtils.isEmpty(parentKey) ? name : parentKey + DOT + name; + NamedNodeMap nodeMap = node.getAttributes(); + parseNodeAttr(nodeMap, map, key); + if (node.getNodeType() == Node.ELEMENT_NODE && node.hasChildNodes()) { + parseNodeList(node.getChildNodes(), map, key); + continue; + } + if (value.length() < 1) { + continue; + } + map.put(parentKey, value); + } + } + + private void parseNodeAttr(NamedNodeMap nodeMap, Map map, + String parentKey) { + if (null == nodeMap || nodeMap.getLength() < 1) { + return; + } + for (int i = 0; i < nodeMap.getLength(); i++) { + Node node = nodeMap.item(i); + if (null == node) { + continue; + } + if (node.getNodeType() == Node.ATTRIBUTE_NODE) { + if (StringUtils.isEmpty(node.getNodeName())) { + continue; + } + if (StringUtils.isEmpty(node.getNodeValue())) { + continue; + } + map.put(String.join(DOT, parentKey, node.getNodeName()), + node.getNodeValue()); + } + } + } + +} diff --git a/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java new file mode 100644 index 00000000..74898027 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/main/java/com/alibaba/cloud/nacos/parser/NacosDataYamlParser.java @@ -0,0 +1,39 @@ +/* + * 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.util.Properties; + +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean; +import org.springframework.core.io.ByteArrayResource; + +/** + * @author zkz + */ +public class NacosDataYamlParser extends AbstractNacosDataParser { + + public NacosDataYamlParser() { + super(",yml,yaml,"); + } + + @Override + protected Properties doParse(String data) { + YamlPropertiesFactoryBean yamlFactory = new YamlPropertiesFactoryBean(); + yamlFactory.setResources(new ByteArrayResource(data.getBytes())); + return yamlFactory.getObject(); + } +} 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 index 7512b283..ad50b614 100644 --- 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 @@ -26,8 +26,15 @@ 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; @@ -35,12 +42,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.util.StringUtils; -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; - /** * On application start up, NacosContextRefresher add nacos listeners to all application * level dataIds, when there is a change in the data, listeners will refresh diff --git a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 597126e8..c9c87261 100644 --- a/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-nacos-config/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,5 +1,16 @@ { "properties": [ + { + "name": "spring.cloud.nacos.server-addr", + "type": "java.lang.String", + "description": "nacos server address." + }, + { + "name": "spring.cloud.nacos.config.server-addr", + "type": "java.lang.String", + "defaultValue": "${spring.cloud.nacos.server-addr}", + "description": "nacos config server address." + }, { "name": "spring.cloud.nacos.config.encode", "type": "java.lang.String", diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java new file mode 100644 index 00000000..328c1859 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressBothLevelTests.java @@ -0,0 +1,42 @@ +package com.alibaba.cloud.nacos; + +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; + +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.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 = 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 + private NacosConfigProperties properties; + + @Test + public void testGetServerAddr() { + assertEquals("NacosConfigProperties server address was wrong", + "321,321,321,321:8848", properties.getServerAddr()); + } + + @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/NacosConfigPropertiesServerAddressTopLevelTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java new file mode 100644 index 00000000..a32e4b4a --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigPropertiesServerAddressTopLevelTests.java @@ -0,0 +1,41 @@ +package com.alibaba.cloud.nacos; + +import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; + +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.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 = NacosConfigPropertiesServerAddressTopLevelTests.TestConfig.class, properties = { + "spring.cloud.nacos.server-addr=123.123.123.123:8848" }, webEnvironment = RANDOM_PORT) +public class NacosConfigPropertiesServerAddressTopLevelTests { + + @Autowired + private NacosConfigProperties properties; + + @Test + public void testGetServerAddr() { + assertEquals("NacosConfigProperties server address was wrong", + "123.123.123.123:8848", properties.getServerAddr()); + } + + @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/NacosConfigurationExtConfigTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java index 46760321..a7a3def2 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationExtConfigTests.java @@ -16,12 +16,13 @@ package com.alibaba.cloud.nacos; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - import java.lang.reflect.InvocationHandler; 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; @@ -31,6 +32,7 @@ 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; @@ -39,9 +41,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.client.NacosPropertySourceLocator; -import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; -import com.alibaba.nacos.client.config.NacosConfigService; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java index 1f80136c..9f6380b5 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationTests.java @@ -16,14 +16,16 @@ package com.alibaba.cloud.nacos; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - 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.Assert; import org.junit.Test; import org.junit.runner.RunWith; @@ -33,6 +35,7 @@ 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; @@ -41,11 +44,9 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -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 static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java new file mode 100644 index 00000000..43c19456 --- /dev/null +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosConfigurationXmlJsonTest.java @@ -0,0 +1,252 @@ +/* + * 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.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.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.NONE; + +/** + * @author zkz + */ + +@RunWith(PowerMockRunner.class) +@PowerMockIgnore("javax.management.*") +@PowerMockRunnerDelegate(SpringRunner.class) +@PrepareForTest({ NacosConfigService.class }) +@SpringBootTest(classes = NacosConfigurationXmlJsonTest.TestConfig.class, properties = { + "spring.application.name=xmlApp", "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-name", + "spring.cloud.nacos.config.cluster-name=test-cluster", + "spring.cloud.nacos.config.file-extension=xml", + "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", + "spring.cloud.nacos.config.accessKey=test-accessKey", + "spring.cloud.nacos.config.secretKey=test-secretKey" }, webEnvironment = NONE) +public class NacosConfigurationXmlJsonTest { + + 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 ("xmlApp.xml".equals(args[0]) && "test-group".equals(args[1])) { + return "\n" + " one\n" + + " \n" + + " three\n" + " \n" + + ""; + } + if ("test-name.xml".equals(args[0]) && "test-group".equals(args[1])) { + return " \n" + + " \n" + + " \n" + + " 开启服务 \n" + + " 初始化一下 \n" + + " \n" + " \n" + + " one\n" + + " \n" + + " three\n" + + " \n" + + " \n" + " \n" + + " 销毁一下 \n" + + " 关闭服务 \n" + + " \n" + " \n" + + " "; + } + + if ("test-name-dev.xml".equals(args[0]) + && "test-group".equals(args[1])) { + return "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + " \n" + + ""; + } + + 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"; + } + + return ""; + } + }); + + } + catch (Exception ignore) { + ignore.printStackTrace(); + + } + } + + @Autowired + private NacosPropertySourceLocator locator; + + @Autowired + private NacosConfigProperties properties; + + @Autowired + private NacosRefreshHistory refreshHistory; + + @Test + public void contextLoads() throws Exception { + + assertNotNull("NacosPropertySourceLocator was not created", locator); + assertNotNull("NacosConfigProperties was not created", properties); + + checkoutNacosConfigServerAddr(); + checkoutNacosConfigNamespace(); + checkoutNacosConfigClusterName(); + checkoutNacosConfigAccessKey(); + checkoutNacosConfigSecrectKey(); + checkoutNacosConfigName(); + checkoutNacosConfigGroup(); + checkoutNacosConfigContextPath(); + checkoutNacosConfigFileExtension(); + checkoutNacosConfigTimeout(); + checkoutNacosConfigEncode(); + + checkoutEndpoint(); + + } + + private void checkoutNacosConfigServerAddr() { + assertEquals("NacosConfigProperties server address is wrong", "127.0.0.1:8848", + properties.getServerAddr()); + } + + private void checkoutNacosConfigNamespace() { + assertEquals("NacosConfigProperties namespace is wrong", "test-namespace", + properties.getNamespace()); + } + + private void checkoutNacosConfigClusterName() { + assertEquals("NacosConfigProperties' cluster is wrong", "test-cluster", + properties.getClusterName()); + } + + private void checkoutNacosConfigAccessKey() { + assertEquals("NacosConfigProperties' is access key is wrong", "test-accessKey", + properties.getAccessKey()); + } + + private void checkoutNacosConfigSecrectKey() { + assertEquals("NacosConfigProperties' is secret key is wrong", "test-secretKey", + properties.getSecretKey()); + } + + private void checkoutNacosConfigContextPath() { + assertEquals("NacosConfigProperties' context path is wrong", "test-contextpath", + properties.getContextPath()); + } + + private void checkoutNacosConfigName() { + assertEquals("NacosConfigProperties' name is wrong", "test-name", + properties.getName()); + } + + private void checkoutNacosConfigGroup() { + assertEquals("NacosConfigProperties' group is wrong", "test-group", + properties.getGroup()); + } + + private void checkoutNacosConfigFileExtension() { + assertEquals("NacosConfigProperties' file extension is wrong", "xml", + properties.getFileExtension()); + } + + private void checkoutNacosConfigTimeout() { + assertEquals("NacosConfigProperties' timeout is wrong", 1000, + properties.getTimeout()); + } + + private void checkoutNacosConfigEncode() { + assertEquals("NacosConfigProperties' encode is wrong", "utf-8", + properties.getEncode()); + } + + 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()); + } + + @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/NacosFileExtensionTest.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java index e4806e66..ef99aaf6 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/NacosFileExtensionTest.java @@ -16,11 +16,12 @@ package com.alibaba.cloud.nacos; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - import java.lang.reflect.InvocationHandler; 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; @@ -30,6 +31,7 @@ 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; @@ -38,8 +40,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.endpoint.NacosConfigEndpointAutoConfiguration; -import com.alibaba.nacos.client.config.NacosConfigService; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing diff --git a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java index 78b5c13a..ec26ab60 100644 --- a/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java +++ b/spring-cloud-alibaba-nacos-config/src/test/java/com/alibaba/cloud/nacos/endpoint/NacosConfigEndpointTests.java @@ -16,16 +16,16 @@ package com.alibaba.cloud.nacos.endpoint; -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - -import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.List; import java.util.Map; -import org.junit.Assert; +import com.alibaba.cloud.nacos.NacosConfigAutoConfiguration; +import com.alibaba.cloud.nacos.NacosConfigBootstrapConfiguration; +import com.alibaba.cloud.nacos.NacosConfigManager; +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; @@ -34,6 +34,7 @@ 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.actuate.health.Health.Builder; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @@ -42,11 +43,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosConfigAutoConfiguration; -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 static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing @@ -68,17 +66,13 @@ public class NacosConfigEndpointTests { 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 { + 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 ""; + if ("test-name.properties".equals(args[0]) + && "DEFAULT_GROUP".equals(args[1])) { + return "user.name=hello\nuser.age=12"; } + return ""; }); } @@ -91,6 +85,9 @@ public class NacosConfigEndpointTests { @Autowired private NacosConfigProperties properties; + @Autowired + private NacosConfigManager nacosConfigManager; + @Autowired private NacosRefreshHistory refreshHistory; @@ -98,7 +95,7 @@ public class NacosConfigEndpointTests { public void contextLoads() throws Exception { checkoutEndpoint(); - checkoutAcmHealthIndicator(); + // checkoutAcmHealthIndicator(); } @@ -107,18 +104,16 @@ public class NacosConfigEndpointTests { Builder builder = new Builder(); NacosConfigHealthIndicator healthIndicator = new NacosConfigHealthIndicator( - properties, properties.configServiceInstance()); + nacosConfigManager.getConfigService()); healthIndicator.doHealthCheck(builder); Builder builder1 = new Builder(); - List dataIds = new ArrayList<>(); - dataIds.add("test-name.properties"); - builder1.up().withDetail("dataIds", dataIds); + builder1.up(); - Assert.assertTrue(builder.build().equals(builder1.build())); + assertEquals(builder1.build(), builder.build()); } - catch (Exception ignoreE) { + catch (Exception ignore) { } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java index 180f1fa8..1dbbaebb 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryAutoConfiguration.java @@ -16,6 +16,10 @@ package com.alibaba.cloud.nacos; +import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration; +import com.alibaba.cloud.nacos.registry.NacosRegistration; +import com.alibaba.cloud.nacos.registry.NacosServiceRegistry; + import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -27,10 +31,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.registry.NacosAutoServiceRegistration; -import com.alibaba.cloud.nacos.registry.NacosRegistration; -import com.alibaba.cloud.nacos.registry.NacosServiceRegistry; - /** * @author xiaojing * @author Mercy @@ -45,16 +45,23 @@ public class NacosDiscoveryAutoConfiguration { @Bean public NacosServiceRegistry nacosServiceRegistry( + NacosNamingManager nacosNamingManager, NacosDiscoveryProperties nacosDiscoveryProperties) { - return new NacosServiceRegistry(nacosDiscoveryProperties); + return new NacosServiceRegistry(nacosNamingManager, nacosDiscoveryProperties); + } + + @Bean + public NacosNamingManager nacosNamingManager() { + return new NacosNamingManager(); } @Bean @ConditionalOnBean(AutoServiceRegistrationProperties.class) - public NacosRegistration nacosRegistration( + public NacosRegistration nacosRegistration(NacosNamingManager nacosNamingManager, NacosDiscoveryProperties nacosDiscoveryProperties, ApplicationContext context) { - return new NacosRegistration(nacosDiscoveryProperties, context); + return new NacosRegistration(nacosNamingManager, nacosDiscoveryProperties, + context); } @Bean diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java index 1b18b136..42d19c83 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosDiscoveryProperties.java @@ -16,15 +16,6 @@ package com.alibaba.cloud.nacos; -import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; -import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; -import static com.alibaba.nacos.api.PropertyKeyConst.NAMING_LOAD_CACHE_AT_START; -import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; -import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; - import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; @@ -37,15 +28,6 @@ import java.util.Properties; import javax.annotation.PostConstruct; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -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.Environment; -import org.springframework.util.StringUtils; - import com.alibaba.nacos.api.NacosFactory; import com.alibaba.nacos.api.naming.NamingMaintainFactory; import com.alibaba.nacos.api.naming.NamingMaintainService; @@ -53,10 +35,30 @@ import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.PreservedMetadataKeys; import com.alibaba.nacos.client.naming.utils.UtilAndComs; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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.Environment; +import org.springframework.util.StringUtils; + +import static com.alibaba.nacos.api.PropertyKeyConst.ACCESS_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.CLUSTER_NAME; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT; +import static com.alibaba.nacos.api.PropertyKeyConst.ENDPOINT_PORT; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMESPACE; +import static com.alibaba.nacos.api.PropertyKeyConst.NAMING_LOAD_CACHE_AT_START; +import static com.alibaba.nacos.api.PropertyKeyConst.SECRET_KEY; +import static com.alibaba.nacos.api.PropertyKeyConst.SERVER_ADDR; + /** * @author dungu.zpf * @author xiaojing * @author Mercy + * @author lyuzb */ @ConfigurationProperties("spring.cloud.nacos.discovery") @@ -108,7 +110,7 @@ public class NacosDiscoveryProperties { private String clusterName = "DEFAULT"; /** - * group name for nacos + * group name for nacos. */ private String group = "DEFAULT_GROUP"; @@ -426,9 +428,11 @@ public class NacosDiscoveryProperties { public void overrideFromEnv(Environment env) { if (StringUtils.isEmpty(this.getServerAddr())) { - String serverAddr = env.resolvePlaceholders("${spring.cloud.nacos.discovery.server-addr:}"); + 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:}"); } this.setServerAddr(serverAddr); } @@ -458,10 +462,11 @@ public class NacosDiscoveryProperties { } if (StringUtils.isEmpty(this.getGroup())) { this.setGroup( - env.resolvePlaceholders("${spring.cloud.nacos.discovery.group:}")); + env.resolvePlaceholders("${spring.cloud.nacos.discovery.group:}")); } } + @Deprecated public NamingService namingServiceInstance() { if (null != namingService) { @@ -478,6 +483,7 @@ public class NacosDiscoveryProperties { return namingService; } + @Deprecated public NamingMaintainService namingMaintainServiceInstance() { if (null != namingMaintainService) { 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 new file mode 100644 index 00000000..8acaf0c7 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/NacosNamingManager.java @@ -0,0 +1,51 @@ +/* + * 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/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java index 3a22f074..2e061c6e 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClient.java @@ -16,21 +16,24 @@ package com.alibaba.cloud.nacos.discovery; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.NacosServiceInstance; -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; - 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.NacosNamingManager; +import com.alibaba.cloud.nacos.NacosServiceInstance; +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 @@ -40,9 +43,12 @@ public class NacosDiscoveryClient implements DiscoveryClient { private static final Logger log = LoggerFactory.getLogger(NacosDiscoveryClient.class); public static final String DESCRIPTION = "Spring Cloud Nacos Discovery Client"; + private NacosNamingManager nacosNamingManager; private NacosDiscoveryProperties discoveryProperties; - public NacosDiscoveryClient(NacosDiscoveryProperties discoveryProperties) { + public NacosDiscoveryClient(NacosNamingManager nacosNamingManager, + NacosDiscoveryProperties discoveryProperties) { + this.nacosNamingManager = nacosNamingManager; this.discoveryProperties = discoveryProperties; } @@ -55,7 +61,7 @@ public class NacosDiscoveryClient implements DiscoveryClient { public List getInstances(String serviceId) { try { String group = discoveryProperties.getGroup(); - List instances = discoveryProperties.namingServiceInstance() + List instances = nacosNamingManager.getNamingService() .selectInstances(serviceId, group, true); return hostToServiceInstanceList(instances, serviceId); } @@ -107,7 +113,7 @@ public class NacosDiscoveryClient implements DiscoveryClient { try { String group = discoveryProperties.getGroup(); - ListView services = discoveryProperties.namingServiceInstance() + ListView services = nacosNamingManager.getNamingService() .getServicesOfServer(1, Integer.MAX_VALUE, group); return services.getData(); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java index 8de3bbae..261402a7 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosDiscoveryClientAutoConfiguration.java @@ -16,6 +16,10 @@ package com.alibaba.cloud.nacos.discovery; +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; + import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -25,9 +29,6 @@ import org.springframework.cloud.client.discovery.simple.SimpleDiscoveryClientAu import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; - /** * @author xiaojing */ @@ -44,9 +45,9 @@ public class NacosDiscoveryClientAutoConfiguration { } @Bean - public DiscoveryClient nacosDiscoveryClient( + public DiscoveryClient nacosDiscoveryClient(NacosNamingManager nacosNamingManager, NacosDiscoveryProperties discoveryProperties) { - return new NacosDiscoveryClient(discoveryProperties); + return new NacosDiscoveryClient(nacosNamingManager, discoveryProperties); } @Bean diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java index d0c45a76..fb777c0e 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/NacosWatch.java @@ -23,8 +23,12 @@ 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.cloud.client.discovery.event.HeartbeatEvent; import org.springframework.context.ApplicationEventPublisher; import org.springframework.context.ApplicationEventPublisherAware; @@ -32,9 +36,6 @@ import org.springframework.context.SmartLifecycle; import org.springframework.scheduling.TaskScheduler; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.nacos.api.naming.listener.EventListener; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java index 0cccdcfd..2c916bad 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosConfigServerAutoConfiguration.java @@ -18,6 +18,8 @@ package com.alibaba.cloud.nacos.discovery.configclient; import javax.annotation.PostConstruct; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -25,8 +27,6 @@ import org.springframework.cloud.config.server.config.ConfigServerProperties; import org.springframework.context.annotation.Configuration; import org.springframework.util.StringUtils; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; - /** * Extra configuration for config server if it happens to be registered with Nacos. * diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java index 309439ae..6ee2aaad 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/discovery/configclient/NacosDiscoveryClientConfigServiceBootstrapConfiguration.java @@ -16,15 +16,15 @@ package com.alibaba.cloud.nacos.discovery.configclient; +import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; + import org.springframework.boot.autoconfigure.ImportAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.cloud.config.client.ConfigServicePropertySourceLocator; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - /** * Helper for config client that wants to lookup the config server via discovery. * diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java index 6ea62bbb..2218fd02 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpoint.java @@ -21,15 +21,17 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.ServiceInfo; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +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 * @author xiaojing @@ -40,9 +42,12 @@ public class NacosDiscoveryEndpoint { private static final Logger log = LoggerFactory .getLogger(NacosDiscoveryEndpoint.class); + private NacosNamingManager nacosNamingManager; private NacosDiscoveryProperties nacosDiscoveryProperties; - public NacosDiscoveryEndpoint(NacosDiscoveryProperties nacosDiscoveryProperties) { + public NacosDiscoveryEndpoint(NacosNamingManager nacosNamingManager, + NacosDiscoveryProperties nacosDiscoveryProperties) { + this.nacosNamingManager = nacosNamingManager; this.nacosDiscoveryProperties = nacosDiscoveryProperties; } @@ -54,7 +59,7 @@ public class NacosDiscoveryEndpoint { Map result = new HashMap<>(); result.put("NacosDiscoveryProperties", nacosDiscoveryProperties); - NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); + NamingService namingService = nacosNamingManager.getNamingService(); List subscribe = Collections.emptyList(); try { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java index efb4b0f8..61fa98b9 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/endpoint/NacosDiscoveryEndpointAutoConfiguration.java @@ -16,6 +16,10 @@ package com.alibaba.cloud.nacos.endpoint; +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; + import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -23,9 +27,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; - /** * @author xiaojing */ @@ -38,8 +39,9 @@ public class NacosDiscoveryEndpointAutoConfiguration { @ConditionalOnMissingBean @ConditionalOnEnabledEndpoint public NacosDiscoveryEndpoint nacosDiscoveryEndpoint( + NacosNamingManager nacosNamingManager, NacosDiscoveryProperties nacosDiscoveryProperties) { - return new NacosDiscoveryEndpoint(nacosDiscoveryProperties); + return new NacosDiscoveryEndpoint(nacosNamingManager, nacosDiscoveryProperties); } } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java index 3dbf37c2..61db22b0 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistration.java @@ -18,6 +18,7 @@ package com.alibaba.cloud.nacos.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.Registration; diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java index b317ffe3..5c1a21e6 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosRegistration.java @@ -21,6 +21,11 @@ import java.util.Map; import javax.annotation.PostConstruct; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.PreservedMetadataKeys; + import org.springframework.cloud.client.DefaultServiceInstance; import org.springframework.cloud.client.ServiceInstance; import org.springframework.cloud.client.discovery.ManagementServerPortUtils; @@ -29,10 +34,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.api.naming.PreservedMetadataKeys; - /** * @author xiaojing */ @@ -43,12 +44,15 @@ public class NacosRegistration implements Registration, ServiceInstance { public static final String MANAGEMENT_ADDRESS = "management.address"; public static final String MANAGEMENT_ENDPOINT_BASE_PATH = "management.endpoints.web.base-path"; + private NacosNamingManager nacosNamingManager; private NacosDiscoveryProperties nacosDiscoveryProperties; private ApplicationContext context; - public NacosRegistration(NacosDiscoveryProperties nacosDiscoveryProperties, + public NacosRegistration(NacosNamingManager nacosNamingManager, + NacosDiscoveryProperties nacosDiscoveryProperties, ApplicationContext context) { + this.nacosNamingManager = nacosNamingManager; this.nacosDiscoveryProperties = nacosDiscoveryProperties; this.context = context; } @@ -143,7 +147,7 @@ public class NacosRegistration implements Registration, ServiceInstance { } public NamingService getNacosNamingService() { - return nacosDiscoveryProperties.namingServiceInstance(); + return nacosNamingManager.getNamingService(); } @Override diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java index c7a2ef7d..a587707e 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/registry/NacosServiceRegistry.java @@ -18,16 +18,18 @@ package com.alibaba.cloud.nacos.registry; import java.util.List; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; +import com.alibaba.nacos.api.naming.NamingService; +import com.alibaba.nacos.api.naming.pojo.Instance; + import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.cloud.client.serviceregistry.Registration; import org.springframework.cloud.client.serviceregistry.ServiceRegistry; import org.springframework.util.StringUtils; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.nacos.api.naming.NamingService; -import com.alibaba.nacos.api.naming.pojo.Instance; - /** * @author xiaojing * @author Mercy @@ -36,13 +38,16 @@ public class NacosServiceRegistry implements ServiceRegistry { private static final Logger log = LoggerFactory.getLogger(NacosServiceRegistry.class); + private final NacosNamingManager nacosNamingManager; private final NacosDiscoveryProperties nacosDiscoveryProperties; private final NamingService namingService; - public NacosServiceRegistry(NacosDiscoveryProperties nacosDiscoveryProperties) { + public NacosServiceRegistry(NacosNamingManager nacosNamingManager, + NacosDiscoveryProperties nacosDiscoveryProperties) { + this.nacosNamingManager = nacosNamingManager; this.nacosDiscoveryProperties = nacosDiscoveryProperties; - this.namingService = nacosDiscoveryProperties.namingServiceInstance(); + this.namingService = nacosNamingManager.getNamingService(); } @Override @@ -79,7 +84,7 @@ public class NacosServiceRegistry implements ServiceRegistry { return; } - NamingService namingService = nacosDiscoveryProperties.namingServiceInstance(); + NamingService namingService = nacosNamingManager.getNamingService(); String serviceId = registration.getServiceId(); String group = nacosDiscoveryProperties.getGroup(); @@ -120,8 +125,8 @@ public class NacosServiceRegistry implements ServiceRegistry { } try { - nacosDiscoveryProperties.namingMaintainServiceInstance() - .updateInstance(serviceId, instance); + nacosNamingManager.getNamingMaintainService().updateInstance(serviceId, + instance); } catch (Exception e) { throw new RuntimeException("update nacos instance status fail", e); @@ -134,7 +139,7 @@ public class NacosServiceRegistry implements ServiceRegistry { String serviceName = registration.getServiceId(); try { - List instances = nacosDiscoveryProperties.namingServiceInstance() + List instances = nacosNamingManager.getNamingService() .getAllInstances(serviceName); for (Instance instance : instances) { if (instance.getIp().equalsIgnoreCase(nacosDiscoveryProperties.getIp()) diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java index 06111263..48424f74 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/ExtendBalancer.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.nacos.ribbon; import java.util.List; diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java index 86d56f24..44af17b5 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfiguration.java @@ -16,15 +16,16 @@ package com.alibaba.cloud.nacos.ribbon; -import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; 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; + /** * integrated Ribbon by default * @author xiaojing @@ -36,8 +37,10 @@ public class NacosRibbonClientConfiguration { @Bean @ConditionalOnMissingBean public ServerList ribbonServerList(IClientConfig config, + NacosNamingManager nacosNamingManager, NacosDiscoveryProperties nacosDiscoveryProperties) { - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + NacosServerList serverList = new NacosServerList(nacosNamingManager, + nacosDiscoveryProperties); serverList.initWithNiwsConfig(config); return serverList; } diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java index 95bd7e6a..f2b556fa 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosRule.java @@ -1,16 +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.nacos.ribbon; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; -import org.apache.commons.lang3.StringUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.util.CollectionUtils; - import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; import com.alibaba.nacos.api.naming.NamingService; import com.alibaba.nacos.api.naming.pojo.Instance; @@ -18,6 +29,12 @@ import com.netflix.client.config.IClientConfig; import com.netflix.loadbalancer.AbstractLoadBalancerRule; import com.netflix.loadbalancer.DynamicServerListLoadBalancer; import com.netflix.loadbalancer.Server; +import org.apache.commons.lang3.StringUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.util.CollectionUtils; /** * Supports preferentially calling the ribbon load balancing rules of the same cluster @@ -31,6 +48,9 @@ public class NacosRule extends AbstractLoadBalancerRule { @Autowired private NacosDiscoveryProperties nacosDiscoveryProperties; + @Autowired + private NacosNamingManager nacosNamingManager; + @Override public Server choose(Object key) { try { @@ -38,8 +58,7 @@ public class NacosRule extends AbstractLoadBalancerRule { DynamicServerListLoadBalancer loadBalancer = (DynamicServerListLoadBalancer) getLoadBalancer(); String name = loadBalancer.getName(); - NamingService namingService = this.nacosDiscoveryProperties - .namingServiceInstance(); + NamingService namingService = this.nacosNamingManager.getNamingService(); List instances = namingService.selectInstances(name, true); if (CollectionUtils.isEmpty(instances)) { LOGGER.warn("no instance in service {}", name); diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java index 481c2d4a..35fc86c4 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerIntrospector.java @@ -18,10 +18,10 @@ package com.alibaba.cloud.nacos.ribbon; import java.util.Map; -import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; - import com.netflix.loadbalancer.Server; +import org.springframework.cloud.netflix.ribbon.DefaultServerIntrospector; + /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java index d85ec353..509da7c0 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/NacosServerList.java @@ -20,9 +20,10 @@ import java.util.ArrayList; import java.util.List; import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; 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; @@ -32,11 +33,14 @@ import com.netflix.loadbalancer.AbstractServerList; */ public class NacosServerList extends AbstractServerList { + private NacosNamingManager nacosNamingManager; private NacosDiscoveryProperties discoveryProperties; private String serviceId; - public NacosServerList(NacosDiscoveryProperties discoveryProperties) { + public NacosServerList(NacosNamingManager nacosNamingManager, + NacosDiscoveryProperties discoveryProperties) { + this.nacosNamingManager = nacosNamingManager; this.discoveryProperties = discoveryProperties; } @@ -53,8 +57,8 @@ public class NacosServerList extends AbstractServerList { private List getServers() { try { String group = discoveryProperties.getGroup(); - List instances = discoveryProperties.namingServiceInstance() - .selectInstances(serviceId, group,true); + List instances = nacosNamingManager.getNamingService() + .selectInstances(serviceId, group, true); return instancesToServerList(instances); } catch (Exception e) { diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java index 64a30167..7a6a1225 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java +++ b/spring-cloud-alibaba-nacos-discovery/src/main/java/com/alibaba/cloud/nacos/ribbon/RibbonNacosAutoConfiguration.java @@ -16,6 +16,8 @@ package com.alibaba.cloud.nacos.ribbon; +import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; + import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.context.properties.EnableConfigurationProperties; @@ -24,8 +26,6 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.nacos.ConditionalOnNacosDiscoveryEnabled; - /** * {@link org.springframework.boot.autoconfigure.EnableAutoConfiguration * Auto-configuration} that sets up Ribbon for Nacos. diff --git a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 3c8226ad..2f0718f9 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/spring-cloud-alibaba-nacos-discovery/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,5 +1,15 @@ -{ - "properties": [ +{"properties": [ + { + "name": "spring.cloud.nacos.server-addr", + "type": "java.lang.String", + "description": "nacos server address." + }, + { + "name": "spring.cloud.nacos.discovery.server-addr", + "type": "java.lang.String", + "defaultValue": "${spring.cloud.nacos.server-addr}", + "description": "nacos discovery server address." + }, { "name": "spring.cloud.nacos.discovery.service", "type": "java.lang.String", @@ -24,5 +34,4 @@ "defaultValue": "true", "description": "enable nacos discovery watch or not ." } - ] -} +]} diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java index 4e13cd20..ab385b75 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryClientTests.java @@ -16,18 +16,20 @@ package com.alibaba.cloud.nacos; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClient; -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.springframework.cloud.client.ServiceInstance; - 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.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.springframework.cloud.client.ServiceInstance; + import static com.alibaba.cloud.nacos.test.NacosMockTest.serviceInstance; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.eq; @@ -56,16 +58,17 @@ public class NacosDiscoveryClientTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); - when(namingService.selectInstances(eq(serviceName),eq("DEFAULT"), eq(true))) + when(namingService.selectInstances(eq(serviceName), eq("DEFAULT"), eq(true))) .thenReturn(instances); NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( - nacosDiscoveryProperties); + nacosNamingManager, nacosDiscoveryProperties); List serviceInstances = discoveryClient .getInstances(serviceName); @@ -97,16 +100,17 @@ public class NacosDiscoveryClientTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); NacosDiscoveryClient discoveryClient = new NacosDiscoveryClient( - nacosDiscoveryProperties); + nacosNamingManager, nacosDiscoveryProperties); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); - when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE),eq("DEFAULT"))) - .thenReturn(nacosServices); + when(namingService.getServicesOfServer(eq(1), eq(Integer.MAX_VALUE), + eq("DEFAULT"))).thenReturn(nacosServices); List services = discoveryClient.getServices(); 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 new file mode 100644 index 00000000..daa50ea7 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressBothLevelTests.java @@ -0,0 +1,44 @@ +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 new file mode 100644 index 00000000..b77c28d7 --- /dev/null +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/NacosDiscoveryPropertiesServerAddressTopLevelTests.java @@ -0,0 +1,46 @@ +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/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java index 0486b851..f2611a66 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpNetworkInterfaceTests.java @@ -16,17 +16,18 @@ package com.alibaba.cloud.nacos.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; +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; @@ -36,9 +37,9 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +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 diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java index 2f0944eb..05ebf753 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationIpTests.java @@ -16,12 +16,13 @@ package com.alibaba.cloud.nacos.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -30,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +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 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 index e0af0e1e..d99a64ed 100644 --- 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 @@ -16,14 +16,13 @@ package com.alibaba.cloud.nacos.registry; -import static com.alibaba.cloud.nacos.registry.NacosRegistration.MANAGEMENT_CONTEXT_PATH; -import static com.alibaba.cloud.nacos.registry.NacosRegistration.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; +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; @@ -32,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +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 @@ -71,11 +70,11 @@ public class NacosAutoServiceRegistrationManagementPortTests { private void checkoutNacosDiscoveryManagementData() { assertEquals("NacosDiscoveryProperties management port was wrong", "8888", - properties.getMetadata().get(MANAGEMENT_PORT)); + properties.getMetadata().get(NacosRegistration.MANAGEMENT_PORT)); assertEquals("NacosDiscoveryProperties management context path was wrong", "/test-context-path", - properties.getMetadata().get(MANAGEMENT_CONTEXT_PATH)); + properties.getMetadata().get(NacosRegistration.MANAGEMENT_CONTEXT_PATH)); } diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java index 25483a82..0492ea71 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationPortTests.java @@ -16,12 +16,13 @@ package com.alibaba.cloud.nacos.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -30,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +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 diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java index 214b569a..a1ba750a 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/registry/NacosAutoServiceRegistrationTests.java @@ -16,15 +16,17 @@ package com.alibaba.cloud.nacos.registry; -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; - import java.util.Map; +import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint; + 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; @@ -35,10 +37,10 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; -import com.alibaba.cloud.nacos.NacosDiscoveryProperties; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; -import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint; +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 @@ -56,7 +58,10 @@ import com.alibaba.cloud.nacos.endpoint.NacosDiscoveryEndpoint; "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" }, webEnvironment = RANDOM_PORT) + "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 @@ -71,6 +76,9 @@ public class NacosAutoServiceRegistrationTests { @Autowired private NacosDiscoveryProperties properties; + @Autowired + private NacosNamingManager nacosNamingManager; + @Autowired private InetUtils inetUtils; @@ -92,6 +100,9 @@ public class NacosAutoServiceRegistrationTests { checkoutNacosDiscoverySecure(); checkoutNacosDiscoveryAccessKey(); checkoutNacosDiscoverySecrectKey(); + checkoutNacosDiscoveryHeartBeatInterval(); + checkoutNacosDiscoveryHeartBeatTimeout(); + checkoutNacosDiscoveryIpDeleteTimeout(); checkoutNacosDiscoveryServiceName(); checkoutNacosDiscoveryServiceIP(); @@ -162,6 +173,21 @@ public class NacosAutoServiceRegistrationTests { properties.getSecretKey()); } + private void checkoutNacosDiscoveryHeartBeatInterval() { + assertEquals("NacosDiscoveryProperties heart beat interval was wrong", + Integer.valueOf(3), properties.getHeartBeatInterval()); + } + + private void checkoutNacosDiscoveryHeartBeatTimeout() { + assertEquals("NacosDiscoveryProperties heart beat timeout was wrong", + Integer.valueOf(6), properties.getHeartBeatTimeout()); + } + + private void checkoutNacosDiscoveryIpDeleteTimeout() { + assertEquals("NacosDiscoveryProperties ip delete timeout was wrong", + Integer.valueOf(9), properties.getIpDeleteTimeout()); + } + private void checkoutNacosDiscoveryServiceName() { assertEquals("NacosDiscoveryProperties service name was wrong", "myTestService1", properties.getService()); @@ -183,11 +209,11 @@ public class NacosAutoServiceRegistrationTests { private void checkoutEndpoint() throws Exception { NacosDiscoveryEndpoint nacosDiscoveryEndpoint = new NacosDiscoveryEndpoint( - properties); + nacosNamingManager, properties); Map map = nacosDiscoveryEndpoint.nacosDiscovery(); assertEquals(map.get("NacosDiscoveryProperties"), properties); assertEquals(map.get("subscribe").toString(), - properties.namingServiceInstance().getSubscribeServices().toString()); + nacosNamingManager.getNamingService().getSubscribeServices().toString()); } @Configuration diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java index 2dd70b04..87cfe8c6 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosRibbonClientConfigurationTests.java @@ -1,8 +1,11 @@ package com.alibaba.cloud.nacos.ribbon; -import static org.assertj.core.api.Assertions.assertThat; +import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; +import com.netflix.client.config.DefaultClientConfigImpl; +import com.netflix.client.config.IClientConfig; import org.junit.Test; + import org.springframework.boot.autoconfigure.AutoConfigurations; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.test.context.runner.WebApplicationContextRunner; @@ -12,10 +15,7 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.nacos.discovery.NacosDiscoveryClientAutoConfiguration; - -import com.netflix.client.config.DefaultClientConfigImpl; -import com.netflix.client.config.IClientConfig; +import static org.assertj.core.api.Assertions.assertThat; /** * @author xiaojing diff --git a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java index 84ec00aa..ac70596d 100644 --- a/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java +++ b/spring-cloud-alibaba-nacos-discovery/src/test/java/com/alibaba/cloud/nacos/ribbon/NacosServerListTests.java @@ -16,26 +16,26 @@ package com.alibaba.cloud.nacos.ribbon; -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; - import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; -import org.junit.Test; - import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.nacos.NacosNamingManager; 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; + +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 @@ -48,14 +48,16 @@ public class NacosServerListTests { public void testEmptyInstancesReturnsEmptyList() throws Exception { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(namingService.selectInstances(anyString(), eq("DEFAULT"), eq(true))) .thenReturn(null); - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + NacosServerList serverList = new NacosServerList(nacosNamingManager, + nacosDiscoveryProperties); List servers = serverList.getInitialListOfServers(); assertThat(servers).isEmpty(); } @@ -70,10 +72,11 @@ public class NacosServerListTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) @@ -81,7 +84,8 @@ public class NacosServerListTests { IClientConfig clientConfig = mock(IClientConfig.class); when(clientConfig.getClientName()).thenReturn("test-service"); - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + NacosServerList serverList = new NacosServerList(nacosNamingManager, + nacosDiscoveryProperties); serverList.initWithNiwsConfig(clientConfig); List servers = serverList.getInitialListOfServers(); assertThat(servers).hasSize(1); @@ -104,10 +108,11 @@ public class NacosServerListTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) .thenReturn(instances.stream().filter(Instance::isHealthy) @@ -115,7 +120,8 @@ public class NacosServerListTests { IClientConfig clientConfig = mock(IClientConfig.class); when(clientConfig.getClientName()).thenReturn("test-service"); - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + NacosServerList serverList = new NacosServerList(nacosNamingManager, + nacosDiscoveryProperties); serverList.initWithNiwsConfig(clientConfig); List servers = serverList.getInitialListOfServers(); assertThat(servers).hasSize(1); @@ -142,10 +148,11 @@ public class NacosServerListTests { NacosDiscoveryProperties nacosDiscoveryProperties = mock( NacosDiscoveryProperties.class); + NacosNamingManager nacosNamingManager = mock(NacosNamingManager.class); NamingService namingService = mock(NamingService.class); - when(nacosDiscoveryProperties.namingServiceInstance()).thenReturn(namingService); + when(nacosNamingManager.getNamingService()).thenReturn(namingService); when(nacosDiscoveryProperties.getGroup()).thenReturn("DEFAULT"); when(namingService.selectInstances(eq("test-service"), eq("DEFAULT"), eq(true))) .thenReturn(instances.stream().filter(Instance::isHealthy) @@ -153,7 +160,8 @@ public class NacosServerListTests { IClientConfig clientConfig = mock(IClientConfig.class); when(clientConfig.getClientName()).thenReturn("test-service"); - NacosServerList serverList = new NacosServerList(nacosDiscoveryProperties); + NacosServerList serverList = new NacosServerList(nacosNamingManager, + nacosDiscoveryProperties); serverList.initWithNiwsConfig(clientConfig); List servers = serverList.getUpdatedListOfServers(); 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 index a26aa578..e115f3e0 100644 --- 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 @@ -16,14 +16,14 @@ 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; -import io.seata.spring.annotation.GlobalTransactionScanner; - /** * @author xiaojing */ @@ -51,7 +51,7 @@ public class GlobalTransactionAutoConfiguration { String txServiceGroup = seataProperties.getTxServiceGroup(); if (StringUtils.isEmpty(txServiceGroup)) { - txServiceGroup = applicationName + "-fescar-service-group"; + txServiceGroup = applicationName + "-seata-service-group"; seataProperties.setTxServiceGroup(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 index 492d054d..c9531434 100644 --- 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 @@ -24,10 +24,10 @@ import org.springframework.boot.context.properties.ConfigurationProperties; @ConfigurationProperties("spring.cloud.alibaba.seata") public class SeataProperties { - // todo support config Fescar server information + // todo support config Seata server information /** - * Seata tx service group.default is ${spring.application.name}-fescar-service-group. + * Seata tx service group.default is ${spring.application.name}-seata-service-group. */ private String txServiceGroup; diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java index 0855e358..9a6fd1c3 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignBuilder.java @@ -16,10 +16,10 @@ package com.alibaba.cloud.seata.feign; -import org.springframework.beans.factory.BeanFactory; - import feign.Feign; +import org.springframework.beans.factory.BeanFactory; + /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java index 9e486120..5b125beb 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClient.java @@ -23,14 +23,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.springframework.beans.factory.BeanFactory; -import org.springframework.util.StringUtils; - import feign.Client; import feign.Request; import feign.Response; import io.seata.core.context.RootContext; +import org.springframework.beans.factory.BeanFactory; +import org.springframework.util.StringUtils; + /** * @author xiaojing */ @@ -68,9 +68,9 @@ public class SeataFeignClient implements Client { Map> headers = new HashMap<>(MAP_SIZE); headers.putAll(request.headers()); - List fescarXid = new ArrayList<>(); - fescarXid.add(xid); - headers.put(RootContext.KEY_XID, fescarXid); + 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-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java index 3602e23d..11f0d76c 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignClientAutoConfiguration.java @@ -16,6 +16,9 @@ package com.alibaba.cloud.seata.feign; +import feign.Client; +import feign.Feign; + import org.springframework.beans.factory.BeanFactory; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -26,9 +29,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import feign.Client; -import feign.Feign; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java index 86b017f6..1922d719 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignContext.java @@ -19,10 +19,10 @@ package com.alibaba.cloud.seata.feign; import java.util.HashMap; import java.util.Map; -import org.springframework.cloud.openfeign.FeignContext; - import feign.Client; +import org.springframework.cloud.openfeign.FeignContext; + /** * * @author xiaojing diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java index 374b8367..21175518 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataFeignObjectWrapper.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.seata.feign; +import feign.Client; + 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 feign.Client; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java index f226244a..3ffd78db 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataHystrixFeignBuilder.java @@ -16,12 +16,12 @@ package com.alibaba.cloud.seata.feign; -import org.springframework.beans.factory.BeanFactory; - import feign.Feign; import feign.Retryer; import feign.hystrix.HystrixFeign; +import org.springframework.beans.factory.BeanFactory; + /** * @author xiaojing */ 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 index d68b2b5d..672759c9 100644 --- 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 @@ -23,17 +23,17 @@ 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; -import feign.Client; -import feign.Request; -import feign.Response; -import io.seata.core.context.RootContext; - /** * @author xiaojing */ @@ -71,9 +71,9 @@ public class SeataLoadBalancerFeignClient extends LoadBalancerFeignClient { Map> headers = new HashMap<>(MAP_SIZE); headers.putAll(request.headers()); - List fescarXid = new ArrayList<>(); - fescarXid.add(xid); - headers.put(RootContext.KEY_XID, fescarXid); + 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-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java index 0f185c2a..9c3615e6 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/SeataSentinelFeignBuilder.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.seata.feign; -import org.springframework.beans.factory.BeanFactory; - import com.alibaba.cloud.sentinel.feign.SentinelFeign; import feign.Feign; import feign.Retryer; +import org.springframework.beans.factory.BeanFactory; + /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java index 465ca3e6..a6739269 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixAutoConfiguration.java @@ -15,12 +15,12 @@ */ package com.alibaba.cloud.seata.feign.hystrix; +import com.netflix.hystrix.HystrixCommand; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.netflix.hystrix.HystrixCommand; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java index 0bff8173..fdd8497d 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/feign/hystrix/SeataHystrixConcurrencyStrategy.java @@ -19,7 +19,6 @@ import java.util.concurrent.Callable; import com.netflix.hystrix.strategy.HystrixPlugins; import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategy; - import io.seata.core.context.RootContext; /** @@ -58,6 +57,7 @@ public class SeataHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy private static class SeataContextCallable implements Callable { private final Callable actual; + private final String xid; SeataContextCallable(Callable actual) { diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java index d90f1255..97680aa0 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/rest/SeataRestTemplateInterceptor.java @@ -18,6 +18,8 @@ package com.alibaba.cloud.seata.rest; import java.io.IOException; +import io.seata.core.context.RootContext; + import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.http.client.ClientHttpRequestInterceptor; @@ -25,8 +27,6 @@ import org.springframework.http.client.ClientHttpResponse; import org.springframework.http.client.support.HttpRequestWrapper; import org.springframework.util.StringUtils; -import io.seata.core.context.RootContext; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java index 9f50352a..cc37590b 100644 --- a/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java +++ b/spring-cloud-alibaba-seata/src/main/java/com/alibaba/cloud/seata/web/SeataHandlerInterceptor.java @@ -19,13 +19,13 @@ package com.alibaba.cloud.seata.web; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; +import io.seata.core.context.RootContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.util.StringUtils; import org.springframework.web.servlet.HandlerInterceptor; -import io.seata.core.context.RootContext; - /** * @author xiaojing * diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java index 4a376fd2..59f74fe9 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/RuleType.java @@ -19,8 +19,6 @@ package com.alibaba.cloud.sentinel.datasource; import java.util.Arrays; import java.util.Optional; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties; import com.alibaba.csp.sentinel.slots.block.AbstractRule; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; @@ -29,6 +27,8 @@ 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.springframework.util.StringUtils; + /** * Enum for {@link AbstractRule} class, using in * {@link AbstractDataSourceProperties#ruleType} @@ -38,48 +38,48 @@ import com.alibaba.csp.sentinel.slots.system.SystemRule; public enum RuleType { /** - * flow + * flow. */ FLOW("flow", FlowRule.class), /** - * degrade + * degrade. */ DEGRADE("degrade", DegradeRule.class), /** - * param flow + * param flow. */ PARAM_FLOW("param-flow", ParamFlowRule.class), /** - * system + * system. */ SYSTEM("system", SystemRule.class), /** - * authority + * authority. */ AUTHORITY("authority", AuthorityRule.class), /** - * gateway flow + * gateway flow. */ GW_FLOW("gw-flow", "com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule"), /** - * api + * api. */ GW_API_GROUP("gw-api-group", "com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition"); /** - * alias for {@link AbstractRule} + * alias for {@link AbstractRule}. */ private final String name; /** - * concrete {@link AbstractRule} class + * concrete {@link AbstractRule} class. */ private Class clazz; /** - * concrete {@link AbstractRule} class name + * concrete {@link AbstractRule} class name. */ private String clazzName; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java index df89dbd9..fb8d1d38 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/AbstractDataSourceProperties.java @@ -19,8 +19,6 @@ package com.alibaba.cloud.sentinel.datasource.config; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; -import org.springframework.core.env.Environment; - import com.alibaba.cloud.sentinel.datasource.RuleType; import com.alibaba.csp.sentinel.adapter.gateway.common.api.GatewayApiDefinitionManager; import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager; @@ -33,6 +31,8 @@ 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} * @@ -42,11 +42,15 @@ public class AbstractDataSourceProperties { @NotEmpty private String dataType = "json"; + @NotNull private RuleType ruleType; + private String converterClass; + @JsonIgnore private final String factoryBeanName; + @JsonIgnore private Environment env; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java index d67baf04..6c392258 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ApolloDataSourceProperties.java @@ -30,8 +30,10 @@ public class ApolloDataSourceProperties extends AbstractDataSourceProperties { @NotEmpty private String namespaceName; + @NotEmpty private String flowRulesKey; + private String defaultFlowRuleValue; public ApolloDataSourceProperties() { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java index 0492e57d..6212af13 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/DataSourcePropertiesConfiguration.java @@ -21,10 +21,10 @@ import java.util.List; import java.util.Objects; import java.util.stream.Collectors; -import org.springframework.util.ObjectUtils; - import com.fasterxml.jackson.annotation.JsonIgnore; +import org.springframework.util.ObjectUtils; + /** * Using By ConfigurationProperties. * diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java index c8551c24..347da650 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/FileDataSourceProperties.java @@ -20,11 +20,11 @@ import java.io.IOException; import javax.validation.constraints.NotEmpty; +import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean; + import org.springframework.util.ResourceUtils; import org.springframework.util.StringUtils; -import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean; - /** * File Properties class Using by {@link DataSourcePropertiesConfiguration} and * {@link FileRefreshableDataSourceFactoryBean} @@ -35,8 +35,11 @@ public class FileDataSourceProperties extends AbstractDataSourceProperties { @NotEmpty private String file; + private String charset = "utf-8"; + private long recommendRefreshMs = 3000L; + private int bufSize = 1024 * 1024; public FileDataSourceProperties() { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java index f8673d0b..a0a23c7a 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/NacosDataSourceProperties.java @@ -18,10 +18,10 @@ package com.alibaba.cloud.sentinel.datasource.config; import javax.validation.constraints.NotEmpty; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; +import org.springframework.util.StringUtils; + /** * Nacos Properties class Using by {@link DataSourcePropertiesConfiguration} and * {@link NacosDataSourceFactoryBean} @@ -39,8 +39,11 @@ public class NacosDataSourceProperties extends AbstractDataSourceProperties { private String dataId; private String endpoint; + private String namespace; + private String accessKey; + private String secretKey; public NacosDataSourceProperties() { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java index 56aef9cf..08f3bc20 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/RedisDataSourceProperties.java @@ -19,10 +19,10 @@ package com.alibaba.cloud.sentinel.datasource.config; import java.time.Duration; import java.util.List; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.datasource.factorybean.RedisDataSourceFactoryBean; +import org.springframework.util.StringUtils; + /** * Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and * {@link RedisDataSourceFactoryBean} @@ -36,27 +36,27 @@ public class RedisDataSourceProperties extends AbstractDataSourceProperties { } /** - * redis server host + * redis server host. */ private String host = "localhost"; /** - * redis server port + * redis server port. */ private int port = 6379; /** - * redis server password + * redis server password. */ private String password; /** - * redis server default select database + * redis server default select database. */ private int database; /** - * redis server timeout + * redis server timeout. */ private Duration timeout; @@ -66,17 +66,17 @@ public class RedisDataSourceProperties extends AbstractDataSourceProperties { private List nodes; /** - * data key in Redis + * data key in Redis. */ private String ruleKey; /** - * channel to subscribe in Redis + * channel to subscribe in Redis. */ private String channel; /** - * redis sentinel model + * redis sentinel model. */ private String masterId; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java index d36c51cb..ae24a0e6 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/config/ZookeeperDataSourceProperties.java @@ -16,12 +16,10 @@ package com.alibaba.cloud.sentinel.datasource.config; -import javax.validation.constraints.NotEmpty; +import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean; import org.springframework.util.StringUtils; -import com.alibaba.cloud.sentinel.datasource.factorybean.ZookeeperDataSourceFactoryBean; - /** * Zookeeper Properties class Using by {@link DataSourcePropertiesConfiguration} and * {@link ZookeeperDataSourceFactoryBean} @@ -34,8 +32,7 @@ public class ZookeeperDataSourceProperties extends AbstractDataSourceProperties super(ZookeeperDataSourceFactoryBean.class.getName()); } - @NotEmpty - private String serverAddr; + private String serverAddr = "localhost:2181"; private String path; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java index f388cbb8..d082f792 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/converter/SentinelConverter.java @@ -24,10 +24,6 @@ import java.util.HashSet; import java.util.List; import java.util.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.util.StringUtils; - import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.slots.block.authority.AuthorityRule; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule; @@ -37,6 +33,10 @@ 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; +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 @@ -85,6 +85,7 @@ public abstract class SentinelConverter List sourceArray = objectMapper.readValue(source, new TypeReference>() { }); + for (Object obj : sourceArray) { String item = null; try { diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java index 47843e5c..758c61b3 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ApolloDataSourceFactoryBean.java @@ -16,11 +16,11 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; -import org.springframework.beans.factory.FactoryBean; - import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource; +import org.springframework.beans.factory.FactoryBean; + /** * A {@link FactoryBean} for creating {@link ApolloDataSource} instance. * @@ -30,8 +30,11 @@ import com.alibaba.csp.sentinel.datasource.apollo.ApolloDataSource; public class ApolloDataSourceFactoryBean implements FactoryBean { private String namespaceName; + private String flowRulesKey; + private String defaultFlowRuleValue; + private Converter converter; @Override diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/FileRefreshableDataSourceFactoryBean.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/FileRefreshableDataSourceFactoryBean.java index 0042134b..f22ea5d6 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/FileRefreshableDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/FileRefreshableDataSourceFactoryBean.java @@ -19,11 +19,11 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; import java.io.File; import java.nio.charset.Charset; -import org.springframework.beans.factory.FactoryBean; - import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource; +import org.springframework.beans.factory.FactoryBean; + /** * A {@link FactoryBean} for creating {@link FileRefreshableDataSource} instance. * @@ -34,9 +34,13 @@ public class FileRefreshableDataSourceFactoryBean implements FactoryBean { private String file; + private String charset; + private long recommendRefreshMs; + private int bufSize; + private Converter converter; @Override diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/NacosDataSourceFactoryBean.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/NacosDataSourceFactoryBean.java index da640f8e..ab2e9fd0 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/NacosDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/NacosDataSourceFactoryBean.java @@ -18,13 +18,13 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; import java.util.Properties; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.util.StringUtils; - import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource; import com.alibaba.nacos.api.PropertyKeyConst; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.StringUtils; + /** * A {@link FactoryBean} for creating {@link NacosDataSource} instance. * @@ -34,13 +34,19 @@ import com.alibaba.nacos.api.PropertyKeyConst; public class NacosDataSourceFactoryBean implements FactoryBean { private String serverAddr; + private String groupId; + private String dataId; + private Converter converter; private String endpoint; + private String namespace; + private String accessKey; + private String secretKey; @Override diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java index bbeb98ee..4e36e17d 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/RedisDataSourceFactoryBean.java @@ -19,15 +19,15 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; import java.time.Duration; import java.util.List; -import org.springframework.beans.factory.FactoryBean; -import org.springframework.util.Assert; -import org.springframework.util.StringUtils; - import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.redis.RedisDataSource; import com.alibaba.csp.sentinel.datasource.redis.config.RedisConnectionConfig; import com.alibaba.csp.sentinel.slots.block.flow.FlowRule; +import org.springframework.beans.factory.FactoryBean; +import org.springframework.util.Assert; +import org.springframework.util.StringUtils; + /** * A {@link FactoryBean} for creating {@link RedisDataSource} instance. * @@ -52,17 +52,17 @@ public class RedisDataSourceFactoryBean implements FactoryBean private Converter converter; /** - * data key in Redis + * data key in Redis. */ private String ruleKey; /** - * channel to subscribe in Redis + * channel to subscribe in Redis. */ private String channel; /** - * redis server password + * redis server password. */ private String password; diff --git a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java index 5731d8f1..19a6ab1f 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/main/java/com/alibaba/cloud/sentinel/datasource/factorybean/ZookeeperDataSourceFactoryBean.java @@ -16,12 +16,13 @@ package com.alibaba.cloud.sentinel.datasource.factorybean; -import org.apache.commons.lang3.StringUtils; -import org.springframework.beans.factory.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; + /** * A {@link FactoryBean} for creating {@link ZookeeperDataSource} instance. * @@ -35,6 +36,7 @@ public class ZookeeperDataSourceFactoryBean implements FactoryBeanJim */ diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesTests.java index 6b13fe35..a61687c2 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/DataSourcePropertiesTests.java @@ -16,16 +16,9 @@ package com.alibaba.cloud.sentinel.datasource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; - import java.io.IOException; import java.util.List; -import org.junit.Test; -import org.springframework.util.ResourceUtils; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.datasource.config.ApolloDataSourceProperties; import com.alibaba.cloud.sentinel.datasource.config.FileDataSourceProperties; import com.alibaba.cloud.sentinel.datasource.config.ZookeeperDataSourceProperties; @@ -39,6 +32,13 @@ import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; +import org.junit.Test; + +import org.springframework.util.ResourceUtils; +import org.springframework.util.StringUtils; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java index 5e49678e..6bb79f75 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/FileRefreshableDataSourceFactoryBeanTests.java @@ -16,19 +16,10 @@ package com.alibaba.cloud.sentinel.datasource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import java.io.FileNotFoundException; import java.io.IOException; import java.util.List; -import org.junit.Test; -import org.springframework.context.annotation.AnnotationConfigApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.util.ResourceUtils; - import com.alibaba.cloud.sentinel.datasource.factorybean.FileRefreshableDataSourceFactoryBean; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource; @@ -36,6 +27,15 @@ 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; + +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +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; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java index 3fbf1060..abbc2ad1 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourceFactoryBeanTests.java @@ -16,19 +16,19 @@ package com.alibaba.cloud.sentinel.datasource; +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.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import org.junit.Test; - -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; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java index 11c39103..0388c34a 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/NacosDataSourcePropertiesTests.java @@ -16,12 +16,12 @@ package com.alibaba.cloud.sentinel.datasource; -import static org.junit.Assert.assertEquals; +import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties; +import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; import org.junit.Test; -import com.alibaba.cloud.sentinel.datasource.config.NacosDataSourceProperties; -import com.alibaba.cloud.sentinel.datasource.factorybean.NacosDataSourceFactoryBean; +import static org.junit.Assert.assertEquals; /** * @author Jim 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 index 4eea620a..f973fe5b 100644 --- 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 @@ -16,12 +16,6 @@ package com.alibaba.cloud.sentinel.datasource; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -import org.junit.Test; - 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; @@ -29,6 +23,12 @@ 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 */ diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java index e909b751..e02aded9 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/SentinelConverterTests.java @@ -16,16 +16,9 @@ package com.alibaba.cloud.sentinel.datasource; -import static org.junit.Assert.assertEquals; - import java.io.IOException; import java.util.List; -import org.apache.commons.io.FileUtils; -import org.junit.Test; -import org.springframework.util.ResourceUtils; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; import com.alibaba.csp.sentinel.slots.block.RuleConstant; @@ -33,6 +26,13 @@ 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; +import org.junit.Test; + +import org.springframework.util.ResourceUtils; +import org.springframework.util.StringUtils; + +import static org.junit.Assert.assertEquals; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java index 813b4053..3070cdbb 100644 --- a/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java +++ b/spring-cloud-alibaba-sentinel-datasource/src/test/java/com/alibaba/cloud/sentinel/datasource/ZookeeperDataSourceFactoryBeanTests.java @@ -16,19 +16,19 @@ package com.alibaba.cloud.sentinel.datasource; +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.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import org.junit.Test; - -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; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java new file mode 100644 index 00000000..bc1bf648 --- /dev/null +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/GatewayEnvironmentPostProcessor.java @@ -0,0 +1,79 @@ +/* + * 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 + * + * 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 java.util.HashMap; +import java.util.Map; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.env.EnvironmentPostProcessor; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.core.env.MapPropertySource; +import org.springframework.core.env.MutablePropertySources; +import org.springframework.core.env.PropertySource; + +/** + * @author zhuhonghan + */ +public class GatewayEnvironmentPostProcessor implements EnvironmentPostProcessor { + + private final static String SENTINEL_FILTER_ENABLED = "spring.cloud.sentinel.filter.enabled"; + + private final static String PROPERTY_SOURCE_NAME = "defaultProperties"; + + @Override + public void postProcessEnvironment(ConfigurableEnvironment environment, + SpringApplication springApplication) { + addDefaultPropertySource(environment); + } + + private void addDefaultPropertySource(ConfigurableEnvironment environment) { + + Map map = new HashMap(); + + configureDefaultProperties(map); + + addOrReplace(environment.getPropertySources(), map); + } + + private void configureDefaultProperties(Map source) { + // Required Properties + source.put(SENTINEL_FILTER_ENABLED, "false"); + } + + private void addOrReplace(MutablePropertySources propertySources, + Map map) { + MapPropertySource target = null; + if (propertySources.contains(PROPERTY_SOURCE_NAME)) { + PropertySource source = propertySources.get(PROPERTY_SOURCE_NAME); + if (source instanceof MapPropertySource) { + target = (MapPropertySource) source; + for (String key : map.keySet()) { + if (!target.containsProperty(key)) { + target.getSource().put(key, map.get(key)); + } + } + } + } + if (target == null) { + target = new MapPropertySource(PROPERTY_SOURCE_NAME, map); + } + if (!propertySources.contains(PROPERTY_SOURCE_NAME)) { + propertySources.addLast(target); + } + } + +} diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java index 3efd42ab..2f068b65 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/SentinelGatewayAutoConfiguration.java @@ -22,11 +22,6 @@ import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; -import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; - import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; import com.alibaba.csp.sentinel.adapter.gateway.common.api.ApiDefinition; @@ -46,6 +41,11 @@ import com.fasterxml.jackson.databind.module.SimpleModule; import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java index 21be002a..f3ce2f11 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelGatewayProperties.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.sentinel.gateway.scg; +import com.alibaba.cloud.sentinel.gateway.ConfigConstants; +import com.alibaba.cloud.sentinel.gateway.FallbackProperties; + import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.boot.context.properties.NestedConfigurationProperty; import org.springframework.core.Ordered; -import com.alibaba.cloud.sentinel.gateway.ConfigConstants; -import com.alibaba.cloud.sentinel.gateway.FallbackProperties; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java index b7693f38..1358c415 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/scg/SentinelSCGAutoConfiguration.java @@ -16,16 +16,26 @@ package com.alibaba.cloud.sentinel.gateway.scg; -import static org.springframework.web.reactive.function.BodyInserters.fromObject; - import java.util.Collections; import java.util.List; import java.util.Optional; import javax.annotation.PostConstruct; +import com.alibaba.cloud.sentinel.gateway.ConfigConstants; +import com.alibaba.cloud.sentinel.gateway.FallbackProperties; +import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager; +import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.RedirectBlockRequestHandler; +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; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -43,17 +53,7 @@ import org.springframework.web.reactive.function.server.ServerResponse; import org.springframework.web.reactive.result.view.ViewResolver; import org.springframework.web.server.ServerWebExchange; -import com.alibaba.cloud.sentinel.gateway.ConfigConstants; -import com.alibaba.cloud.sentinel.gateway.FallbackProperties; -import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter; -import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.BlockRequestHandler; -import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager; -import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.RedirectBlockRequestHandler; -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 reactor.core.publisher.Mono; +import static org.springframework.web.reactive.function.BodyInserters.fromObject; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java index 9f9074e6..06c2cf83 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/FallBackProviderHandler.java @@ -2,16 +2,17 @@ package com.alibaba.cloud.sentinel.gateway.zuul; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.util.CollectionUtils; - 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; + +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.util.CollectionUtils; + /** * @author tiger */ diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java index 12a866b4..de7eda7d 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulAutoConfiguration.java @@ -20,17 +20,6 @@ import java.util.Optional; import javax.annotation.PostConstruct; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -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 com.alibaba.cloud.sentinel.gateway.ConfigConstants; import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.RequestOriginParser; import com.alibaba.csp.sentinel.adapter.gateway.zuul.callback.ZuulGatewayCallbackManager; @@ -40,6 +29,17 @@ import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilt import com.alibaba.csp.sentinel.config.SentinelConfig; import com.netflix.zuul.http.ZuulServlet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +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; /** * Sentinel Spring Cloud Zuul AutoConfiguration diff --git a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java index 5989b5d9..e36bc5d6 100644 --- a/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java +++ b/spring-cloud-alibaba-sentinel-gateway/src/main/java/com/alibaba/cloud/sentinel/gateway/zuul/SentinelZuulProperties.java @@ -16,15 +16,15 @@ package com.alibaba.cloud.sentinel.gateway.zuul; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.NestedConfigurationProperty; - import com.alibaba.cloud.sentinel.gateway.ConfigConstants; import com.alibaba.csp.sentinel.adapter.gateway.zuul.constants.ZuulConstant; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulErrorFilter; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPostFilter; import com.alibaba.csp.sentinel.adapter.gateway.zuul.filters.SentinelZuulPreFilter; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.boot.context.properties.NestedConfigurationProperty; + /** * @author Jim */ 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 index 921458e3..7501ee49 100644 --- 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 @@ -25,6 +25,7 @@ public interface SentinelConstants { String BLOCK_TYPE = "block"; String FALLBACK_TYPE = "fallback"; + String URLCLEANER_TYPE = "urlCleaner"; // commercialization diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java index 1f00c16d..ac10d2b4 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelProperties.java @@ -20,15 +20,15 @@ import java.util.List; import java.util.Map; import java.util.TreeMap; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.core.Ordered; -import org.springframework.validation.annotation.Validated; - import com.alibaba.cloud.sentinel.datasource.config.DataSourcePropertiesConfiguration; import com.alibaba.csp.sentinel.config.SentinelConfig; 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.core.Ordered; +import org.springframework.validation.annotation.Validated; + /** * {@link ConfigurationProperties} for Sentinel. * 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 index 5dfe6884..0e792fb1 100644 --- 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 @@ -23,8 +23,15 @@ 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; @@ -35,12 +42,6 @@ import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; - /** * @author xiaojing */ diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java index 86a6bcbc..431a2ac1 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/SentinelWebFluxAutoConfiguration.java @@ -22,8 +22,15 @@ import java.util.Optional; import javax.annotation.PostConstruct; +import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer; +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; + import org.springframework.beans.factory.ObjectProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; @@ -37,12 +44,6 @@ import org.springframework.core.annotation.Order; import org.springframework.http.codec.ServerCodecConfigurer; import org.springframework.web.reactive.result.view.ViewResolver; -import com.alibaba.csp.sentinel.adapter.reactor.SentinelReactorTransformer; -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; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java index 2638ee33..039c9b16 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/annotation/SentinelRestTemplate.java @@ -38,4 +38,7 @@ public @interface SentinelRestTemplate { Class fallbackClass() default void.class; + 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-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java index 1e5d6c8b..c543802e 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/BlockClassRegistry.java @@ -29,6 +29,7 @@ final class 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) { return FALLBACK_MAP.get(getKey(clazz, name)); @@ -38,6 +39,10 @@ final class BlockClassRegistry { return BLOCK_HANDLER_MAP.get(getKey(clazz, name)); } + static Method lookupUrlCleaner(Class clazz, String name) { + return URL_CLEANER_MAP.get(getKey(clazz, name)); + } + static void updateFallbackFor(Class clazz, String name, Method method) { if (clazz == null || StringUtil.isBlank(name)) { throw new IllegalArgumentException("Bad argument"); @@ -52,6 +57,13 @@ final class BlockClassRegistry { BLOCK_HANDLER_MAP.put(getKey(clazz, name), method); } + static void updateUrlCleanerFor(Class clazz, String name, Method method) { + if (clazz == null || StringUtil.isBlank(name)) { + throw new IllegalArgumentException("Bad argument"); + } + URL_CLEANER_MAP.put(getKey(clazz, name), method); + } + private static String getKey(Class clazz, String name) { return String.format("%s:%s", clazz.getCanonicalName(), name); } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java index a3b435bd..bfcdcd52 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelAutoConfiguration.java @@ -18,19 +18,6 @@ package com.alibaba.cloud.sentinel.custom; import javax.annotation.PostConstruct; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -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.ApplicationContext; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.core.env.Environment; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.SentinelProperties; import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; import com.alibaba.cloud.sentinel.datasource.converter.XmlConverter; @@ -51,6 +38,19 @@ import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.dataformat.xml.XmlMapper; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +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.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.env.Environment; +import org.springframework.util.StringUtils; + /** * @author xiaojing * @author jiashuai.xie diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java index 178060bf..10baa943 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelBeanPostProcessor.java @@ -20,8 +20,13 @@ import java.lang.reflect.Method; import java.util.Arrays; 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; + import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanDefinition; import org.springframework.beans.factory.support.BeanDefinitionBuilder; @@ -38,10 +43,6 @@ import org.springframework.util.ClassUtils; import org.springframework.util.StringUtils; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.sentinel.SentinelConstants; -import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; -import com.alibaba.csp.sentinel.slots.block.BlockException; - /** * PostProcessor handle @SentinelRestTemplate Annotation, add interceptor for RestTemplate * @@ -90,6 +91,9 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces checkBlock4RestTemplate(sentinelRestTemplate.fallbackClass(), sentinelRestTemplate.fallback(), beanName, SentinelConstants.FALLBACK_TYPE); + checkBlock4RestTemplate(sentinelRestTemplate.urlCleanerClass(), + sentinelRestTemplate.urlCleaner(), beanName, + SentinelConstants.URLCLEANER_TYPE); } private void checkBlock4RestTemplate(Class blockClass, String blockMethod, @@ -111,8 +115,14 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces throw new IllegalArgumentException(type + " method attribute exists but " + type + " class attribute is not exists in bean[" + beanName + "]"); } - Class[] args = new Class[] { HttpRequest.class, byte[].class, - ClientHttpRequestExecution.class, BlockException.class }; + Class[] args; + if (type.equals(SentinelConstants.URLCLEANER_TYPE)) { + args = new Class[] { String.class }; + } + else { + args = new Class[] { HttpRequest.class, byte[].class, + ClientHttpRequestExecution.class, BlockException.class }; + } String argsStr = Arrays.toString( Arrays.stream(args).map(clazz -> clazz.getSimpleName()).toArray()); Method foundMethod = ClassUtils.getStaticMethod(blockClass, blockMethod, args); @@ -127,21 +137,32 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces + ", please check your class name, method name and arguments"); } - if (!ClientHttpResponse.class.isAssignableFrom(foundMethod.getReturnType())) { - log.error( - "{} method return value in bean[{}] is not ClientHttpResponse: {}#{}{}", - type, beanName, blockClass.getName(), blockMethod, argsStr); + Class standardReturnType; + if (type.equals(SentinelConstants.URLCLEANER_TYPE)) { + standardReturnType = String.class; + } + else { + standardReturnType = ClientHttpResponse.class; + } + + if (!standardReturnType.isAssignableFrom(foundMethod.getReturnType())) { + log.error("{} method return value in bean[{}] is not {}: {}#{}{}", type, + beanName, standardReturnType.getName(), blockClass.getName(), + blockMethod, argsStr); throw new IllegalArgumentException(type + " method return value in bean[" - + beanName + "] is not ClientHttpResponse: " + blockClass.getName() - + "#" + blockMethod + argsStr); + + beanName + "] is not " + standardReturnType.getName() + ": " + + blockClass.getName() + "#" + blockMethod + argsStr); } if (type.equals(SentinelConstants.BLOCK_TYPE)) { BlockClassRegistry.updateBlockHandlerFor(blockClass, blockMethod, foundMethod); } - else { + else if (type.equals(SentinelConstants.FALLBACK_TYPE)) { BlockClassRegistry.updateFallbackFor(blockClass, blockMethod, foundMethod); } + else { + BlockClassRegistry.updateUrlCleanerFor(blockClass, blockMethod, foundMethod); + } } private boolean checkSentinelProtect(RootBeanDefinition beanDefinition, @@ -177,7 +198,9 @@ public class SentinelBeanPostProcessor implements MergedBeanDefinitionPostProces .append(sentinelRestTemplate.blockHandlerClass().getSimpleName()) .append(sentinelRestTemplate.blockHandler()).append("_") .append(sentinelRestTemplate.fallbackClass().getSimpleName()) - .append(sentinelRestTemplate.fallback()); + .append(sentinelRestTemplate.fallback()).append("_") + .append(sentinelRestTemplate.urlCleanerClass().getSimpleName()) + .append(sentinelRestTemplate.urlCleaner()); RestTemplate restTemplate = (RestTemplate) bean; String interceptorBeanName = interceptorBeanNamePrefix + "@" + bean.toString(); diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java index 526719bc..7642d9e8 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelCircuitBreakerConfiguration.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.custom; import org.springframework.context.annotation.Configuration; @@ -9,4 +25,5 @@ import org.springframework.context.annotation.Configuration; */ @Configuration public class SentinelCircuitBreakerConfiguration { + } diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java index 6c7d3f1d..eeae2998 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelDataSourceHandler.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.custom; import java.lang.reflect.Field; @@ -7,15 +23,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.SmartInitializingSingleton; -import org.springframework.beans.factory.support.BeanDefinitionBuilder; -import org.springframework.beans.factory.support.DefaultListableBeanFactory; -import org.springframework.core.env.Environment; -import org.springframework.util.ReflectionUtils; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.sentinel.SentinelProperties; import com.alibaba.cloud.sentinel.datasource.config.AbstractDataSourceProperties; import com.alibaba.cloud.sentinel.datasource.converter.JsonConverter; @@ -23,6 +30,16 @@ 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; + +import org.springframework.beans.factory.SmartInitializingSingleton; +import org.springframework.beans.factory.support.BeanDefinitionBuilder; +import org.springframework.beans.factory.support.DefaultListableBeanFactory; +import org.springframework.core.env.Environment; +import org.springframework.util.ReflectionUtils; +import org.springframework.util.StringUtils; + /** * Sentinel {@link ReadableDataSource} Handler Handle the configurations of * 'spring.cloud.sentinel.datasource' diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java index 4594caef..1c81e3ef 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/custom/SentinelProtectInterceptor.java @@ -21,12 +21,6 @@ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.net.URI; -import org.springframework.http.HttpRequest; -import org.springframework.http.client.ClientHttpRequestExecution; -import org.springframework.http.client.ClientHttpRequestInterceptor; -import org.springframework.http.client.ClientHttpResponse; -import org.springframework.web.client.RestTemplate; - import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; import com.alibaba.cloud.sentinel.rest.SentinelClientHttpResponse; import com.alibaba.csp.sentinel.Entry; @@ -36,6 +30,12 @@ import com.alibaba.csp.sentinel.Tracer; import com.alibaba.csp.sentinel.slots.block.BlockException; import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException; +import org.springframework.http.HttpRequest; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.web.client.RestTemplate; + /** * Interceptor using by SentinelRestTemplate * @@ -65,6 +65,14 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor if (hostResource.equals(hostWithPathResource)) { entryWithPath = false; } + Method urlCleanerMethod = BlockClassRegistry.lookupUrlCleaner( + sentinelRestTemplate.urlCleanerClass(), + sentinelRestTemplate.urlCleaner()); + if (urlCleanerMethod != null) { + hostWithPathResource = (String) methodInvoke(urlCleanerMethod, + hostWithPathResource); + } + Entry hostEntry = null, hostWithPathEntry = null; ClientHttpResponse response = null; try { @@ -105,7 +113,7 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor Method fallbackMethod = extractFallbackMethod(sentinelRestTemplate.fallback(), sentinelRestTemplate.fallbackClass()); if (fallbackMethod != null) { - return methodInvoke(fallbackMethod, args); + return (ClientHttpResponse) methodInvoke(fallbackMethod, args); } else { return new SentinelClientHttpResponse(); @@ -116,16 +124,16 @@ public class SentinelProtectInterceptor implements ClientHttpRequestInterceptor sentinelRestTemplate.blockHandler(), sentinelRestTemplate.blockHandlerClass()); if (blockHandler != null) { - return methodInvoke(blockHandler, args); + return (ClientHttpResponse) methodInvoke(blockHandler, args); } else { return new SentinelClientHttpResponse(); } } - private ClientHttpResponse methodInvoke(Method method, Object... args) { + private Object methodInvoke(Method method, Object... args) { try { - return (ClientHttpResponse) method.invoke(null, args); + return method.invoke(null, args); } catch (IllegalAccessException e) { throw new RuntimeException(e); diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java index 3d523ebb..bb1e1331 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpoint.java @@ -19,9 +19,6 @@ package com.alibaba.cloud.sentinel.endpoint; import java.util.HashMap; import java.util.Map; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - import com.alibaba.cloud.sentinel.SentinelProperties; import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig; import com.alibaba.csp.sentinel.config.SentinelConfig; @@ -34,6 +31,9 @@ import com.alibaba.csp.sentinel.slots.system.SystemRuleManager; import com.alibaba.csp.sentinel.transport.config.TransportConfig; import com.alibaba.csp.sentinel.util.AppNameUtil; +import org.springframework.boot.actuate.endpoint.annotation.Endpoint; +import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; + /** * Endpoint for Sentinel, contains ans properties and rules * @author xiaojing diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java index df8f6f45..e268e11e 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelEndpointAutoConfiguration.java @@ -16,6 +16,8 @@ package com.alibaba.cloud.sentinel.endpoint; +import com.alibaba.cloud.sentinel.SentinelProperties; + import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.actuate.autoconfigure.endpoint.condition.ConditionalOnEnabledEndpoint; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; @@ -25,8 +27,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; -import com.alibaba.cloud.sentinel.SentinelProperties; - /** * @author hengyunabc */ @@ -49,5 +49,4 @@ 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-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java index e5415047..72dc9bf9 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/endpoint/SentinelHealthIndicator.java @@ -19,6 +19,12 @@ package com.alibaba.cloud.sentinel.endpoint; import java.util.HashMap; import java.util.Map; +import com.alibaba.cloud.sentinel.SentinelProperties; +import com.alibaba.csp.sentinel.datasource.AbstractDataSource; +import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider; +import com.alibaba.csp.sentinel.transport.HeartbeatSender; +import com.alibaba.csp.sentinel.transport.config.TransportConfig; + import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; @@ -26,12 +32,6 @@ import org.springframework.boot.actuate.health.HealthIndicator; import org.springframework.boot.actuate.health.Status; import org.springframework.util.StringUtils; -import com.alibaba.cloud.sentinel.SentinelProperties; -import com.alibaba.csp.sentinel.datasource.AbstractDataSource; -import com.alibaba.csp.sentinel.heartbeat.HeartbeatSenderProvider; -import com.alibaba.csp.sentinel.transport.HeartbeatSender; -import com.alibaba.csp.sentinel.transport.config.TransportConfig; - /** * A {@link HealthIndicator} for Sentinel, which checks the status of Sentinel Dashboard * and DataSource. diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java index cabd7c20..b83fbfd9 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelContractHolder.java @@ -38,7 +38,7 @@ public class SentinelContractHolder implements Contract { * map key is constructed by ClassFullName + configKey. configKey is constructed by * {@link feign.Feign#configKey} */ - public final static Map METADATA_MAP = new HashMap(); + public final static Map METADATA_MAP = new HashMap<>(); public SentinelContractHolder(Contract delegate) { this.delegate = delegate; diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java index b869f844..f3849798 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeign.java @@ -21,12 +21,6 @@ import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.util.Map; -import org.springframework.beans.BeansException; -import org.springframework.cloud.openfeign.FeignContext; -import org.springframework.context.ApplicationContext; -import org.springframework.context.ApplicationContextAware; -import org.springframework.util.ReflectionUtils; - import feign.Contract; import feign.Feign; import feign.InvocationHandlerFactory; @@ -34,6 +28,12 @@ import feign.Target; import feign.hystrix.FallbackFactory; import feign.hystrix.HystrixFeign; +import org.springframework.beans.BeansException; +import org.springframework.cloud.openfeign.FeignContext; +import org.springframework.context.ApplicationContext; +import org.springframework.context.ApplicationContextAware; +import org.springframework.util.ReflectionUtils; + /** * {@link Feign.Builder} like {@link HystrixFeign.Builder} * diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java index 9989c996..5f393e6d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelFeignAutoConfiguration.java @@ -16,6 +16,10 @@ package com.alibaba.cloud.sentinel.feign; +import com.alibaba.csp.sentinel.SphU; + +import feign.Feign; + import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -23,10 +27,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; -import com.alibaba.csp.sentinel.SphU; - -import feign.Feign; - /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java index ef8c6c33..2693a796 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/feign/SentinelInvocationHandler.java @@ -16,8 +16,6 @@ package com.alibaba.cloud.sentinel.feign; -import static feign.Util.checkNotNull; - import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @@ -38,6 +36,8 @@ import feign.MethodMetadata; import feign.Target; import feign.hystrix.FallbackFactory; +import static feign.Util.checkNotNull; + /** * {@link InvocationHandler} handle invocation that protected by Sentinel * diff --git a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java index a38084e3..36dcab4d 100644 --- a/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java +++ b/spring-cloud-alibaba-sentinel/src/main/java/com/alibaba/cloud/sentinel/rest/SentinelClientHttpResponse.java @@ -24,14 +24,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; +import com.alibaba.cloud.sentinel.custom.SentinelProtectInterceptor; + import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.client.AbstractClientHttpResponse; -import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; -import com.alibaba.cloud.sentinel.custom.SentinelProtectInterceptor; - /** * Using by {@link SentinelRestTemplate} and {@link SentinelProtectInterceptor} * diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java index 24841208..5a0ba2e3 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java +++ b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelAutoConfigurationTests.java @@ -16,18 +16,29 @@ package com.alibaba.cloud.sentinel; -import static org.assertj.core.api.Assertions.assertThatExceptionOfType; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.mock; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - import java.util.Arrays; import java.util.Map; +import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; +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; +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 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; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -45,21 +56,11 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; -import com.alibaba.cloud.sentinel.annotation.SentinelRestTemplate; -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; -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 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 static org.assertj.core.api.Assertions.assertThatExceptionOfType; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.mock; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author Jim @@ -107,6 +108,7 @@ public class SentinelAutoConfigurationTests { private int port; private String flowUrl = "http://localhost:" + port + "/flow"; + private String degradeUrl = "http://localhost:" + port + "/degrade"; @Before diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java index ef8c67e3..7913ca18 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java +++ b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelBeanAutowiredTests.java @@ -16,24 +16,11 @@ package com.alibaba.cloud.sentinel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; - import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; -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.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.test.context.junit4.SpringRunner; - 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; @@ -42,6 +29,20 @@ 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 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.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; + /** * @author Jim */ diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java index 40446485..571f4cb0 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java +++ b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelDataSourceTests.java @@ -16,12 +16,12 @@ package com.alibaba.cloud.sentinel; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; +import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration; +import com.alibaba.cloud.sentinel.datasource.RuleType; 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; @@ -29,8 +29,9 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.cloud.sentinel.custom.SentinelAutoConfiguration; -import com.alibaba.cloud.sentinel.datasource.RuleType; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java index 92e17bea..f5e3666d 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java +++ b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelFeignTests.java @@ -16,17 +16,17 @@ package com.alibaba.cloud.sentinel; -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 java.util.Arrays; +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; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.ImportAutoConfiguration; @@ -39,10 +39,11 @@ import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; -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 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; /** * @author Jim diff --git a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java index d05624fb..fe1a107c 100644 --- a/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java +++ b/spring-cloud-alibaba-sentinel/src/test/java/com/alibaba/cloud/sentinel/SentinelRestTemplateTests.java @@ -16,9 +16,13 @@ package com.alibaba.cloud.sentinel; -import static org.junit.Assert.assertEquals; +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; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.AnnotationConfigApplicationContext; @@ -28,10 +32,7 @@ import org.springframework.http.HttpRequest; import org.springframework.http.client.ClientHttpRequestExecution; import org.springframework.web.client.RestTemplate; -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 static org.junit.Assert.assertEquals; /** * @author Jim @@ -91,6 +92,26 @@ public class SentinelRestTemplateTests { new AnnotationConfigApplicationContext(TestConfig10.class); } + @Test(expected = BeanCreationException.class) + public void testUrlClnMethod() { + new AnnotationConfigApplicationContext(TestConfig11.class); + } + + @Test(expected = BeanCreationException.class) + public void testUrlClnClass() { + new AnnotationConfigApplicationContext(TestConfig12.class); + } + + @Test(expected = BeanCreationException.class) + public void testUrlClnMethodExists() { + new AnnotationConfigApplicationContext(TestConfig13.class); + } + + @Test(expected = BeanCreationException.class) + public void testUrlClnReturnValue() { + new AnnotationConfigApplicationContext(TestConfig14.class); + } + @Configuration public static class TestConfig1 { @Bean @@ -160,7 +181,7 @@ public class SentinelRestTemplateTests { } @Bean - @SentinelRestTemplate(blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, blockHandler = "handleException", fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, fallback = "fallbackException") + @SentinelRestTemplate(blockHandlerClass = SentinelRestTemplateTests.ExceptionUtil.class, blockHandler = "handleException", fallbackClass = SentinelRestTemplateTests.ExceptionUtil.class, fallback = "fallbackException", urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, urlCleaner = "clean") RestTemplate restTemplate() { return new RestTemplate(); } @@ -247,6 +268,66 @@ public class SentinelRestTemplateTests { } } + @Configuration + public static class TestConfig11 { + @Bean + SentinelBeanPostProcessor sentinelBeanPostProcessor( + ApplicationContext applicationContext) { + return new SentinelBeanPostProcessor(applicationContext); + } + + @Bean + @SentinelRestTemplate(urlCleaner = "cln") + RestTemplate restTemplate() { + return new RestTemplate(); + } + } + + @Configuration + public static class TestConfig12 { + @Bean + SentinelBeanPostProcessor sentinelBeanPostProcessor( + ApplicationContext applicationContext) { + return new SentinelBeanPostProcessor(applicationContext); + } + + @Bean + @SentinelRestTemplate(urlCleanerClass = UrlCleanUtil.class) + RestTemplate restTemplate() { + return new RestTemplate(); + } + } + + @Configuration + public static class TestConfig13 { + @Bean + SentinelBeanPostProcessor sentinelBeanPostProcessor( + ApplicationContext applicationContext) { + return new SentinelBeanPostProcessor(applicationContext); + } + + @Bean + @SentinelRestTemplate(urlCleanerClass = SentinelRestTemplateTests.UrlCleanUtil.class, urlCleaner = "clean1") + RestTemplate restTemplate() { + return new RestTemplate(); + } + } + + @Configuration + public static class TestConfig14 { + @Bean + SentinelBeanPostProcessor sentinelBeanPostProcessor( + ApplicationContext applicationContext) { + return new SentinelBeanPostProcessor(applicationContext); + } + + @Bean + @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) { @@ -271,4 +352,13 @@ public class SentinelRestTemplateTests { } } + public static class UrlCleanUtil { + public static String clean(String url) { + return url; + } + + public static void clean2(String url) { + } + } + } diff --git a/spring-cloud-alibaba-sidecar/pom.xml b/spring-cloud-alibaba-sidecar/pom.xml new file mode 100644 index 00000000..b38ed31a --- /dev/null +++ b/spring-cloud-alibaba-sidecar/pom.xml @@ -0,0 +1,43 @@ + + + + com.alibaba.cloud + spring-cloud-alibaba + 2.0.1.BUILD-SNAPSHOT + + 4.0.0 + + spring-cloud-alibaba-sidecar + Spring Cloud Alibaba Sidecar + An easy way to integrate polyglot apps for Spring Cloud Alibaba. + + + + org.springframework.cloud + spring-cloud-starter-gateway + + + + org.springframework.boot + spring-boot-starter-actuator + + + + com.alibaba.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + org.springframework.cloud + spring-cloud-starter-consul-discovery + true + + + + org.springframework.boot + spring-boot-configuration-processor + true + + + diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java new file mode 100644 index 00000000..d31e5320 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarAutoConfiguration.java @@ -0,0 +1,56 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar; + +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; +import org.springframework.core.env.ConfigurableEnvironment; +import org.springframework.web.client.RestTemplate; + +/** + * @author www.itmuch.com + */ +@Configuration +@EnableConfigurationProperties(SidecarProperties.class) +public class SidecarAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + + @Bean + public SidecarHealthIndicator sidecarHealthIndicator( + SidecarProperties sidecarProperties, RestTemplate restTemplate) { + return new SidecarHealthIndicator(sidecarProperties, restTemplate); + } + + @Bean + public SidecarHealthChecker sidecarHealthChecker( + SidecarDiscoveryClient sidecarDiscoveryClient, + SidecarHealthIndicator sidecarHealthIndicator, + SidecarProperties sidecarProperties, ConfigurableEnvironment environment) { + SidecarHealthChecker cleaner = new SidecarHealthChecker(sidecarDiscoveryClient, + sidecarHealthIndicator, sidecarProperties, environment); + cleaner.check(); + return cleaner; + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java new file mode 100644 index 00000000..8a67c575 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarDiscoveryClient.java @@ -0,0 +1,40 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar; + +/** + * @author www.itmuch.com + */ +public interface SidecarDiscoveryClient { + + /** + * register instance. + * @param applicationName applicationName + * @param ip ip + * @param port port + */ + void registerInstance(String applicationName, String ip, Integer port); + + /** + * deregister instance. + * @param applicationName applicationName + * @param ip ip + * @param port port + */ + void deregisterInstance(String applicationName, String ip, Integer port); + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java new file mode 100644 index 00000000..2976e875 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthChecker.java @@ -0,0 +1,77 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar; + +import java.util.concurrent.TimeUnit; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import reactor.core.scheduler.Schedulers; + +import org.springframework.boot.actuate.health.HealthIndicator; +import org.springframework.boot.actuate.health.Status; +import org.springframework.core.env.ConfigurableEnvironment; + +/** + * @author www.itmuch.com + */ +public class SidecarHealthChecker { + + private static final Logger log = LoggerFactory.getLogger(SidecarHealthChecker.class); + + private final SidecarDiscoveryClient sidecarDiscoveryClient; + + private final HealthIndicator healthIndicator; + + private final SidecarProperties sidecarProperties; + + private final ConfigurableEnvironment environment; + + public SidecarHealthChecker(SidecarDiscoveryClient sidecarDiscoveryClient, + HealthIndicator healthIndicator, SidecarProperties sidecarProperties, + ConfigurableEnvironment environment) { + this.sidecarDiscoveryClient = sidecarDiscoveryClient; + this.healthIndicator = healthIndicator; + this.sidecarProperties = sidecarProperties; + this.environment = environment; + } + + public void check() { + Schedulers.single().schedulePeriodically(() -> { + String ip = sidecarProperties.getIp(); + Integer port = sidecarProperties.getPort(); + + Status status = healthIndicator.health().getStatus(); + String applicationName = environment.getProperty("spring.application.name"); + + if (status.equals(Status.UP)) { + this.sidecarDiscoveryClient.registerInstance(applicationName, ip, port); + log.debug( + "Health check success. register this instance. applicationName = {}, ip = {}, port = {}, status = {}", + applicationName, ip, port, status); + } + else { + log.warn( + "Health check failed. unregister this instance. applicationName = {}, ip = {}, port = {}, status = {}", + applicationName, ip, port, status); + this.sidecarDiscoveryClient.deregisterInstance(applicationName, ip, port); + } + + }, 0, sidecarProperties.getHealthCheckInterval(), TimeUnit.MILLISECONDS); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java new file mode 100644 index 00000000..4d07a380 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarHealthIndicator.java @@ -0,0 +1,81 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar; + +import java.net.URI; +import java.util.Map; + +import org.springframework.boot.actuate.health.AbstractHealthIndicator; +import org.springframework.boot.actuate.health.Health; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +/** + * @author www.itmuch.com + */ +public class SidecarHealthIndicator extends AbstractHealthIndicator { + + private final SidecarProperties sidecarProperties; + + private final RestTemplate restTemplate; + + public SidecarHealthIndicator(SidecarProperties sidecarProperties, + RestTemplate restTemplate) { + this.sidecarProperties = sidecarProperties; + this.restTemplate = restTemplate; + } + + @Override + protected void doHealthCheck(Health.Builder builder) throws Exception { + try { + URI uri = this.sidecarProperties.getHealthCheckUrl(); + if (uri == null) { + builder.up(); + return; + } + + ResponseEntity> exchange = this.restTemplate.exchange(uri, + HttpMethod.GET, null, + new ParameterizedTypeReference>() { + }); + + Map map = exchange.getBody(); + + if (map == null) { + this.getWarning(builder); + return; + } + Object status = map.get("status"); + if (status instanceof String) { + builder.status(status.toString()); + } + else { + this.getWarning(builder); + } + } + catch (Exception e) { + builder.down().withDetail("error", e.getMessage()); + } + } + + private void getWarning(Health.Builder builder) { + builder.unknown().withDetail("warning", "no status field in response"); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java new file mode 100644 index 00000000..b95f9189 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/SidecarProperties.java @@ -0,0 +1,91 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar; + +import java.net.URI; + +import javax.validation.constraints.Max; +import javax.validation.constraints.Min; +import javax.validation.constraints.NotNull; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; + +/** + * @author www.itmuch.com + */ +@ConfigurationProperties("sidecar") +@Validated +public class SidecarProperties { + + /** + * polyglot service's ip. + */ + private String ip; + + /** + * polyglot service's port. + */ + @NotNull + @Max(65535) + @Min(1) + private Integer port; + + /** + * polyglot service's health check url. this endpoint must return json and the format + * must follow spring boot actuator's health endpoint. eg. {"status": "UP"}. + */ + private URI healthCheckUrl; + + /** + * interval of health check. + */ + private long healthCheckInterval = 30000L; + + public String getIp() { + return ip; + } + + public void setIp(String ip) { + this.ip = ip; + } + + public Integer getPort() { + return port; + } + + public void setPort(Integer port) { + this.port = port; + } + + public URI getHealthCheckUrl() { + return healthCheckUrl; + } + + public void setHealthCheckUrl(URI healthCheckUrl) { + this.healthCheckUrl = healthCheckUrl; + } + + public long getHealthCheckInterval() { + return healthCheckInterval; + } + + public void setHealthCheckInterval(long healthCheckInterval) { + this.healthCheckInterval = healthCheckInterval; + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java new file mode 100644 index 00000000..51ce4a86 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoConfiguration.java @@ -0,0 +1,70 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar.consul; + +import java.util.List; + +import com.alibaba.cloud.sidecar.SidecarAutoConfiguration; +import com.alibaba.cloud.sidecar.SidecarDiscoveryClient; +import com.alibaba.cloud.sidecar.SidecarProperties; + +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; +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.ConsulAutoServiceRegistrationAutoConfiguration; +import org.springframework.cloud.consul.serviceregistry.ConsulRegistrationCustomizer; +import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; +import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistryAutoConfiguration; +import org.springframework.context.ApplicationContext; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +/** + * @author www.itmuch.com + */ +@Configuration +@ConditionalOnClass(ConsulServiceRegistryAutoConfiguration.class) +@AutoConfigureBefore({ ConsulAutoServiceRegistrationAutoConfiguration.class, + SidecarAutoConfiguration.class }) +public class SidecarConsulAutoConfiguration { + + @Bean + public ConsulAutoRegistration consulRegistration( + AutoServiceRegistrationProperties autoServiceRegistrationProperties, + ConsulDiscoveryProperties properties, ApplicationContext applicationContext, + ObjectProvider> registrationCustomizers, + HeartbeatProperties heartbeatProperties, + SidecarProperties sidecarProperties) { + return SidecarConsulAutoRegistration.registration( + autoServiceRegistrationProperties, properties, applicationContext, + registrationCustomizers.getIfAvailable(), heartbeatProperties, + sidecarProperties); + } + + @Bean + public SidecarDiscoveryClient sidecarDiscoveryClient( + ConsulDiscoveryProperties properties, ConsulServiceRegistry serviceRegistry, + ConsulAutoRegistration registration) { + return new SidecarConsulDiscoveryClient(properties, serviceRegistry, + registration); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java new file mode 100644 index 00000000..2e816bbb --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulAutoRegistration.java @@ -0,0 +1,85 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.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.ConsulRegistrationCustomizer; +import org.springframework.context.ApplicationContext; +import org.springframework.core.env.Environment; + +/** + * @author www.itmuch.com + */ +public class SidecarConsulAutoRegistration extends ConsulAutoRegistration { + + public SidecarConsulAutoRegistration(NewService service, + AutoServiceRegistrationProperties autoServiceRegistrationProperties, + ConsulDiscoveryProperties properties, ApplicationContext context, + HeartbeatProperties heartbeatProperties) { + super(service, autoServiceRegistrationProperties, properties, context, + heartbeatProperties); + } + + public static ConsulAutoRegistration registration( + AutoServiceRegistrationProperties autoServiceRegistrationProperties, + ConsulDiscoveryProperties properties, ApplicationContext context, + List registrationCustomizers, + HeartbeatProperties heartbeatProperties, + SidecarProperties sidecarProperties) { + + NewService service = new NewService(); + String appName = getAppName(properties, context.getEnvironment()); + service.setId(getInstanceId(sidecarProperties, context.getEnvironment())); + if (!properties.isPreferAgentAddress()) { + service.setAddress(sidecarProperties.getIp()); + } + service.setName(normalizeForDns(appName)); + service.setTags(createTags(properties)); + + // set health check, use alibaba sidecar self's port rather than polyglot app's + // port. + service.setPort( + Integer.valueOf(context.getEnvironment().getProperty("server.port"))); + setCheck(service, autoServiceRegistrationProperties, properties, context, + heartbeatProperties); + + service.setPort(sidecarProperties.getPort()); + + ConsulAutoRegistration registration = new ConsulAutoRegistration(service, + autoServiceRegistrationProperties, properties, context, + heartbeatProperties); + customize(registrationCustomizers, registration); + return registration; + } + + public static String getInstanceId(SidecarProperties sidecarProperties, + Environment environment) { + return String.format("%s-%s-%s", + environment.getProperty("spring.application.name"), + sidecarProperties.getIp(), sidecarProperties.getPort()); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.java new file mode 100644 index 00000000..49088f3a --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/consul/SidecarConsulDiscoveryClient.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.sidecar.consul; + +import com.alibaba.cloud.sidecar.SidecarDiscoveryClient; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties; +import org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration; +import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry; + +/** + * @author www.itmuch.com + */ +public class SidecarConsulDiscoveryClient implements SidecarDiscoveryClient { + + private static final Logger log = LoggerFactory + .getLogger(SidecarConsulDiscoveryClient.class); + + private final ConsulDiscoveryProperties properties; + + private final ConsulServiceRegistry serviceRegistry; + + private final ConsulAutoRegistration registration; + + public SidecarConsulDiscoveryClient(ConsulDiscoveryProperties properties, + ConsulServiceRegistry serviceRegistry, ConsulAutoRegistration registration) { + this.properties = properties; + this.serviceRegistry = serviceRegistry; + this.registration = registration; + } + + @Override + public void registerInstance(String applicationName, String ip, Integer port) { + + if (!this.properties.isRegister()) { + log.debug("Registration disabled."); + return; + } + + serviceRegistry.register(registration); + + } + + @Override + public void deregisterInstance(String applicationName, String ip, Integer port) { + if (!this.properties.isRegister() || !this.properties.isDeregister()) { + return; + } + serviceRegistry.deregister(registration); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java new file mode 100644 index 00000000..1c1f28af --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosAutoConfiguration.java @@ -0,0 +1,54 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar.nacos; + +import com.alibaba.cloud.nacos.NacosDiscoveryAutoConfiguration; +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.sidecar.SidecarAutoConfiguration; +import com.alibaba.cloud.sidecar.SidecarDiscoveryClient; +import com.alibaba.cloud.sidecar.SidecarProperties; + +import org.springframework.boot.autoconfigure.AutoConfigureBefore; +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; + +/** + * @author www.itmuch.com + */ +@Configuration +@AutoConfigureBefore({ NacosDiscoveryAutoConfiguration.class, + SidecarAutoConfiguration.class }) +@ConditionalOnClass(NacosDiscoveryProperties.class) +public class SidecarNacosAutoConfiguration { + + @Bean + @ConditionalOnMissingBean + public SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties( + SidecarProperties sidecarProperties) { + return new SidecarNacosDiscoveryProperties(sidecarProperties); + } + + @Bean + @ConditionalOnMissingBean + public SidecarDiscoveryClient sidecarDiscoveryClient( + SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) { + return new SidecarNacosDiscoveryClient(sidecarNacosDiscoveryProperties); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.java new file mode 100644 index 00000000..e4302afe --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryClient.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.sidecar.nacos; + +import com.alibaba.cloud.sidecar.SidecarDiscoveryClient; +import com.alibaba.nacos.api.exception.NacosException; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * @author www.itmuch.com + */ +public class SidecarNacosDiscoveryClient implements SidecarDiscoveryClient { + + private static final Logger log = LoggerFactory + .getLogger(SidecarNacosDiscoveryClient.class); + + private final SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties; + + public SidecarNacosDiscoveryClient( + SidecarNacosDiscoveryProperties sidecarNacosDiscoveryProperties) { + this.sidecarNacosDiscoveryProperties = sidecarNacosDiscoveryProperties; + } + + @Override + public void registerInstance(String applicationName, String ip, Integer port) { + try { + this.sidecarNacosDiscoveryProperties.namingServiceInstance() + .registerInstance(applicationName, ip, port); + } + catch (NacosException e) { + log.warn("nacos exception happens", e); + } + } + + @Override + public void deregisterInstance(String applicationName, String ip, Integer port) { + try { + this.sidecarNacosDiscoveryProperties.namingServiceInstance() + .deregisterInstance(applicationName, ip, port); + } + catch (NacosException e) { + log.warn("nacos exception happens", e); + } + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java new file mode 100644 index 00000000..d58c60c1 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/java/com/alibaba/cloud/sidecar/nacos/SidecarNacosDiscoveryProperties.java @@ -0,0 +1,49 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.sidecar.nacos; + +import java.net.SocketException; + +import com.alibaba.cloud.nacos.NacosDiscoveryProperties; +import com.alibaba.cloud.sidecar.SidecarProperties; +import org.apache.commons.lang3.StringUtils; + +/** + * @author itmuch.com + */ +public class SidecarNacosDiscoveryProperties extends NacosDiscoveryProperties { + + private final SidecarProperties sidecarProperties; + + public SidecarNacosDiscoveryProperties(SidecarProperties sidecarProperties) { + this.sidecarProperties = sidecarProperties; + } + + @Override + public void init() throws SocketException { + super.init(); + + String ip = sidecarProperties.getIp(); + if (StringUtils.isNotBlank(ip)) { + this.setIp(ip); + } + + Integer port = sidecarProperties.getPort(); + this.setPort(port); + } + +} diff --git a/spring-cloud-alibaba-sidecar/src/main/resources/META-INF/spring.factories b/spring-cloud-alibaba-sidecar/src/main/resources/META-INF/spring.factories new file mode 100644 index 00000000..726e9382 --- /dev/null +++ b/spring-cloud-alibaba-sidecar/src/main/resources/META-INF/spring.factories @@ -0,0 +1,4 @@ +org.springframework.boot.autoconfigure.EnableAutoConfiguration=\ + com.alibaba.cloud.sidecar.nacos.SidecarNacosAutoConfiguration,\ + com.alibaba.cloud.sidecar.SidecarAutoConfiguration,\ + com.alibaba.cloud.sidecar.consul.SidecarConsulAutoConfiguration \ No newline at end of file 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 index ac82882f..a069add5 100644 --- 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 @@ -16,6 +16,12 @@ 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; @@ -25,12 +31,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; - /** * Created on 01/10/2017. * 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 index e16d686c..def27cf6 100644 --- 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 @@ -19,13 +19,13 @@ 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; -import com.alibaba.alicloud.acm.bootstrap.AcmPropertySource; - /** * @author juven.xuxb, 5/17/16. */ 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 index 5c45cfeb..75a1a514 100644 --- 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 @@ -23,15 +23,16 @@ 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; -import com.alibaba.edas.acm.ConfigService; -import com.alibaba.edas.acm.exception.ConfigException; - /** * @author juven.xuxb * @author xiaolongzuo 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 index 3dae0710..a0c9fed6 100644 --- 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 @@ -16,6 +16,8 @@ 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; @@ -23,8 +25,6 @@ import org.springframework.core.env.CompositePropertySource; import org.springframework.core.env.Environment; import org.springframework.core.env.PropertySource; -import com.alibaba.alicloud.context.acm.AcmIntegrationProperties; - /** * @author juven.xuxb * @author xiaolongzuo 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 index 172b058a..ce6ea784 100644 --- 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 @@ -23,14 +23,14 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - 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. * 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 index 587e90a2..ab92119c 100644 --- 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 @@ -16,6 +16,10 @@ 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; @@ -24,10 +28,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; -import com.alibaba.alicloud.acm.AcmPropertySourceRepository; -import com.alibaba.alicloud.acm.refresh.AcmRefreshHistory; -import com.alibaba.alicloud.context.acm.AcmProperties; - /** * @author xiaojing */ 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 index d172baa4..2c4095a8 100644 --- 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 @@ -19,15 +19,15 @@ package com.alibaba.alicloud.acm.endpoint; import java.util.ArrayList; import java.util.List; -import org.springframework.boot.actuate.health.AbstractHealthIndicator; -import org.springframework.boot.actuate.health.Health; -import org.springframework.util.StringUtils; - 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 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 index 245d578e..846992ce 100644 --- 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 @@ -23,8 +23,14 @@ 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; @@ -34,11 +40,6 @@ import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationListener; import org.springframework.util.StringUtils; -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; - /** * On application start up, AcmContextRefresher add diamond listeners to all application * level dataIds, when there is a change in the data, listeners will refresh 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 index 038983d9..db9cc369 100644 --- 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 @@ -16,14 +16,16 @@ package com.alibaba.alicloud.acm; -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; - 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; @@ -32,6 +34,7 @@ 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; @@ -40,12 +43,10 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -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 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 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 index 52daad49..e3469efb 100644 --- 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 @@ -16,11 +16,13 @@ package com.alibaba.alicloud.acm; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - 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; @@ -29,6 +31,7 @@ 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; @@ -37,9 +40,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.edas.acm.ConfigService; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing 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 index ba25f8db..b6629dfa 100644 --- 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 @@ -16,11 +16,13 @@ package com.alibaba.alicloud.acm; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - 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; @@ -29,6 +31,7 @@ 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; @@ -37,9 +40,7 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.acm.endpoint.AcmEndpointAutoConfiguration; -import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; -import com.alibaba.edas.acm.ConfigService; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing 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 index 36376ae9..0263c9a7 100644 --- 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 @@ -16,15 +16,19 @@ package com.alibaba.alicloud.acm.endpoint; -import static org.junit.Assert.assertEquals; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; - 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; @@ -33,6 +37,7 @@ 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; @@ -41,12 +46,8 @@ import org.springframework.boot.test.context.SpringBootTest; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -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 static org.junit.Assert.assertEquals; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.NONE; /** * @author xiaojing 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 index c86049e9..f3933722 100644 --- 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 @@ -16,6 +16,11 @@ 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; @@ -28,11 +33,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; - /** * @author xiaolongzuo */ 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 index 7f7d34ab..f0c7e09d 100644 --- 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 @@ -23,12 +23,12 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.springframework.cloud.client.ServiceInstance; -import org.springframework.cloud.client.discovery.DiscoveryClient; - 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 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 index d119791d..d3fab935 100644 --- 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 @@ -21,15 +21,16 @@ import java.util.List; import java.util.Map; import java.util.Set; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - 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 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 index befe6733..26e16205 100644 --- 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 @@ -16,13 +16,13 @@ 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; -import com.alibaba.alicloud.context.ans.AnsProperties; - /** * @author xiaolongzuo */ 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 index c7612698..1c0d71a3 100644 --- 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 @@ -18,6 +18,7 @@ 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; 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 index 8f738260..f4f51193 100644 --- 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 @@ -21,6 +21,8 @@ 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; @@ -29,8 +31,6 @@ import org.springframework.context.ApplicationContext; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; -import com.alibaba.alicloud.context.ans.AnsProperties; - /** * @author xiaolongzuo */ 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 index fda95738..647ea12b 100644 --- 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 @@ -20,13 +20,14 @@ 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; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.ipms.NodeReactor; +import org.springframework.cloud.client.serviceregistry.ServiceRegistry; /** * @author xiaolongzuo 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 index 59ba3fa6..afde04b6 100644 --- 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 @@ -16,13 +16,13 @@ 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; -import com.netflix.client.config.IClientConfig; -import com.netflix.loadbalancer.ServerList; - /** * @author xiaolongzuo * @author pbting 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 index 5c4ddb88..e73052d5 100644 --- 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 @@ -16,6 +16,8 @@ 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; @@ -24,8 +26,6 @@ import org.springframework.cloud.netflix.ribbon.RibbonClients; import org.springframework.cloud.netflix.ribbon.SpringClientFactory; import org.springframework.context.annotation.Configuration; -import com.alibaba.alicloud.ans.ConditionalOnAnsEnabled; - /** * @author xiaolongzuo */ 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 index 009db660..b18d8fa1 100644 --- 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 @@ -16,26 +16,27 @@ package com.alibaba.alicloud.ans; -import static org.assertj.core.api.Assertions.assertThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.when; - 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 com.alibaba.alicloud.ans.test.AnsMockTest; -import com.alibaba.ans.core.NamingService; -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; /** * @author xiaojing 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 index 21c78b6b..8ebd43e8 100644 --- 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 @@ -16,12 +16,13 @@ package com.alibaba.alicloud.ans.registry; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -30,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; +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 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 index ebfbf090..4211aec8 100644 --- 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 @@ -16,17 +16,18 @@ package com.alibaba.alicloud.ans.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; - 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; @@ -36,9 +37,9 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; +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 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 index ed185a98..7386fbb8 100644 --- 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 @@ -16,12 +16,13 @@ package com.alibaba.alicloud.ans.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -30,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; +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 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 index c3a89ab6..7f959fd8 100644 --- 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 @@ -16,14 +16,13 @@ package com.alibaba.alicloud.ans.registry; -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; +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; @@ -32,9 +31,11 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; +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 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 index 46ed81b2..4d3fa817 100644 --- 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 @@ -16,12 +16,13 @@ package com.alibaba.alicloud.ans.registry; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -30,9 +31,9 @@ import org.springframework.cloud.client.serviceregistry.AutoServiceRegistrationC import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -import com.alibaba.alicloud.ans.AnsAutoConfiguration; -import com.alibaba.alicloud.ans.AnsDiscoveryClientAutoConfiguration; -import com.alibaba.alicloud.context.ans.AnsProperties; +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 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 index e44467fc..c22eb988 100644 --- 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 @@ -16,18 +16,21 @@ package com.alibaba.alicloud.ans.registry; -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; - 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; @@ -38,12 +41,10 @@ import org.springframework.cloud.commons.util.InetUtils; import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; -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 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 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 index f5d1587e..b1470c00 100644 --- 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 @@ -16,11 +16,14 @@ package com.alibaba.alicloud.ans.ribbon; -import static org.assertj.core.api.Assertions.assertThat; -import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; +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; @@ -32,11 +35,8 @@ import org.springframework.context.annotation.Configuration; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.web.client.RestTemplate; -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 static org.assertj.core.api.Assertions.assertThat; +import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT; /** * @author xiaojing 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 index 9d62610d..956062fa 100644 --- 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 @@ -16,18 +16,17 @@ package com.alibaba.alicloud.ans.ribbon; -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; - 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; @@ -35,11 +34,11 @@ import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; -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 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 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 index bef39ad7..23476abb 100644 --- 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 @@ -16,21 +16,20 @@ 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; -import java.util.Arrays; -import java.util.List; - -import org.junit.Test; - -import com.alibaba.ans.shaded.com.taobao.vipserver.client.core.Host; - -import com.netflix.loadbalancer.Server; - /** * @author xiaolongzuo */ 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 index a43c695d..1b498c96 100644 --- 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 @@ -16,10 +16,10 @@ package com.alibaba.alicloud.context; -import org.springframework.boot.context.properties.ConfigurationProperties; - import com.alibaba.cloud.context.AliCloudConfiguration; +import org.springframework.boot.context.properties.ConfigurationProperties; + /** * @author xiaolongzuo */ 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 index 0be77f62..16605a70 100644 --- 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 @@ -18,6 +18,11 @@ 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; @@ -28,11 +33,6 @@ import org.springframework.core.env.Environment; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -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; - /** * @author xiaolongzuo */ 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 index f66ba230..48a50f7d 100644 --- 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 @@ -16,11 +16,11 @@ package com.alibaba.alicloud.context.acm; -import org.springframework.boot.context.properties.ConfigurationProperties; - import com.alibaba.cloud.context.AliCloudServerMode; import com.alibaba.cloud.context.acm.AcmConfiguration; +import org.springframework.boot.context.properties.ConfigurationProperties; + /** * acm properties * 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 index 6d028331..415e2a47 100644 --- 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 @@ -16,15 +16,15 @@ package com.alibaba.alicloud.context.ans; -import org.springframework.context.ApplicationContext; -import org.springframework.context.event.ContextRefreshedEvent; - 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. * 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 index 56f8ebc9..ba06520c 100644 --- 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 @@ -16,13 +16,13 @@ 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; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; - /** * @author xiaolongzuo */ 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 index 99aa4a69..5a541cbf 100644 --- 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 @@ -26,15 +26,15 @@ 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; -import com.alibaba.cloud.context.AliCloudServerMode; -import com.alibaba.cloud.context.ans.AnsConfiguration; - /** * @author xiaolongzuo */ 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 index 61a8e1da..dcf9f28b 100644 --- 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 @@ -16,6 +16,11 @@ 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; @@ -23,11 +28,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; - /** * @author xiaolongzuo */ 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 index c34979c9..2c99b417 100644 --- 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 @@ -16,11 +16,11 @@ 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; -import com.alibaba.cloud.context.edas.EdasConfiguration; - /** * @author xiaolongzuo */ 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 index e413edcf..695ee518 100644 --- 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 @@ -1,13 +1,14 @@ package com.alibaba.alicloud.context.nacos; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - 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 */ 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 index 2abba6ee..8a347aa8 100644 --- 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 @@ -17,14 +17,15 @@ package com.alibaba.alicloud.context.nacos; import java.util.Properties; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - 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 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 index 840783f8..ea619cf3 100644 --- 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 @@ -16,6 +16,13 @@ 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; @@ -26,13 +33,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -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; - /** * OSS Auto {@link Configuration} * 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 index a261e6ad..33c46092 100644 --- 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 @@ -16,13 +16,13 @@ package com.alibaba.alicloud.context.oss; -import org.springframework.beans.factory.annotation.Value; -import org.springframework.boot.context.properties.ConfigurationProperties; - 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. * 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 index 69504bb9..7b154521 100644 --- 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 @@ -16,6 +16,13 @@ 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; @@ -24,13 +31,6 @@ import org.springframework.boot.context.properties.EnableConfigurationProperties import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -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; - /** * @author xiaolongzuo */ 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 index e0671705..93002ce3 100644 --- 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 @@ -16,10 +16,10 @@ package com.alibaba.alicloud.context.scx; -import org.springframework.boot.context.properties.ConfigurationProperties; - import com.alibaba.cloud.context.scx.ScxConfiguration; +import org.springframework.boot.context.properties.ConfigurationProperties; + /** * @author xiaolongzuo */ 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 index 2a0c6b50..b049e1dd 100644 --- 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 @@ -16,15 +16,16 @@ package com.alibaba.alicloud.context.sentinel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent; - 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 */ 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 index c3e64a66..fbb81e23 100644 --- 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 @@ -19,11 +19,6 @@ package com.alibaba.alicloud.context.statistics; import java.util.ArrayList; import java.util.List; -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; - import com.alibaba.alicloud.context.acm.AcmContextBootstrapConfiguration; import com.alibaba.alicloud.context.acm.AcmProperties; import com.alibaba.alicloud.context.ans.AnsContextAutoConfiguration; @@ -37,6 +32,11 @@ 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 */ 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 index 34afd223..f0c00f04 100644 --- 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 @@ -16,12 +16,13 @@ package com.alibaba.alicloud.context; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; - 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 */ 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 index 72fe9d28..7cd533bf 100644 --- 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 @@ -20,6 +20,7 @@ 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; 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 index cbd4ff90..26eeba63 100644 --- 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 @@ -16,16 +16,17 @@ package com.alibaba.alicloud.context.acm; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - 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 */ 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 index a60923be..7f04a791 100644 --- 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 @@ -16,11 +16,11 @@ package com.alibaba.alicloud.context.ans; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; import org.junit.Test; -import com.alibaba.alicloud.context.BaseAliCloudSpringApplication; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** * @author xiaolongzuo 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 index 225acc7b..b5034598 100644 --- 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 @@ -16,25 +16,26 @@ package com.alibaba.alicloud.context.ans; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; - 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 com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; -import com.alibaba.cloud.context.AliCloudServerMode; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** * @author xiaolongzuo 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 index f16d9f6c..3e9b28e8 100644 --- 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 @@ -16,13 +16,14 @@ package com.alibaba.alicloud.context.edas; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +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 com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; +import static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author xiaolongzuo 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 index 6b028f09..61532226 100644 --- 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 @@ -16,16 +16,16 @@ package com.alibaba.alicloud.context.nacos; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +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 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 static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author xiaolongzuo 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 index 58ceebd6..5ba92819 100644 --- 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 @@ -16,16 +16,16 @@ package com.alibaba.alicloud.context.nacos; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +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 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 static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author xiaolongzuo 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 index b3317a29..ecbd0c0f 100644 --- 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 @@ -16,16 +16,16 @@ package com.alibaba.alicloud.context.oss; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - 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 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 index c9803f81..38fd1f7f 100644 --- 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 @@ -16,13 +16,14 @@ package com.alibaba.alicloud.context.scx; -import static org.assertj.core.api.Assertions.assertThat; +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 com.alibaba.alicloud.context.edas.EdasProperties; +import static org.assertj.core.api.Assertions.assertThat; /** * @author xiaolongzuo 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 index abc88e33..5fde2951 100644 --- 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 @@ -16,16 +16,16 @@ package com.alibaba.alicloud.context.sentinel; -import static org.assertj.core.api.AssertionsForClassTypes.assertThat; +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 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 static org.assertj.core.api.AssertionsForClassTypes.assertThat; /** * @author xiaolongzuo 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 index 2943f8de..dd1965b8 100644 --- 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 @@ -16,15 +16,16 @@ package com.alibaba.alicloud.context.sms; -import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; +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 com.alibaba.alicloud.context.AliCloudContextAutoConfiguration; -import com.alibaba.alicloud.context.edas.EdasContextAutoConfiguration; +import static org.assertj.core.api.AssertionsForInterfaceTypes.assertThat; /** * @author xiaolongzuo 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 index 316f1758..f03bd41f 100644 --- 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 @@ -16,11 +16,11 @@ package com.alibaba.alicloud.utils; -import org.powermock.api.mockito.PowerMockito; - import com.alibaba.cloud.context.edas.EdasChangeOrderConfiguration; import com.alibaba.cloud.context.edas.EdasChangeOrderConfigurationFactory; +import org.powermock.api.mockito.PowerMockito; + /** * @author xiaolongzuo */ diff --git a/spring-cloud-alicloud-oss/pom.xml b/spring-cloud-alicloud-oss/pom.xml index 2efe04c8..0089180b 100644 --- a/spring-cloud-alicloud-oss/pom.xml +++ b/spring-cloud-alicloud-oss/pom.xml @@ -58,5 +58,11 @@ test + + org.mockito + mockito-core + test + + 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 index 7024cfc2..74cda28d 100644 --- 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 @@ -18,13 +18,13 @@ 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; -import com.aliyun.oss.OSS; - /** * Shutdown All OSS Clients when {@code ApplicationContext} gets closed * {@link ApplicationListener} 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 index 0cbf049e..2d87eddc 100644 --- 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 @@ -16,18 +16,24 @@ 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 com.alibaba.alicloud.oss.resource.OssStorageProtocolResolver; - -import com.aliyun.oss.OSS; +import static com.alibaba.alicloud.oss.OssConstants.OSS_TASK_EXECUTOR_BEAN_NAME; /** - * OSS Auto {@link Configuration} + * OSS Auto {@link Configuration}. * * @author Jim */ @@ -42,4 +48,12 @@ public class OssAutoConfiguration { 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 index d018b892..8bee73f6 100644 --- 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 @@ -17,13 +17,29 @@ package com.alibaba.alicloud.oss; /** - * OSS constants + * OSS constants. * * @author Jim */ -public interface OssConstants { +public final class OssConstants { - String PREFIX = "spring.cloud.alibaba.oss"; - String ENABLED = PREFIX + ".enabled"; + /** + * 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 index e7ef504d..40a2d3a6 100644 --- 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 @@ -21,13 +21,13 @@ 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; -import com.aliyun.oss.OSSClient; - /** * Actuator {@link Endpoint} to expose OSS Meta Data * 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 index 2d1f2d50..0a372e1d 100644 --- 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 @@ -16,8 +16,10 @@ 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; @@ -27,8 +29,6 @@ import org.springframework.core.io.ProtocolResolver; import org.springframework.core.io.Resource; import org.springframework.core.io.ResourceLoader; -import com.aliyun.oss.OSS; - /** * A {@link ProtocolResolver} implementation for the {@code oss://} protocol. * @@ -37,6 +37,9 @@ import com.aliyun.oss.OSS; public class OssStorageProtocolResolver implements ProtocolResolver, BeanFactoryPostProcessor, ResourceLoaderAware { + /** + * protocol of oss resource. + */ public static final String PROTOCOL = "oss://"; private static final Logger log = LoggerFactory @@ -63,7 +66,7 @@ public class OssStorageProtocolResolver if (!location.startsWith(PROTOCOL)) { return null; } - return new OssStorageResource(getOSS(), location); + return new OssStorageResource(getOSS(), location, beanFactory); } @Override @@ -82,4 +85,5 @@ public class OssStorageProtocolResolver 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 index 6137b2d5..6f84d2b5 100644 --- 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 @@ -20,18 +20,28 @@ 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 org.springframework.core.io.Resource; -import org.springframework.util.Assert; +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 @@ -43,18 +53,40 @@ import com.aliyun.oss.model.OSSObject; * @see Bucket * @see OSSObject */ -public class OssStorageResource implements Resource { +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; - public OssStorageResource(OSS oss, String 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(); @@ -70,6 +102,13 @@ public class OssStorageResource implements Resource { 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 @@ -125,7 +164,7 @@ public class OssStorageResource implements Resource { @Override public Resource createRelative(String relativePath) throws IOException { return new OssStorageResource(this.oss, - this.location.resolve(relativePath).toString()); + this.location.resolve(relativePath).toString(), this.beanFactory); } @Override @@ -157,7 +196,7 @@ public class OssStorageResource implements Resource { public Bucket getBucket() { return this.oss.listBuckets().stream() .filter(bucket -> bucket.getName().equals(this.bucketName)).findFirst() - .get(); + .orElse(null); } /** @@ -193,4 +232,70 @@ public class OssStorageResource implements Resource { } } + /** + * 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/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java b/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java new file mode 100644 index 00000000..0d429975 --- /dev/null +++ b/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/DummyOssClient.java @@ -0,0 +1,104 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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 new file mode 100644 index 00000000..2e977102 --- /dev/null +++ b/spring-cloud-alicloud-oss/src/test/java/com/alibaba/alicloud/oss/resource/OssStorageResourceTest.java @@ -0,0 +1,273 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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/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 index 2f173666..8334aff1 100644 --- 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 @@ -19,14 +19,15 @@ package com.alibaba.alicloud.scx.endpoint; import java.util.HashMap; import java.util.Map; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.boot.actuate.endpoint.annotation.Endpoint; -import org.springframework.boot.actuate.endpoint.annotation.ReadOperation; - 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 */ 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 index 98563e3a..e841b845 100644 --- 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 @@ -16,6 +16,9 @@ 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; @@ -23,9 +26,6 @@ import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication; import org.springframework.context.annotation.Bean; -import com.alibaba.alicloud.context.edas.EdasProperties; -import com.alibaba.alicloud.context.scx.ScxProperties; - /** * @author xiaolongzuo */ 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 index 5724785c..60ff79c1 100644 --- 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 @@ -18,16 +18,16 @@ package com.alibaba.alicloud.sms; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; -import org.springframework.boot.context.event.ApplicationStartedEvent; -import org.springframework.context.ApplicationListener; -import org.springframework.stereotype.Component; - 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 */ 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 index b7e6ea3b..79dc7800 100644 --- 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 @@ -17,9 +17,6 @@ package com.alibaba.alicloud.sms; import java.text.ParseException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.alibaba.alicloud.context.AliCloudProperties; import com.alibaba.alicloud.context.sms.SmsProperties; import com.alibaba.alicloud.sms.base.DefaultAlicomMessagePuller; @@ -34,6 +31,8 @@ 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 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 index 4cf87d7b..3a8cb837 100755 --- 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 @@ -25,14 +25,13 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledThreadPoolExecutor; -import org.apache.commons.lang3.concurrent.BasicThreadFactory; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - 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; /** * 阿里通信官方消息默认拉取工具类 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 index 70def740..0c0fd984 100755 --- 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 @@ -21,9 +21,6 @@ import java.util.TimeZone; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - import com.aliyun.mns.client.CloudAccount; import com.aliyun.mns.client.CloudQueue; import com.aliyun.mns.client.MNSClient; @@ -36,6 +33,8 @@ 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 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 index 08e75098..c71e7b90 100644 --- 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 @@ -15,12 +15,6 @@ */ package com.alibaba.alicloud.sms.config; -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; - import com.alibaba.alicloud.context.AliCloudProperties; import com.alibaba.alicloud.context.sms.SmsProperties; import com.alibaba.alicloud.sms.ISmsService; @@ -29,6 +23,12 @@ 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 */ 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 new file mode 100644 index 00000000..b066ed11 --- /dev/null +++ b/spring-cloud-starter-alibaba/spring-cloud-starter-alibaba-sidecar/pom.xml @@ -0,0 +1,22 @@ + + + + com.alibaba.cloud + spring-cloud-starter-alibaba + 2.0.1.BUILD-SNAPSHOT + ../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-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java b/spring-cloud-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java index 4895741c..ffb28a1c 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-starter-alibaba/spring-cloud-starter-bus-rocketmq/src/main/java/com/alibaba/cloud/bus/rocketmq/env/RocketMQBusEnvironmentPostProcessor.java @@ -1,12 +1,11 @@ /* - * Licensed to the Apache Software Foundation (ASF) under one or more - * contributor license agreements. See the NOTICE file distributed with - * this work for additional information regarding copyright ownership. - * The ASF licenses this file to You under the Apache License, Version 2.0 - * (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * Copyright (C) 2018 the original author or authors. * - * http://www.apache.org/licenses/LICENSE-2.0 + * Licensed under the Apache License, Version 2.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, diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java index 72c97420..e2a527dd 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderConstants.java @@ -16,8 +16,11 @@ package com.alibaba.cloud.stream.binder.rocketmq; +import static org.apache.rocketmq.spring.support.RocketMQHeaders.PREFIX; + /** * @author Jim + * @author Xiejiashuai */ public interface RocketMQBinderConstants { @@ -31,6 +34,11 @@ public interface RocketMQBinderConstants { */ String DEFAULT_NAME_SERVER = "127.0.0.1:9876"; - String DEFAULT_GROUP = "rocketmq_binder_default_group_name"; + String DEFAULT_GROUP = PREFIX + "binder_default_group_name"; + + /** + * RocketMQ re-consume times + */ + String ROCKETMQ_RECONSUME_TIMES = PREFIX + "RECONSUME_TIMES"; } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java index 673d3370..db982da6 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQBinderUtils.java @@ -16,11 +16,12 @@ package com.alibaba.cloud.stream.binder.rocketmq; -import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; -import org.springframework.util.StringUtils; - import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; +import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; + +import org.springframework.util.StringUtils; + /** * @author Jim */ diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java index 64409e7b..e1c14587 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQMessageChannelBinder.java @@ -16,9 +16,27 @@ package com.alibaba.cloud.stream.binder.rocketmq; +import java.util.Collection; +import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Set; +import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer; +import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQInboundChannelAdapter; +import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQMessageHandler; +import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQMessageSource; +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.RocketMQConsumerProperties; +import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQExtendedBindingProperties; +import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQProducerProperties; +import com.alibaba.cloud.stream.binder.rocketmq.provisioning.RocketMQTopicProvisioner; +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; import org.apache.rocketmq.client.producer.DefaultMQProducer; @@ -27,6 +45,7 @@ import org.apache.rocketmq.remoting.RPCHook; import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; 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.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedProducerProperties; @@ -42,19 +61,6 @@ import org.springframework.messaging.MessageHandler; import org.springframework.messaging.MessagingException; import org.springframework.util.StringUtils; -import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer; -import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQInboundChannelAdapter; -import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQMessageHandler; -import com.alibaba.cloud.stream.binder.rocketmq.integration.RocketMQMessageSource; -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.RocketMQConsumerProperties; -import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQExtendedBindingProperties; -import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQProducerProperties; -import com.alibaba.cloud.stream.binder.rocketmq.provisioning.RocketMQTopicProvisioner; - -import com.fasterxml.jackson.databind.ObjectMapper; - /** * @author Jim */ @@ -148,15 +154,19 @@ public class RocketMQMessageChannelBinder extends producer.setMaxMessageSize( producerProperties.getExtension().getMaxMessageSize()); rocketMQTemplate.setProducer(producer); + if (producerProperties.isPartitioned()) { + rocketMQTemplate + .setMessageQueueSelector(new PartitionMessageQueueSelector()); + } } RocketMQMessageHandler messageHandler = new RocketMQMessageHandler( rocketMQTemplate, destination.getName(), producerGroup, producerProperties.getExtension().getTransactional(), - instrumentationManager); + instrumentationManager, producerProperties); messageHandler.setBeanFactory(this.getApplicationContext().getBeanFactory()); messageHandler.setSync(producerProperties.getExtension().getSync()); - + messageHandler.setHeaderMapper(createHeaderMapper(producerProperties)); if (errorChannel != null) { messageHandler.setSendFailureChannel(errorChannel); } @@ -258,4 +268,27 @@ public class RocketMQMessageChannelBinder extends return topicInUse; } + private RocketMQHeaderMapper createHeaderMapper( + final ExtendedConsumerProperties extendedConsumerProperties) { + Set trustedPackages = extendedConsumerProperties.getExtension() + .getTrustedPackages(); + return createHeaderMapper(trustedPackages); + } + + private RocketMQHeaderMapper createHeaderMapper( + final ExtendedProducerProperties producerProperties) { + return createHeaderMapper(Collections.emptyList()); + } + + private RocketMQHeaderMapper createHeaderMapper(Collection trustedPackages) { + ObjectMapper objectMapper = this.getApplicationContext() + .getBeansOfType(ObjectMapper.class).values().iterator().next(); + JacksonRocketMQHeaderMapper headerMapper = new JacksonRocketMQHeaderMapper( + objectMapper); + if (!StringUtils.isEmpty(trustedPackages)) { + headerMapper.addTrustedPackages(trustedPackages); + } + return headerMapper; + } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java index c7539822..8c550459 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/actuator/RocketMQBinderHealthIndicator.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.stream.binder.rocketmq.actuator; +import com.alibaba.cloud.stream.binder.rocketmq.metrics.Instrumentation; +import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; + import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.actuate.health.AbstractHealthIndicator; import org.springframework.boot.actuate.health.Health; -import com.alibaba.cloud.stream.binder.rocketmq.metrics.Instrumentation; -import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; - /** * @author Timur Valiev * @author Jim diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java index 642eb731..1addfec0 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderAutoConfiguration.java @@ -16,20 +16,21 @@ package com.alibaba.cloud.stream.binder.rocketmq.config; -import org.apache.rocketmq.spring.autoconfigure.RocketMQAutoConfiguration; -import org.apache.rocketmq.spring.autoconfigure.RocketMQProperties; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.boot.context.properties.EnableConfigurationProperties; -import org.springframework.context.annotation.Bean; -import org.springframework.context.annotation.Configuration; -import org.springframework.context.annotation.Import; - import com.alibaba.cloud.stream.binder.rocketmq.RocketMQMessageChannelBinder; 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; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.context.properties.EnableConfigurationProperties; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.context.annotation.Import; + /** * @author Timur Valiev * @author Jim diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java index cdc3537a..c435b512 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQBinderHealthIndicatorAutoConfiguration.java @@ -16,13 +16,13 @@ package com.alibaba.cloud.stream.binder.rocketmq.config; +import com.alibaba.cloud.stream.binder.rocketmq.actuator.RocketMQBinderHealthIndicator; + import org.springframework.boot.actuate.endpoint.annotation.Endpoint; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; -import com.alibaba.cloud.stream.binder.rocketmq.actuator.RocketMQBinderHealthIndicator; - /** * @author Jim */ diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java index 33186962..318c98d8 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/config/RocketMQComponent4BinderAutoConfiguration.java @@ -16,6 +16,9 @@ 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; import org.apache.rocketmq.client.producer.DefaultMQProducer; @@ -24,6 +27,7 @@ import org.apache.rocketmq.spring.config.RocketMQConfigUtils; import org.apache.rocketmq.spring.config.RocketMQTransactionAnnotationProcessor; import org.apache.rocketmq.spring.config.TransactionHandlerRegistry; import org.apache.rocketmq.spring.core.RocketMQTemplate; + import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; @@ -32,10 +36,6 @@ import org.springframework.context.annotation.Configuration; import org.springframework.core.env.Environment; import org.springframework.util.StringUtils; -import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; - -import com.fasterxml.jackson.databind.ObjectMapper; - /** * @author Jim */ diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java index 1a11324f..05ee68df 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/consuming/RocketMQListenerBindingContainer.java @@ -19,6 +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.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; @@ -43,18 +48,25 @@ import org.apache.rocketmq.spring.support.RocketMQListenerContainer; import org.apache.rocketmq.spring.support.RocketMQUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.InitializingBean; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.context.SmartLifecycle; +import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -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 static com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants.ROCKETMQ_RECONSUME_TIMES; /** + * A class that Listen on rocketmq message. + *

+ * this class will delegate {@link RocketMQListener} to handle message + * * @author Jim + * @author Xiejiashuai + * @see RocketMQListener */ public class RocketMQListenerBindingContainer implements InitializingBean, RocketMQListenerContainer, SmartLifecycle { @@ -84,6 +96,8 @@ public class RocketMQListenerBindingContainer private RocketMQListener rocketMQListener; + private RocketMQHeaderMapper headerMapper; + private DefaultMQPushConsumer consumer; private boolean running; @@ -91,12 +105,16 @@ public class RocketMQListenerBindingContainer private final ExtendedConsumerProperties rocketMQConsumerProperties; private final RocketMQMessageChannelBinder rocketMQMessageChannelBinder; + private final RocketMQBinderConfigurationProperties rocketBinderConfigurationProperties; // The following properties came from RocketMQConsumerProperties. private ConsumeMode consumeMode; + private SelectorType selectorType; + private String selectorExpression; + private MessageModel messageModel; public RocketMQListenerBindingContainer( @@ -365,10 +383,35 @@ public class RocketMQListenerBindingContainer return messageModel; } + public RocketMQHeaderMapper getHeaderMapper() { + return headerMapper; + } + + public void setHeaderMapper(RocketMQHeaderMapper headerMapper) { + this.headerMapper = headerMapper; + } + + /** + * Convert rocketmq {@link MessageExt} to Spring {@link Message}. + * @param messageExt the rocketmq message + * @return the converted Spring {@link Message} + */ + @SuppressWarnings("unchecked") + private Message convertToSpringMessage(MessageExt messageExt) { + + // add reconsume-times header to messageExt + int reconsumeTimes = messageExt.getReconsumeTimes(); + messageExt.putUserProperty(ROCKETMQ_RECONSUME_TIMES, + String.valueOf(reconsumeTimes)); + Message message = RocketMQUtil.convertToSpringMessage(messageExt); + return MessageBuilder.fromMessage(message) + .copyHeaders(headerMapper.toHeaders(messageExt.getProperties())).build(); + } + public class DefaultMessageListenerConcurrently implements MessageListenerConcurrently { - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "Duplicates" }) @Override public ConsumeConcurrentlyStatus consumeMessage(List msgs, ConsumeConcurrentlyContext context) { @@ -376,10 +419,10 @@ public class RocketMQListenerBindingContainer log.debug("received msg: {}", messageExt); try { long now = System.currentTimeMillis(); - rocketMQListener - .onMessage(RocketMQUtil.convertToSpringMessage(messageExt)); + rocketMQListener.onMessage(convertToSpringMessage(messageExt)); long costTime = System.currentTimeMillis() - now; - log.debug("consume {} cost: {} ms", messageExt.getMsgId(), costTime); + log.debug("consume {} message key:[{}] cost: {} ms", + messageExt.getMsgId(), messageExt.getKeys(), costTime); } catch (Exception e) { log.warn("consume message failed. messageExt:{}", messageExt, e); @@ -390,11 +433,12 @@ public class RocketMQListenerBindingContainer return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; } + } public class DefaultMessageListenerOrderly implements MessageListenerOrderly { - @SuppressWarnings("unchecked") + @SuppressWarnings({ "unchecked", "Duplicates" }) @Override public ConsumeOrderlyStatus consumeMessage(List msgs, ConsumeOrderlyContext context) { @@ -402,10 +446,10 @@ public class RocketMQListenerBindingContainer log.debug("received msg: {}", messageExt); try { long now = System.currentTimeMillis(); - rocketMQListener - .onMessage(RocketMQUtil.convertToSpringMessage(messageExt)); + rocketMQListener.onMessage(convertToSpringMessage(messageExt)); long costTime = System.currentTimeMillis() - now; - log.info("consume {} cost: {} ms", messageExt.getMsgId(), costTime); + log.info("consume {} message key:[{}] cost: {} ms", + messageExt.getMsgId(), messageExt.getKeys(), costTime); } catch (Exception e) { log.warn("consume message failed. messageExt:{}", messageExt, e); @@ -417,6 +461,7 @@ public class RocketMQListenerBindingContainer return ConsumeOrderlyStatus.SUCCESS; } + } } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java index eeb8d3ef..bb1327d8 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQInboundChannelAdapter.java @@ -16,9 +16,15 @@ package com.alibaba.cloud.stream.binder.rocketmq.integration; +import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer; +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; + import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.integration.endpoint.MessageProducerSupport; import org.springframework.integration.support.MessageBuilder; @@ -31,11 +37,6 @@ import org.springframework.retry.RetryListener; import org.springframework.retry.support.RetryTemplate; import org.springframework.util.Assert; -import com.alibaba.cloud.stream.binder.rocketmq.consuming.RocketMQListenerBindingContainer; -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; - /** * @author Jim */ diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java index 6aa0e0fe..8ed0d417 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageHandler.java @@ -16,32 +16,41 @@ package com.alibaba.cloud.stream.binder.rocketmq.integration; +import java.util.List; +import java.util.Map; import java.util.Optional; +import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; +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; import org.apache.rocketmq.client.producer.SendStatus; import org.apache.rocketmq.common.message.MessageConst; +import org.apache.rocketmq.common.message.MessageQueue; import org.apache.rocketmq.spring.core.RocketMQTemplate; import org.apache.rocketmq.spring.support.RocketMQHeaders; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + +import org.springframework.cloud.stream.binder.BinderHeaders; +import org.springframework.cloud.stream.binder.ExtendedProducerProperties; import org.springframework.context.Lifecycle; import org.springframework.integration.handler.AbstractMessageHandler; import org.springframework.integration.support.DefaultErrorMessageStrategy; import org.springframework.integration.support.ErrorMessageStrategy; import org.springframework.integration.support.MessageBuilder; +import org.springframework.messaging.Message; import org.springframework.messaging.MessageChannel; import org.springframework.messaging.MessagingException; import org.springframework.messaging.support.ErrorMessage; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; -import com.alibaba.cloud.stream.binder.rocketmq.metrics.Instrumentation; -import com.alibaba.cloud.stream.binder.rocketmq.metrics.InstrumentationManager; - /** * @author Jim */ @@ -56,6 +65,8 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li private final RocketMQTemplate rocketMQTemplate; + private RocketMQHeaderMapper headerMapper; + private final Boolean transactional; private final String destination; @@ -68,14 +79,18 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li private volatile boolean running = false; + private ExtendedProducerProperties producerProperties; + public RocketMQMessageHandler(RocketMQTemplate rocketMQTemplate, String destination, String groupName, Boolean transactional, - InstrumentationManager instrumentationManager) { + InstrumentationManager instrumentationManager, + ExtendedProducerProperties producerProperties) { this.rocketMQTemplate = rocketMQTemplate; this.destination = destination; this.groupName = groupName; this.transactional = transactional; this.instrumentationManager = instrumentationManager; + this.producerProperties = producerProperties; } @Override @@ -97,6 +112,22 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li .build(), e); } } + if (producerProperties.isPartitioned()) { + try { + List messageQueues = rocketMQTemplate.getProducer() + .fetchPublishMessageQueues(destination); + if (producerProperties.getPartitionCount() != messageQueues.size()) { + logger.info(String.format( + "The partition count of topic '%s' will change from '%s' to '%s'", + destination, producerProperties.getPartitionCount(), + messageQueues.size())); + producerProperties.setPartitionCount(messageQueues.size()); + } + } + catch (MQClientException e) { + logger.error("fetch publish message queues fail", e); + } + } running = true; } @@ -117,6 +148,12 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li protected void handleMessageInternal(org.springframework.messaging.Message message) throws Exception { try { + // issue 737 fix + Map jsonHeaders = headerMapper + .fromHeaders(message.getHeaders()); + message = org.springframework.messaging.support.MessageBuilder + .fromMessage(message).copyHeaders(jsonHeaders).build(); + final StringBuilder topicWithTags = new StringBuilder(destination); String tags = Optional .ofNullable(message.getHeaders().get(RocketMQHeaders.TAGS)).orElse("") @@ -124,6 +161,7 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li if (!StringUtils.isEmpty(tags)) { topicWithTags.append(":").append(tags); } + SendResult sendRes = null; if (transactional) { sendRes = rocketMQTemplate.sendMessageInTransaction(groupName, @@ -146,36 +184,52 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li catch (Exception e) { // ignore } + boolean needSelectQueue = message.getHeaders() + .containsKey(BinderHeaders.PARTITION_HEADER); if (sync) { - sendRes = rocketMQTemplate.syncSend(topicWithTags.toString(), message, - rocketMQTemplate.getProducer().getSendMsgTimeout(), - delayLevel); + if (needSelectQueue) { + sendRes = rocketMQTemplate.syncSendOrderly( + topicWithTags.toString(), message, "", + rocketMQTemplate.getProducer().getSendMsgTimeout()); + } + else { + sendRes = rocketMQTemplate.syncSend(topicWithTags.toString(), + message, + rocketMQTemplate.getProducer().getSendMsgTimeout(), + delayLevel); + } log.debug("sync send to topic " + topicWithTags + " " + sendRes); } else { - rocketMQTemplate.asyncSend(topicWithTags.toString(), message, - new SendCallback() { - @Override - public void onSuccess(SendResult sendResult) { - log.debug("async send to topic " + topicWithTags + " " - + sendResult); - } + Message finalMessage = message; + SendCallback sendCallback = new SendCallback() { + @Override + public void onSuccess(SendResult sendResult) { + log.debug("async send to topic " + topicWithTags + " " + + sendResult); + } - @Override - public void onException(Throwable e) { - log.error( - "RocketMQ Message hasn't been sent. Caused by " - + e.getMessage()); - if (getSendFailureChannel() != null) { - getSendFailureChannel().send( - RocketMQMessageHandler.this.errorMessageStrategy - .buildErrorMessage( - new MessagingException( - message, e), - null)); - } - } - }); + @Override + public void onException(Throwable e) { + log.error("RocketMQ Message hasn't been sent. Caused by " + + e.getMessage()); + if (getSendFailureChannel() != null) { + getSendFailureChannel().send( + RocketMQMessageHandler.this.errorMessageStrategy + .buildErrorMessage(new MessagingException( + finalMessage, e), null)); + } + } + }; + if (needSelectQueue) { + rocketMQTemplate.asyncSendOrderly(topicWithTags.toString(), + message, "", sendCallback, + rocketMQTemplate.getProducer().getSendMsgTimeout()); + } + else { + rocketMQTemplate.asyncSend(topicWithTags.toString(), message, + sendCallback); + } } } if (sendRes != null && !sendRes.getSendStatus().equals(SendStatus.SEND_OK)) { @@ -230,4 +284,12 @@ public class RocketMQMessageHandler extends AbstractMessageHandler implements Li public void setSync(boolean sync) { this.sync = sync; } + + public RocketMQHeaderMapper getHeaderMapper() { + return headerMapper; + } + + 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-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java index 2855bf9c..1506a689 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/integration/RocketMQMessageSource.java @@ -19,6 +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.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; @@ -31,6 +35,7 @@ import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; import org.apache.rocketmq.spring.support.RocketMQUtil; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.springframework.beans.factory.DisposableBean; import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.context.Lifecycle; @@ -43,10 +48,6 @@ import org.springframework.messaging.Message; import org.springframework.util.Assert; import org.springframework.util.StringUtils; -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; - /** * @author Jim */ diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java index 4fda8c8f..e06a8690 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQBinderConfigurationProperties.java @@ -16,21 +16,26 @@ package com.alibaba.cloud.stream.binder.rocketmq.properties; -import org.apache.rocketmq.common.MixAll; -import org.springframework.boot.context.properties.ConfigurationProperties; +import javax.validation.constraints.Pattern; import com.alibaba.cloud.stream.binder.rocketmq.RocketMQBinderConstants; +import org.apache.rocketmq.common.MixAll; + +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; /** * @author Timur Valiev * @author Jim */ @ConfigurationProperties(prefix = "spring.cloud.stream.rocketmq.binder") +@Validated public class RocketMQBinderConfigurationProperties { /** * The name server for rocketMQ, formats: `host:port;host:port`. */ + @Pattern(regexp = "^[\\d.:;]+$", message = "nameServer needs to match expression \"host:port;host:port\"") private String nameServer = RocketMQBinderConstants.DEFAULT_NAME_SERVER; /** @@ -93,4 +98,5 @@ public class RocketMQBinderConfigurationProperties { public void setCustomizedTraceTopic(String customizedTraceTopic) { this.customizedTraceTopic = customizedTraceTopic; } + } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java index e78345b6..854c4f47 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/properties/RocketMQConsumerProperties.java @@ -16,8 +16,13 @@ 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; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly; import org.apache.rocketmq.common.protocol.heartbeat.MessageModel; @@ -51,7 +56,9 @@ public class RocketMQConsumerProperties { private Boolean orderly = false; /** - * for concurrently listener. message consume retry strategy + * for concurrently listener. message consume retry strategy. see + * {@link ConsumeConcurrentlyContext#delayLevelWhenNextConsume}. -1 means dlq(or + * discard, see {@link this#shouldRequeue}), others means requeue */ private int delayLevelWhenNextConsume = 0; @@ -62,6 +69,11 @@ public class RocketMQConsumerProperties { private Boolean enabled = true; + /** + * {@link JacksonRocketMQHeaderMapper#addTrustedPackages(String...)} + */ + private Set trustedPackages; + // ------------ For Pull Consumer ------------ private long pullTimeout = 10 * 1000; @@ -145,4 +157,12 @@ public class RocketMQConsumerProperties { public boolean shouldRequeue() { return delayLevelWhenNextConsume != -1; } + + public Set getTrustedPackages() { + return trustedPackages; + } + + public void setTrustedPackages(Set trustedPackages) { + this.trustedPackages = trustedPackages; + } } diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java index 95f0b5fb..c77867e2 100644 --- a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/RocketMQTopicProvisioner.java @@ -16,8 +16,12 @@ 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; + import org.springframework.cloud.stream.binder.ExtendedConsumerProperties; import org.springframework.cloud.stream.binder.ExtendedProducerProperties; import org.springframework.cloud.stream.provisioning.ConsumerDestination; @@ -25,9 +29,6 @@ import org.springframework.cloud.stream.provisioning.ProducerDestination; import org.springframework.cloud.stream.provisioning.ProvisioningException; import org.springframework.cloud.stream.provisioning.ProvisioningProvider; -import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQConsumerProperties; -import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQProducerProperties; - /** * @author Timur Valiev * @author Jim diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java new file mode 100644 index 00000000..effa183b --- /dev/null +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/provisioning/selector/PartitionMessageQueueSelector.java @@ -0,0 +1,55 @@ +/* + * Copyright 2013-2018 the original author or authors. + * + * Licensed under the Apache License, Version 2.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.provisioning.selector; + +import java.util.List; + +import org.apache.rocketmq.client.producer.MessageQueueSelector; +import org.apache.rocketmq.common.message.Message; +import org.apache.rocketmq.common.message.MessageQueue; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.cloud.stream.binder.BinderHeaders; + +/** + * @author wangxing + */ +public class PartitionMessageQueueSelector implements MessageQueueSelector { + + private static final Logger LOGGER = LoggerFactory + .getLogger(PartitionMessageQueueSelector.class); + + @Override + public MessageQueue select(List mqs, Message msg, Object arg) { + Integer partition = 0; + try { + partition = Math.abs( + Integer.parseInt(msg.getProperty(BinderHeaders.PARTITION_HEADER))); + if (partition >= mqs.size()) { + LOGGER.warn( + "the partition '{}' is greater than the number of queues '{}'.", + partition, mqs.size()); + partition = partition % mqs.size(); + } + } + catch (NumberFormatException ignored) { + } + return mqs.get(partition); + } + +} \ No newline at end of file diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java new file mode 100644 index 00000000..a2b0c013 --- /dev/null +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/AbstractRocketMQHeaderMapper.java @@ -0,0 +1,64 @@ +/* + * 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.stream.binder.rocketmq.support; + +import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; + +import org.apache.rocketmq.common.message.MessageConst; + +import org.springframework.messaging.MessageHeaders; +import org.springframework.util.Assert; + +/** + * Base for RocketMQ header mappers. + * + * @author caotc + * @since 2.0.1.RELEASE + */ +public abstract class AbstractRocketMQHeaderMapper implements RocketMQHeaderMapper { + private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8; + + private Charset charset; + + public AbstractRocketMQHeaderMapper() { + this(DEFAULT_CHARSET); + } + + public AbstractRocketMQHeaderMapper(Charset charset) { + Assert.notNull(charset, "'charset' cannot be null"); + this.charset = charset; + } + + protected boolean matches(String headerName) { + return !MessageConst.STRING_HASH_SET.contains(headerName) + && !MessageHeaders.ID.equals(headerName) + && !MessageHeaders.TIMESTAMP.equals(headerName) + && !MessageHeaders.CONTENT_TYPE.equals(headerName) + && !MessageHeaders.REPLY_CHANNEL.equals(headerName) + && !MessageHeaders.ERROR_CHANNEL.equals(headerName); + } + + public Charset getCharset() { + return charset; + } + + public void setCharset(Charset charset) { + 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-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java new file mode 100644 index 00000000..9be2a4d6 --- /dev/null +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/JacksonRocketMQHeaderMapper.java @@ -0,0 +1,286 @@ +/* + * 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.stream.binder.rocketmq.support; + +import java.io.IOException; +import java.nio.charset.Charset; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.springframework.lang.Nullable; +import org.springframework.messaging.MessageHeaders; +import org.springframework.util.ClassUtils; + +/** + * jackson header mapper for RocketMQ. Header types are added to a special header + * {@link #JSON_TYPES}. + * + * @author caotc + * @since 2.0.1.RELEASE + */ +public class JacksonRocketMQHeaderMapper extends AbstractRocketMQHeaderMapper { + + private final static Logger log = LoggerFactory + .getLogger(JacksonRocketMQHeaderMapper.class); + + private static final List DEFAULT_TRUSTED_PACKAGES = Arrays + .asList("java.lang", "java.net", "java.util", "org.springframework.util"); + + /** + * Header name for java types of other headers. + */ + public static final String JSON_TYPES = "spring_json_header_types"; + + private final ObjectMapper objectMapper; + private final Set trustedPackages = new LinkedHashSet<>( + DEFAULT_TRUSTED_PACKAGES); + + public JacksonRocketMQHeaderMapper(ObjectMapper objectMapper) { + this.objectMapper = objectMapper; + } + + public JacksonRocketMQHeaderMapper(Charset charset, ObjectMapper objectMapper) { + super(charset); + this.objectMapper = objectMapper; + } + + @Override + public Map fromHeaders(MessageHeaders headers) { + final Map target = new HashMap<>(); + final Map jsonHeaders = new HashMap<>(); + headers.forEach((key, value) -> { + if (matches(key)) { + if (value instanceof String) { + target.put(key, (String) value); + } + else { + try { + String className = value.getClass().getName(); + target.put(key, objectMapper.writeValueAsString(value)); + jsonHeaders.put(key, className); + } + catch (Exception e) { + log.debug("Could not map " + key + " with type " + + value.getClass().getName(), e); + } + } + } + }); + if (jsonHeaders.size() > 0) { + try { + target.put(JSON_TYPES, objectMapper.writeValueAsString(jsonHeaders)); + } + catch (IllegalStateException | JsonProcessingException e) { + log.error("Could not add json types header", e); + } + } + return target; + } + + @Override + public MessageHeaders toHeaders(Map source) { + final Map target = new HashMap<>(); + final Map jsonTypes = decodeJsonTypes(source); + source.forEach((key, value) -> { + if (matches(key) && !(key.equals(JSON_TYPES))) { + if (jsonTypes != null && jsonTypes.containsKey(key)) { + Class type = Object.class; + String requestedType = jsonTypes.get(key); + boolean trusted = trusted(requestedType); + if (trusted) { + try { + type = ClassUtils.forName(requestedType, null); + } + catch (Exception e) { + log.error("Could not load class for header: " + key, e); + } + } + + if (trusted) { + try { + Object val = decodeValue(value, type); + target.put(key, val); + } + catch (IOException e) { + log.error("Could not decode json type: " + value + + " for key: " + key, e); + target.put(key, value); + } + } + else { + target.put(key, new NonTrustedHeaderType(value, requestedType)); + } + } + else { + target.put(key, value); + } + } + }); + return new MessageHeaders(target); + } + + /** + * @param packagesToTrust the packages to trust. + * @see #addTrustedPackages(Collection) + */ + public void addTrustedPackages(String... packagesToTrust) { + if (Objects.nonNull(packagesToTrust)) { + addTrustedPackages(Arrays.asList(packagesToTrust)); + } + } + + /** + * Add packages to the trusted packages list (default {@code java.util, java.lang}) + * used when constructing objects from JSON. If any of the supplied packages is + * {@code "*"}, all packages are trusted. If a class for a non-trusted package is + * encountered, the header is returned to the application with value of type + * {@link NonTrustedHeaderType}. + * @param packagesToTrust the packages to trust. + */ + public void addTrustedPackages(Collection packagesToTrust) { + if (packagesToTrust != null) { + for (String whiteList : packagesToTrust) { + if ("*".equals(whiteList)) { + this.trustedPackages.clear(); + break; + } + else { + this.trustedPackages.add(whiteList); + } + } + } + } + + public Set getTrustedPackages() { + return this.trustedPackages; + } + + public ObjectMapper getObjectMapper() { + return objectMapper; + } + + private Object decodeValue(String jsonString, Class type) + throws IOException, LinkageError { + Object value = objectMapper.readValue(jsonString, type); + if (type.equals(NonTrustedHeaderType.class)) { + // Upstream NTHT propagated; may be trusted here... + NonTrustedHeaderType nth = (NonTrustedHeaderType) value; + if (trusted(nth.getUntrustedType())) { + try { + value = objectMapper.readValue(nth.getHeaderValue(), + ClassUtils.forName(nth.getUntrustedType(), null)); + } + catch (Exception e) { + log.error("Could not decode header: " + nth, e); + } + } + } + return value; + } + + @Nullable + private Map decodeJsonTypes(Map source) { + if (source.containsKey(JSON_TYPES)) { + String value = source.get(JSON_TYPES); + try { + return objectMapper.readValue(value, + new TypeReference>() { + }); + } + catch (IOException e) { + log.error("Could not decode json types: " + value, e); + } + } + return null; + } + + protected boolean trusted(String requestedType) { + if (requestedType.equals(NonTrustedHeaderType.class.getName())) { + return true; + } + if (!this.trustedPackages.isEmpty()) { + int lastDot = requestedType.lastIndexOf('.'); + if (lastDot < 0) { + return false; + } + String packageName = requestedType.substring(0, lastDot); + for (String trustedPackage : this.trustedPackages) { + if (packageName.equals(trustedPackage) + || packageName.startsWith(trustedPackage + ".")) { + return true; + } + } + return false; + } + return true; + } + + /** + * Represents a header that could not be decoded due to an untrusted type. + */ + public static class NonTrustedHeaderType { + + private String headerValue; + + private String untrustedType; + + public NonTrustedHeaderType() { + super(); + } + + NonTrustedHeaderType(String headerValue, String untrustedType) { + this.headerValue = headerValue; + this.untrustedType = untrustedType; + } + + public void setHeaderValue(String headerValue) { + this.headerValue = headerValue; + } + + public String getHeaderValue() { + return this.headerValue; + } + + public void setUntrustedType(String untrustedType) { + this.untrustedType = untrustedType; + } + + public String getUntrustedType() { + return this.untrustedType; + } + + @Override + public String toString() { + return "NonTrustedHeaderType [headerValue=" + headerValue + ", untrustedType=" + + this.untrustedType + "]"; + } + + } + +} diff --git a/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java new file mode 100644 index 00000000..c833dd1a --- /dev/null +++ b/spring-cloud-stream-binder-rocketmq/src/main/java/com/alibaba/cloud/stream/binder/rocketmq/support/RocketMQHeaderMapper.java @@ -0,0 +1,43 @@ +/* + * 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.stream.binder.rocketmq.support; + +import java.util.Map; + +import org.springframework.messaging.MessageHeaders; + +/** + * 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. + * @return the native target message. + */ + Map fromHeaders(MessageHeaders headers); + + /** + * Map from the given target message to abstracted {@link MessageHeaders}. + * @param source the native target message. + * @return the target headers. + */ + MessageHeaders toHeaders(Map source); +} diff --git a/spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java b/spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java index 842c630c..5930f0b9 100644 --- a/spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java +++ b/spring-cloud-stream-binder-rocketmq/src/test/java/com/alibaba/cloud/stream/binder/rocketmq/RocketMQAutoConfigurationTests.java @@ -16,16 +16,17 @@ package com.alibaba.cloud.stream.binder.rocketmq; -import static org.assertj.core.api.Assertions.assertThat; - -import org.junit.Test; -import org.springframework.boot.autoconfigure.AutoConfigurations; -import org.springframework.boot.test.context.runner.ApplicationContextRunner; - import com.alibaba.cloud.stream.binder.rocketmq.config.RocketMQBinderAutoConfiguration; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQBinderConfigurationProperties; import com.alibaba.cloud.stream.binder.rocketmq.properties.RocketMQExtendedBindingProperties; +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 Jim */