diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc index d1d1bea46..570c7b02d 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/acm.adoc @@ -6,7 +6,7 @@ Spring Cloud AliCloud ACM 是 Config Server 和 Client 的替代方案,客户 === 如何引入 Spring Cloud AliCloud ACM -Spring Cloud Alibaba 已经发布了 0.2.0.RELEASE 版本,需要首先导入依赖管理POM。 +Spring Cloud Alibaba 已经发布了 0.2.1.RELEASE 版本,需要首先导入依赖管理POM。 [source,xml] ---- @@ -15,7 +15,7 @@ Spring Cloud Alibaba 已经发布了 0.2.0.RELEASE 版本,需要首先导入 org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import 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 206381418..cf60b1ba8 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/ans.adoc @@ -4,7 +4,7 @@ ANS(Application Naming Service) 是隶属于阿里云 EDAS 产品的组件 === 如何引入 Spring Cloud AliCloud ANS -Spring Cloud Alibaba 已经发布了 0.2.0.RELEASE 版本,需要首先导入依赖管理 POM。 +Spring Cloud Alibaba 已经发布了 0.2.1.RELEASE 版本,需要首先导入依赖管理 POM。 [source,xml] ---- @@ -13,7 +13,7 @@ Spring Cloud Alibaba 已经发布了 0.2.0.RELEASE 版本,需要首先导入 org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc index dbf8f1613..a85c14c2f 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/nacos-config.adoc @@ -51,7 +51,7 @@ NOTE: 注意dataid是以 properties(默认的文件扩展名方式)为扩展名 org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import 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 70899a8a2..aa088d4d2 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 @@ -22,7 +22,7 @@ pom.xml 示例如下所示: org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import @@ -84,7 +84,7 @@ Spring Cloud 的 Finchley.SR1 版本最佳实践的 Spring Boot 版本是 2.0.6. org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/oss.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/oss.adoc index 40317202a..11539d0b7 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc-zh/oss.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc-zh/oss.adoc @@ -13,7 +13,7 @@ Spring Cloud Alibaba 已经发布了0.2.0版本,需要首先导入依赖管理 org.springframework.cloud spring-cloud-alibaba-dependencies - 0.2.0.RELEASE + 0.2.1.RELEASE pom import diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/acm.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/acm.adoc index acd5795c5..f488a8022 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/acm.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/acm.adoc @@ -1 +1,185 @@ == Spring Cloud Alibaba Cloud ACM + +Spring Cloud Alibaba Cloud ACM is an implementation of the commercial product Application Configuration Management(ACM) in the client side of Spring Cloud, and is free of charge. + +Spring Cloud Alibaba Cloud ACM is an alternative solution for Config Server and Client. The concepts on the client and server have the same abstractions with Spring Environment and PropertySource. In special Bootstrap phases, configurations are loaded to the Spring environment. During the application lifecycle from development, deployment, test to production, you can manage the configurations across all the environments, and make sure that all information required for application migration is ready when needed. + +=== How to Introduce Spring Cloud Alibaba Cloud ACM + +We’ve released Spring Cloud Alibaba version 0.2.1. You will need to add dependency management POM first. + +[source,xml] +---- + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + +---- + +Next we need to introduce Spring Cloud Alibaba Cloud ACM Starter. + +[source,xml] +---- + + org.springframework.cloud + spring-cloud-starter-alicloud-acm + +---- + +=== Use ACM to Manage Configurations + +When Spring Cloud Alibaba Cloud ACM Starter is introduced into the client, the application will automatically get configuration information from the configuration management server when it starts, and inject the configuration into Spring Environment. + +The following is a simple illustration. + +[source,java] +---- +@SpringBootApplication +public class ProviderApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args); + String userName = applicationContext.getEnvironment().getProperty("user.name"); + String userAge = applicationContext.getEnvironment().getProperty("user.age"); + System.err.println("user name :" +userName+"; age: "+userAge); + } +} +---- + +As we need to obtain configuration information from the configuration server, we will need to configure the address of the server. We also need to add the following information in bootstrap.properties. + +[source,properties] +---- +# Required. The application name will be used as part of the keyword to get the configuration key from the server. +spring.application.name=acm-config +server.port=18081 +# The following is the IP and port number of the configuration server. +spring.cloud.alicloud.acm.server-list=127.0.0.1 +spring.cloud.alicloud.acm.server-port=8080 +---- + +NOTE: By now the configuration center is not started yet, so you will get an error message if your application is started. Therefore, start the configuration center before you start your application. + + +=== Start Configuration Center + +ACM uses two types of configuration centers. One is a lightweight configuration center which is totally free, the other is ACM which is used on Alibaba Cloud. Generally, you can use the lightweight version for application development and local testing, and use ACM for canary deployment or production. + +==== Start Lightweight Configuration Center + +Refer to the https://help.aliyun.com/document_detail/44163.html[Configure Lightweight Configuration Center] for details about how to download and install lightweight configuration center. + +NOTE: You only need to perform step 1(Download lightweight configuration center) and step 2(Start lightweight configuration center). Step 3(Configure hosts) is not required if you use ACM at the same time. + + +==== Use ACM on the Cloud + +Using ACM on the cloud saves you from the tedious work of server maintenance while at the same time provides a better stability. There is no difference at the code level between using ACM on cloud and lightweight configuration center, but there are some differences in configurations. + +The following is a simple sample of using ACM. You can view configuration details on https://acm.console.aliyun.com[ACM Console] + +[source,properties] +---- +# The application name will be used as part of the keyword to obtain configuration key from the server, and is mandatory. +spring.application.name=ans-provider +# Configure your own port number +server.port=18081 +# The following is the IP and port number of the configuration center. +spring.cloud.alicloud.acm.server-mode=EDAS +spring.cloud.alicloud.access-key=Your Alibaba Cloud AK +spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK +spring.cloud.alicloud.acm.endpoint=acm.aliyun.com +spring.cloud.alicloud.acm.namespace=Your ACM namespace(You can find the namespace on the ACM console) +---- + +NOTE: EDAS provides application hosting service and will fill in all configurations automatically for the hosted applications. + +=== Add Configuration in the Configuration Center + +1. After you start the lightweight configuration center, add the following configuration on the console. + +[source,subs="normal"] +---- +Group: DEFAULT_GROOUP + +DataId: acm-config.properties + +Content: user.name=james + user.age=18 +---- + +NOTE: The format of dataId is `{prefix}. {file-extension}`. “prefix” is obtained from spring.application.name by default, and the value of “file-extension” is "properties” by default. + +=== Start Application Verification + +Start the following example and you can see that the value printed on the console is the value we configured in the lightweight configuration center. + +[source,subs="normal"] +---- +user name :james; age: 18 +---- + +=== Modify Configuration File Extension + +The default file extension of dataId in spring-cloud-starter-alicloud-acm is properties. In addition to properties, yaml is also supported. +You can set the file extension using spring.cloud.nacos.config.file-extension. Just set it to `yaml` or `yml`for yaml format. + +NOTE: After you change the file extension, you need to make corresponding format changes in the DataID and content of the configuration center. + +=== Dynamic Configuration Updates + +spring-cloud-starter-alicloud-acm supports dynamic configuration updates. Context Refresh in Spring is triggered when you update configuration in the configuration center. +All classes with @RefreshScope and @ConfigurationProperties annotations will be refershed automatically. + +NOTE: You can disable automatic refresh by this setting: spring.cloud.nacos.config.refresh.enabled=false + +=== Configure Profile Granularity + +When configuration is loaded by spring-cloud-starter-alicloud-acm, configuration with dataid {spring.application.name}. {file-extension} will be loaded first. If there is content in spring.profiles.active, the content of spring.profile, and configuration with the dataid format of{spring.application.name}-{profile}. {file-extension} will also be loaded in turn, and the latter has higher priority. + +spring.profiles.active is the configuration metadata, and should also be configured in bootstrap.properties or bootstrap.yaml. For example, you can add the following content in bootstrap.properties. + +[sources,properties] +---- +spring.profiles.active={profile-name} +---- + +Note: You can also configure the granularity through JVM parameters such as -Dspring.profiles.active=develop or --spring.profiles.active=develop, which have higher priority. Just follow the specifications of Spring Boot. + + + +=== Support Custom Group Configurations + +DEFAULT_GROUP is used by default when no `{spring.cloud.nacos.config.group}` configuration is defined. If you need to define your own group, you can use the following method: + +[source,properties] +---- +spring.cloud.nacos.config.group=DEVELOP_GROUP +---- + +NOTE: This configuration must be placed in the bootstrap.properties file, and the value of Group must be the same with the value of `spring.cloud.nacos.config.group`. + +==== Support Shared Configurations + +ACM provides a solution to share the same configuration across multiple applications. You can do this by adding the `spring.application.group` configuration in Bootstrap. + +[source,properties] +---- +spring.application.group=company.department.team +---- + +Then, you application will retrieve configurations from the following DataId in turn before it retrieves its own configuration: company:application.properties, company.department:application.properties, company.department.team:application.properties。 +After that, it also retrieves configuration from {spring.application.group}: {spring.application.name}. {file-extension} +The later in order, the higer the priority, and the unique configuration of the application itself has the highest priority. + + +NOTE: The default suffix of DataId is properties, and you can change it using spring.cloud.nacos.config.file-extension. `{spring.application.group}: {spring.application.name}. {file-extension}` 。 + +NOTE: If you configured `spring.profiles.active` , then the DataId format of `{spring.application.group}: {spring.application.name}-{spring.profiles.active}. {file-extension}` is also supported, and has higher priority than `{spring.application.group}: {spring.application.name}. {file-extension}` diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc index 7f5c95a03..2aec5ed4a 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/ans.adoc @@ -1 +1,111 @@ == Spring Cloud Alibaba Cloud ANS + +ANS(Application Naming Service) is a component of EDAS. Spring Cloud Alibaba Cloud ANS provides the commercial version of service registration and discovery in conformity with the Spring Cloud specifications, so that you can develop your applications locally and run them on the cloud. + +=== How to Introduce Spring Cloud Alibaba Cloud ANS + +We’ve released Spring Cloud Alibaba version 0.2.1. You will need to add dependency management POM first. + +[source,xml] +---- + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + +---- + +Next we need to introduce Spring Cloud AliCloud ANS Starter. + +[source,xml] +---- + + org.springframework.cloud + spring-cloud-starter-alicloud-ans + +---- + +=== Use ANS to Register Service + +When Spring Cloud AliCloud ANS Starter is introduced on the client, the metadata of the service such as IP, port number and weright will be registered to the registration center automatically. The client will maintain heartbeat with the server to prove that it is capable of providing service properly. + +The following is a simple illustration. + +[source,java] +---- +@SpringBootApplication +@EnableDiscoveryClient +@RestController +public class ProviderApplication { + + @RequestMapping("/") + public String home() { + return "Hello world"; + } + + public static void main(String[] args) { + SpringApplication.run(ProviderApplication.class, args); + } + +} +---- + +As the service will registered to the registration center, we will need to configure the address of the registration center. We also need to add the following address in application.properties. + +[source,properties] +---- +# The application name will be used as the service name, therefore it is mandatory. +spring.application.name=ans-provider +server.port=18081 +# The following is the IP and port number of the registration center. +spring.cloud.alicloud.ans.server-list=127.0.0.1 +spring.cloud.alicloud.ans.server-port=8080 +---- + +NOTE: By now the registration center is not started yet, so you will get an error message if your application is started. Therefore, start the registration center before you start your application. + +=== Start Registration Center + +ANS uses two types of registration centers. One is the free lightweight configuration center and the other is the registration center on cloud, which is provided through EDAS. Generally, you can use the lightweight version for application development and local testing, and use EDAS for canary deployment or production. + +==== Start Lightweight Configuration Center + +Refer to the https://help.aliyun.com/document_detail/44163.html[Configure Lightweight Configuration Center] for details about how to download and install lightweight configuration center. + +NOTE: You only need to perform step 1(Download lightweight configuration center) and step 2(Start lightweight configuration center). Step 3(Configure hosts) is not required if you use ANS at the same time. + +After you start the lightweight configuration center, start ProviderApplication directly, and you will be able to register your service to the configuration center. The default port of the lightweight configuration center is 8080, therefore you can open http://127.0.0.1:8080, click “Services” on the left and see the registered service. + +==== User Registration Center on the Cloud + +Using the registration center on the cloud saves you from the tedious work of server maintenance while at the same time provides a better stability. There is no difference at the code level between using the registration center on cloud and lightweight configuration center, but there are some differences in configurations. + +The following is a simple sample of using the registration center on the cloud. + +[source,properties] +---- +# The application name will be used the service name, and is therefore mandatory. +spring.application.name=ans-provider +# Configure your own port number +server.port=18081 +# The following is the IP and port number of the configuration center. The default value is 127.0.0.1 and 8080, so the following lines can be omitted. +spring.cloud.alicloud.ans.server-mode=EDAS +spring.cloud.alicloud.access-key=Your Alibaba Cloud AK +spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK +spring.cloud.alicloud.edas.namespace=cn-xxxxx +---- + +The default value of server-mode is LOCAL. If you want to use the registration center on cloud, you need to change it to EDAS. + +Access-key and secret-key are the AK/SK of your Alibaba Cloud account. Register an Alibaba Cloud account first and log on to the Cloud Console https://usercenter.console.aliyun.com/#/manage/ak[Alibaba Cloud AK/SK] to copy your AccessKey ID and Access Key Secret. If you haven’t created one, click the “Create AccessKey” button. + +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/dependency-management.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc index 1c1640c1c..310e56c3c 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/dependency-management.adoc @@ -2,3 +2,32 @@ The Spring Cloud Alibaba Bill of Materials (BOM) contains the versions of all the dependencies it uses. +Version 0.2.1.RELEASE is compatible with the Spring Cloud Finchley. Version 0.1.1.RELEASE is compatible with the Spring Cloud Edgware. + +These artifacts are available from Maven Central and Spring Release repository via BOM: + + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + +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 + + + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-config.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-config.adoc index e933cff8c..5f42987b4 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-config.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-config.adoc @@ -1 +1,362 @@ == Spring Cloud Alibaba Nacos Config + +Nacos provides key/value storage of configurations and other metadata as well as server and client support for externalized configurations in distributed systems. With Spring Cloud Alibaba Nacos Config, you can manage externalized configurations of your Spring Cloud applications in the Nacos Server. + +Spring Cloud Alibaba Nacos Config is an alternative solution for Config Server and Client. The concepts on the client and server have the same abstractions with Spring Environment and PropertySource. In special Bootstrap phases, configurations are loaded to the Spring environment. During the application lifecycle from development, deployment, test to production, you can manage the configurations across all the environments, and make sure that all information required for application migration is ready when needed. + +=== Quickstart + +===== Initialize Nacos Server + +1. Start Nacos Server. Refer to https://nacos.io/zh-cn/docs/quick-start.html[Nacos Documentation] for details about how to start the Nacos server. + +2. Add the following configurations in Nacos: + +[source,subs="normal"] +---- +Data ID: nacos-config.properties + +Group : DEFAULT_GROUP + +Configuration format: Properties + +Configuration content: user.name=nacos-config-properties + user.age=90 +---- + +NOTE: The default file extension of dataid is properties. + +===== Usage on the Client + +To use Nacos to manage externalized configurations for your applications, you need to add a Spring Boot Starter while building your application: org.springframework.cloud:spring-cloud-starter-alibaba-nacos-config The following is a basic configuration of maven dependency: + +[source,xml] +---- + + org.springframework.boot + spring-boot-starter-parent + 2.0.5.RELEASE + + + + + + + org.springframework.cloud + spring-cloud-dependencies + Finchley.SR1 + pom + import + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + + + + + org.springframework.cloud + spring-cloud-starter-alibaba-nacos-config + + + org.springframework.boot + spring-boot-starter + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + +---- + +Now we can create a standard Spring Boot application. + +[source,java] +---- +@SpringBootApplication +public class ProviderApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args); + String userName = applicationContext.getEnvironment().getProperty("user.name"); + String userAge = applicationContext.getEnvironment().getProperty("user.age"); + System.err.println("user name :" +userName+"; age: "+userAge); + } +} +---- + +Before running this example, we need to configure the address of the Nacos server in bootstrap.properties. For example: + +.bootstrap.properties +[source,properties] +---- +spring.application.name=nacos-config +spring.cloud.nacos.config.server-addr=127.0.0.1:8848 +---- + +NOTE: If you use domain name to access Nacos, the format of `spring.cloud.nacos.config.server-addr` should be `Domain name:port`. +For example, if the Nacos domain name is abc.com.nacos, and the listerner port is 80, then the configuration should be `spring.cloud.nacos.config.server-addr=abc.com.nacos:80`. +Port 80 cannot be omitted. + +Run this example and you can see the following output: + +[source,subs="normal"] +---- +2018-11-02 14:24:51.638 INFO 32700 --- [main] c.a.demo.provider.ProviderApplication : Started ProviderApplication in 14.645 seconds (JVM running for 15.139) +user name :nacos-config-properties; age: 90 +2018-11-02 14:24:51.688 INFO 32700 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@a8c5e74: startup date [Fri Nov 02 14:24:51 CST 2018]; root of context hierarchy +2018-11 +---- + +=== Add Configurations with DataId in YAML Format + +spring-cloud-starter-alibaba-nacos-config supports yaml format as well. You only need to complete the following 2 steps. + +1. In the bootstrap.properties file, add the following line to claim that the format of dataid is yaml. As follows: + +.bootstrap.properties +[source,yaml] +---- +spring.cloud.nacos.config.file-extension=yaml +---- + +2. Add a configuration with the dataId in yaml format on the Nacos console, as shown below: + +[source,subs="normal"] +---- +Data ID: nacos-config.yaml + +Group : DEFAULT_GROUP + +Configuration format: YAML + +Configuration content: user.name: nacos-config-yaml + user.age: 68 +---- + +After completing the preivous two steps, restart the testing program and you will see the following result. + +[source,subs="normal"] +---- +2018-11-02 14:59:00.484 INFO 32928 --- [main] c.a.demo.provider.ProviderApplication:Started ProviderApplication in 14.183 seconds (JVM running for 14.671) +user name :nacos-config-yaml; age: 68 +2018-11-02 14:59:00.529 INFO 32928 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@265a478e: startup date [Fri Nov 02 14:59:00 CST 2018]; root of context hierarchy +---- + +=== Support Dynamic Configuration Udpates + +spring-cloud-starter-alibaba-nacos-config also supports dynamic configuration updates. The code for starting Spring Boot application testing is as follows: + +[source,java] +---- +@SpringBootApplication +public class ProviderApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args); + while(true) { + //When configurations are refreshed dynamically, they will be updated in the Enviroment, therefore here we retrieve configurations from Environment every other second. + String userName = applicationContext.getEnvironment().getProperty("user.name"); + String userAge = applicationContext.getEnvironment().getProperty("user.age"); + System.err.println("user name :" + userName + "; age: " + userAge); + TimeUnit.SECONDS.sleep(1); + } + } +} +---- + +When user.name is changed, the latest value can be retrieved from the application, as shown below: + +[source,subs="normal"] +---- +user name :nacos-config-yaml; age: 68 +user name :nacos-config-yaml; age: 68 +user name :nacos-config-yaml; age: 68 +2018-11-02 15:04:25.069 INFO 32957 --- [-127.0.0.1:8848] o.s.boot.SpringApplication : Started application in 0.144 seconds (JVM running for 71.752) +2018-11-02 15:04:25.070 INFO 32957 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@10c89124: startup date [Fri Nov 02 15:04:25 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@6520af7 +2018-11-02 15:04:25.071 INFO 32957 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6520af7: startup date [Fri Nov 02 15:04:24 CST 2018]; root of context hierarchy +//Read the updated value from Enviroment +user name :nacos-config-yaml-update; age: 68 +user name :nacos-config-yaml-update; age: 68 +---- + +NOTE: You can disable automatic refresh with this setting`spring.cloud.nacos.config.refresh.enabled=false`. + +=== Support configurations at the profile level + +When configurations are loaded by spring-cloud-starter-alibaba-nacos-config, basic configurations with dataid of `${spring.application.name}. ${file-extension:properties}` , and dataid of `${spring.application.name}-${profile}. ${file-extension:properties}` are also loaded. If you need to use different configurations from different environments, you can use the `${spring.profiles.active}` configuration provided by Spring. + +[source,properties] +---- +spring.profiles.active=develop +---- + +NOTE: When specified in configuration files, ${spring.profiles.active} must be placed in bootstrap.properties. + +Add a basic configuration in Nacos, with a dataid of nacos-config-develop.yaml, as shown below: + +[source,subs="normal"] +---- +Data ID: nacos-config-develop.yaml + +Group : DEFAULT_GROUP + +Configuration format: YAML + +Configuration content: current.env: develop-env +---- + +Run the following Spring Boot application testing code: + +[source,java] +---- +@SpringBootApplication +public class ProviderApplication { + + public static void main(String[] args) { + ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args); + while(true) { + String userName = applicationContext.getEnvironment().getProperty("user.name"); + String userAge = applicationContext.getEnvironment().getProperty("user.age"); + //Get the current deployment environment + String currentEnv = applicationContext.getEnvironment().getProperty("current.env"); + System.err.println("in "+currentEnv+" enviroment; "+"user name :" + userName + "; age: " + userAge); + TimeUnit.SECONDS.sleep(1); + } + } +} +---- +After started, you can see the output as follows in the console: + +[source,subs="normal"] +---- +in develop-env enviroment; user name :nacos-config-yaml-update; age: 68 +2018-11-02 15:34:25.013 INFO 33014 --- [ Thread-11] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6f1c29b7: startup date [Fri Nov 02 15:33:57 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@63355449 +---- + +To switch to the production environment, you only need to change the parameter of `${spring.profiles.active}`. As show below: + +[source,properties] +---- +spring.profiles.active=product +---- + +At the same time, add the basic configuration with the dataid in the Nacos of your production environment. For example, you can add the configuration with the dataid of nacos-config-product.yaml in Nacos of your production environment: + +[source,subs="normal"] +---- +Data ID: nacos-config-product.yaml + +Group : DEFAULT_GROUP + +Configuration format: YAML + +Configuration content: current.env: product-env +---- + +Start the testing program and you will see the following result: + +[source,subs="normal"] +---- +in product-env enviroment; user name :nacos-config-yaml-update; age: 68 +2018-11-02 15:42:14.628 INFO 33024 --- [Thread-11] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aa8e115: startup date [Fri Nov 02 15:42:03 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@19bb07ed +---- + + +NOTE: In this example, we coded the configuration in the configuration file by using the `spring.profiles.active=` method. In real scenarios, this variable needs to be different in different environment. You can use the `-Dspring.profiles.active=` parameter to specify the configuration so that you can switch between different environments easily. + +=== Support Custom Namespaces +For details about namespaces in Nacos, refer to https://nacos.io/zh-cn/docs/concepts.html[Nacos Concepts] + +[quote] +Namespaces are used to isolate configurations for different tenants. Groups and Data IDs can be the same across different namespaces. Typical scenarios of namespaces is the isolation of configurations for different environments, for example, isolation between development/testing environments and production environments(configurations and services and so on). + +The “Public” namespace of Nacos is used if no namespace is specified in `${spring.cloud.nacos.config.namespace}`. You can also specify a custom namespace in the following way: +[source,properties] +---- +spring.cloud.nacos.config.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7 +---- + +NOTE: This configuration must be in the bootstrap.properties file. The value of `spring.cloud.nacos.config.namespace` is the id of the namespace, and the value of id can be retrieved from the Nacos console. Do not select other namespaces when adding configurations. Otherwise configurations cannot be retrieved properly. + +=== Support Custom Groups + +DEFAULT_GROUP is used by default when no `{spring.cloud.nacos.config.group}` configuration is defined. If you need to define your own group, you can define it in the following property: + +[source,properties] +---- +spring.cloud.nacos.config.group=DEVELOP_GROUP +---- + +NOTE: This configuration must be in the bootstrap.properties file, and the value of Group must be the same with the value of `spring.cloud.nacos.config.group`. + +=== Support Custom Data Id + +As of Spring Cloud Alibaba Nacos Config, data id can be self-defined. For detailed design of this part, refer to https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/141[Github issue]. +The following is a complete sample: + +[source,properties] +---- +spring.application.name=opensource-service-provider +spring.cloud.nacos.config.server-addr=127.0.0.1:8848 + +# config external configuration +# 1. Data Id is in the default group of DEFAULT_GROUP, and dynamic refresh of configurations is not supported. +spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties + +# 2. Data Id is not in the default group, and dynamic refresh of configurations is not supported. +spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties +spring.cloud.nacos.config.ext-config[1].group=GLOBALE_GROUP + +# 3. Data Id is not in the default group and dynamic referesh of configurations is supported. +spring.cloud.nacos.config.ext-config[2].data-id=ext-config-common03.properties +spring.cloud.nacos.config.ext-config[2].group=REFRESH_GROUP +spring.cloud.nacos.config.ext-config[2].refresh=true +---- + +We can see that: + +* Support multiple data ids by configuring `spring.cloud.nacos.config.ext-config[n].data-id`. +* Customize the group of data id by configuring `spring.cloud.nacos.config.ext-config[n].group`. If not specified, DEFAULT_GROUP is used. +* Control whether this data id supports dynamic refresh of configurations is supported when configurations are changed by configuring `spring.cloud.nacos.config.ext-config[n].refresh`. + It’s not supported by default. + + +NOTE: When multiple Data Ids are configured at the same time, the priority is defined by the value of “n” in `spring.cloud.nacos.config.ext-config[n].data-id`. The bigger the value, the higher the priority. + +NOTE: The value of `spring.cloud.nacos.config.ext-config[n].data-id` must have a file extension, and it could be properties or yaml/yml. +The setting in `spring.cloud.nacos.config.file-extension` does not have any impact on the custom Data Id file extension. + +The configuration of custom Data Id allows the sharing of configurations among multiple applications, and also enables support of multiple configurations for one application. + +To share the data id among multiple applications in a clearer manner, you can also use the following method: + +[source,properties] +---- +spring.cloud.nacos.config.shared-dataids=bootstrap-common.properties,all-common.properties +spring.cloud.nacos.config.refreshable-dataids=bootstrap-common.properties +---- + +We can see that: + +* Multiple shared data ids can be configured using `spring.cloud.nacos.config.shared-dataids` , and the data ids are separted by commas. +* `spring.cloud.nacos.config.refreshable-dataids` is used to control which data ids will be refreshed dynamically when configurations are updated, and that the latest configuration values can be retrieved by applications. Data ids are separated with commas. + If not specified, all shared data ids will not be dynamically refreshed. + +NOTE: When using `spring.cloud.nacos.config.shared-dataids` to configure multiple shared data ids, +we agree on the following priority between the shared configurations: Priorities are decided based on the order in which the configurations appear. The one that occurs later is higher in priority than the one that appears first. + +NOTE: When using `spring.cloud.nacos.config.shared-dataids`, the data Id must have a file extension, and it could be properties or yaml/yml. +And the configuration in `spring.cloud.nacos.config.file-extension` does not have any impact on the customized Data Id file extension. + +NOTE: When `spring.cloud.nacos.config.refreshable-dataids` specifies the data ids that support dynamic refresh, the corresponding values of the data ids should also specify file extensions. \ No newline at end of file diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-discovery.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-discovery.adoc index 21a1177bf..16a3ca383 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-discovery.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/nacos-discovery.adoc @@ -1 +1,317 @@ == Spring Cloud Alibaba Nacos Discovery + +This project provides seamless integration with Nacos for Spring Boot applications in terms of service registration and discovery through automatic configurations and other standard usages of the Spring programming model. +Nacos has endured the tough tests of the Double 11 Shopping festivals for years. By adding a few simple annotations, you can register a service quickly and use Nacos as the service registration center for a large scale distributed system. + +=== Service Registration and Discovery: Nacos Discovery Starter + +Service discovery is one of the key components in the microservices architecture. In such a architecture, configuring a service list for every client manually could be a daunting task, and makes dynamic scaling extremely difficult. + Nacos Discovery Starter helps you to register your service to the Nacos server automatically, and the Nacos server keeps track of the services and refreshes the service list dynamically. In addition, Nacos +Discovery Starter registers some of the metadata of the service instance, such as host, port, health check URL, homepage to Nacos. For details about how to download and start Nacos, refer to the https://nacos.io/zh-cn/docs/quick-start.html[Nacos Website]。 + +==== How to Introduce Nacos Discovery Starter + +To introduce Nacos Discovey Starter into your project, use the group ID of `org.springframework.cloud` and the artifact ID of `spring-cloud-starter-alibaba-nacos-discovery`. +pom.xml sample: + +[source,xml,indent=0] +---- + + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + + + + + + org.springframework.cloud + spring-cloud-starter-alibaba-nacos-discovery + + +---- + +==== Start a Provider Application + +If you use the Finchley.SR1 version of Spring Cloud , then you will need to be very cautious when selecting the Spring Boot version, because the version incompatibility might lead to many unexpected results. +The best practice for Spring Cloud Finchley.SR1 is to use the 2.0.6 release of Spring Boot. When starting a provider application, please also check if your Spring Boot version is +1.X.Y.RELEASE or 2.1.0.RELEASE. If not, please change it to 2.0.6.RELEASE. + +The following sample illustrates how to register a service to Nacos. + +1. Configuration of pom.xml The following is a complete example of pom.xml: +[source, xml] +---- + + + 4.0.0 + + open.source.test + nacos-discovery-test + 1.0-SNAPSHOT + nacos-discovery-test + + + org.springframework.boot + spring-boot-starter-parent + 2.0.6.RELEASE + + + + + UTF-8 + UTF-8 + 1.8 + + + + + + org.springframework.cloud + spring-cloud-dependencies + Finchley.SR1 + pom + import + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-web + + + + org.springframework.boot + spring-boot-starter-actuator + + + + org.springframework.cloud + spring-cloud-starter-alibaba-nacos-discovery + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + +---- + +2. Configuration of application.properties Some of the basic configurations of Nacos must be included in application.properties(or application.yaml), as shown below: +application.properties +[source,properties] +---- +server.port=8081 +spring.application.name=nacos-producer +spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 +management.endpoints.web.exposure.include=* +---- + + +NOTE: If you do not want to use Nacos for service registration and discovery, you can set `spring.cloud.nacos.discovery` to `false`. + +3. The following is a sample for starting Provider: +[source,java,indent=0] +---- +@SpringBootApplication +@EnableDiscoveryClient +public class NacosProviderDemoApplication { + + public static void main(String[] args) { + SpringApplication.run(NacosProducerDemoApplication.class, args); + } + + @RestController + public class EchoController { + @GetMapping(value = "/echo/{string}") + public String echo(@PathVariable String string) { + return "Hello Nacos Discovery " + string; + } + } +} +---- + +Now you can see the registered services on the Nacos console. + +NOTE: Before you start the provider application, please start Nacos first. Refer to https://nacos.io/zh-cn/docs/quick-start.html[Naco Website] for more details. + +=== Service EndPoint + +spring-cloud-starter-alibaba-nacos-discovery provides an EndPoint, and the address is `http://ip:port/actuator/nacos-discovery`. +The EndPoint mainly provides two types of information: + + 1. Subscribe: Shows the current service subscribers + 2. NacosDiscoveryProperties: Shows the current basic Nacos configurations of the current service + +The followings shows how a service instance accesses the EndPoint: + +[source, json] +---- +{ + "subscribe": [ + { + "jsonFromServer": "", + "name": "nacos-provider", + "clusters": "", + "cacheMillis": 10000, + "hosts": [ + { + "instanceId": "30.5.124.156#8081#DEFAULT#nacos-provider", + "ip": "30.5.124.156", + "port": 8081, + "weight": 1.0, + "healthy": true, + "enabled": true, + "cluster": { + "serviceName": null, + "name": null, + "healthChecker": { + "type": "TCP" + }, + "defaultPort": 80, + "defaultCheckPort": 80, + "useIPPort4Check": true, + "metadata": { + + } + }, + "service": null, + "metadata": { + + } + } + ], + "lastRefTime": 1541755293119, + "checksum": "e5a699c9201f5328241c178e804657e11541755293119", + "allIPs": false, + "key": "nacos-producer", + "valid": true + } + ], + "NacosDiscoveryProperties": { + "serverAddr": "127.0.0.1:8848", + "endpoint": "", + "namespace": "", + "logName": "", + "service": "nacos-provider", + "weight": 1.0, + "clusterName": "DEFAULT", + "metadata": { + + }, + "registerEnabled": true, + "ip": "30.5.124.201", + "networkInterface": "", + "port": 8082, + "secure": false, + "accessKey": "", + "secretKey": "" + } +} +---- + +=== Start a Consumer Application + +It might not be as easy as starting a provider application, because the consumer needs to call the RESTful service of the provider. In this example, we will use the most primitive way, that is, +combining the LoadBalanceClient and RestTemolate explicitly to access the RESTful service. +You can refer to section 1.2 for pom.xml and application.properties configurations. The following is the sample code for starting a consumer application. + +NOTE: You can also access the service by using RestTemplate and FeignClient with load balancing. + +[source, java] +---- +@SpringBootApplication +@EnableDiscoveryClient +public class NacosConsumerApp { + + @RestController + public class NacosController{ + + @Autowired + private LoadBalancerClient loadBalancerClient; + @Autowired + private RestTemplate restTemplate; + + @Value("${spring.application.name}") + private String appName; + + @GetMapping("/echo/app-name") + public String echoAppName(){ + //Access through the combination of LoadBalanceClient and RestTemolate + ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-provider"); + String url = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName); + System.out.println("request url:" +url); + return restTemplate.getForObject(url,String.class); + } + + } + + //Instantiate RestTemplate Instance + @Bean + public RestTemplate restTemplate(){ + + return new RestTemplate(); + } + + public static void main(String[] args) { + + SpringApplication.run(NacosConsumerApp.class,args); + } +} +---- + +In this example, we injected a LoadBalancerClient instance, and instantiated a RestTemplate manually. At the same time, we injected the configuration value of `spring.application.name` into the application, +so that the current application name can be displayed when calling the service of the provider. + +NOTE: Please start Nacos before you start the consumer application. For details, please refer to https://nacos.io/zh-cn/docs/quick-start.html[Nacos Website]. + +Next, access the `http://ip:port/echo/app-name` interface provided by the consumer. Here we started the port of 8082. The access result is shown below: + + Address:http://127.0.0.1:8082/echo/app-name + Access result: Hello Nacos Discovery nacos-consumer + +=== More Information about Nacos Starter Configurations + +The following shows the other configurations of the starter of spring-cloud-starter-alibaba-nacos-discovery: + +:frame: topbot +[width="60%",options="header"] +|==== +^|Configuration ^|Key ^|Default Value ^|Description +|`Server address`|`spring.cloud.nacos.discovery.server-addr`|`No default value`|`IP and port of the Nacos Server listener` +|`Service name`|`spring.cloud.nacos.discovery.service`|`${spring.application.name}`|`Name the current service` +|`Weight`|`spring.cloud.nacos.discovery.weight`|`1`|`Value range: 1 to 100. The bigger the value, the greater the weight` +|`Network card name`|`spring.cloud.nacos.discovery.network-interface`|`No default value`|`If the IP address is not specified, the registered IP address is the IP address of the network card. If this is not specified either, the IP address of the first network card will be used by default.` +|`Registered IP address`|`spring.cloud.nacos.discovery.ip`|`No default value`|`Highest priority` +|`Registered port`|`spring.cloud.nacos.discovery.port`|`-1`|`Will be detected automatically by default. Do not need to be configured.` +|`Namespace`|`spring.cloud.nacos.discovery.namespace`|`No default value`|`A typical scenario is to isolate the service registration for different environment, such as resource (configurations, services etc.) isolation between testing and production environment` ` +|`AccessKey`|`spring.cloud.nacos.discovery.access-key`|`No default value`|`Alibaba Cloud account` +|`SecretKey`|`spring.cloud.nacos.discovery.secret-key`|`No default value`|`Alibaba Cloud account accesskey` +|`Metadata`|`spring.cloud.nacos.discovery.metadata`|`No default value`|`You can define some of the metadata for your services in the Map format` +|`Log file name`|`spring.cloud.nacos.discovery.log-name`|`No default value`| +|`Endpoint`|`spring.cloud.nacos.discovery.enpoint`|`UTF-8`|`The domain name of a certain service in a specific region. You can retrieve the server address dynamically with this domain name` +|`Integrate Ribbon or not`|`ribbon.nacos.enabled`|`true`|`Set to true in most cases` +|==== + diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/oss.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/oss.adoc index f9a28c12d..6a73be894 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/oss.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/oss.adoc @@ -1 +1,157 @@ == Spring Cloud Alibaba Cloud OSS + +OSS(Object Storage Service)is a storage product on Alibaba Cloud. Spring Cloud Alibaba Cloud OSS provides the commercialized storage service in conformity with Spring Cloud specifications. We provide easy-to-use APIs and supports the integration of Resource in the Spring framework. + +=== How to Introduce Spring Cloud Alibaba Cloud OSS + +We’ve released Spring Cloud Alibaba version 0.2.1. You will need to add dependency management POM first. + +[source,xml] +---- + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + +---- + +Next we need to introduce Spring Cloud Alibaba Cloud OSS Starter. + +[source,xml] +---- + + org.springframework.cloud + spring-cloud-starter-alicloud-oss + +---- + +=== How to Use OSS API + +==== Configure OSS + +Before you start to use Spring Cloud Alibaba Cloud OSS, please add the following configurations in application.properties. + +[source,properties] +---- +spring.cloud.alicloud.access-key=Your Alibaba Cloud AK +spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK +spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com +---- + +access-key and secret-key is the AK/SK of your Alibaba Cloud account. If you don’t have one, please register an account first, and log on to https://usercenter.console.aliyun.com/#/manage/ak[Alibaba Cloud AK/SK Management] to get your AccessKey ID and Access Key Secret . If you haven’t create the AccessKeys, click “Create AccessKey” to create one. + +For endpoint information, please refer to the OSS https://help.aliyun.com/document_detail/31837.html[Documentation] and get the endpoint for your region. + + +==== Introduce OSS API + +The OSS API of Spring Cloud Alibaba Cloud OSS is based on the official OSS SDK, and includes APIs for uploading, downloading, viewing files. + +Here is a simple application that uses the OSS API. + +[source,java] +---- +@SpringBootApplication +public class OssApplication { + + @Autowired + private OSS ossClient; + + @RequestMapping("/") + public String home() { + ossClient.putObject("bucketName", "fileName", new FileInputStream("/your/local/file/path")); + return "upload success"; + } + + public static void main(String[] args) throws URISyntaxException { + SpringApplication.run(OssApplication.class, args); + } + +} +---- + +Before you upload your files, please https://account.aliyun.com/register/register.htm?spm=5176.8142029.388261.26.e9396d3eaYK2sG&oauth_callback=https%3A%2F%2Fwww.aliyun.com%2F[Register an Alibaba Cloud Account]. If you already have one, please https://common-buy.aliyun.com/?spm=5176.8465980.unusable.dopen.4cdf1450rg8Ujb&commodityCode=oss#/open[Sign up for OSS]. + +Log on to the https://oss.console.aliyun.com/overview[OSS Console], click “Create New Bucket” and create a bucket as instructed. Replace the bucket name in the “bucketname” of the previous code with your new bucket name. "fileName” can be any name you like, and "/your/local/file/path” can be any local file path. Next you can run `curl http://127.0.0.1:port number/ to upload your files, and you will see your file on the https://oss.console.aliyun.com/overview[OSS Console]. + +For more instructions on OSS APIs, please refer to https://help.aliyun.com/document_detail/32008.html[OSS SDK Documentation]. + +=== Integrate with the Resource Specifications of Spring + +Spring Cloud Alibaba Cloud OSS integrates the Resource of the Spring framework, which allows you to use the OSS resources easily. + +The following is a simple example of how to use Resource. + +[source,java] +---- +@SpringBootApplication +public class OssApplication { + + @Value("oss://bucketName/fileName") + private Resource file; + + @GetMapping("/file") + public String fileResource() { + try { + return "get file resource success. content: " + StreamUtils.copyToString( + file.getInputStream(), Charset.forName(CharEncoding.UTF_8)); + } catch (Exception e) { + return "get resource fail: " + e.getMessage(); + } + } + + public static void main(String[] args) throws URISyntaxException { + SpringApplication.run(OssApplication.class, args); + } + +} +---- + +NOTE: A prerequisite for the above sample is that you need to have a bucket named “bucketName” on OSS, and you have a file named “fileName” in this bucket. + +=== Use STS Authentication + +In addition to AccessKeys, Spring Cloud Alibaba Cloud OSS also supports STS authentication. STS is an authentication method with temporary security tokens, and is usually used for a third party to access its resources temporarily. + +For a third party to access resources temporarily, it only needs to complete the following configurations. + +[source,properties] +---- +spring.cloud.alicloud.oss.authorization-mode=STS +spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com +spring.cloud.alicloud.oss.sts.access-key=Your authenticated AK +spring.cloud.alicloud.oss.sts.secret-key=Your authenticated SK +spring.cloud.alicloud.oss.sts.security-token=Your authenticated ST +---- + +Among which, spring.cloud.alicloud.oss.authorization-mode is the enumeration type. Fill in STS here means that STS authentication is used. For endpoint information, refer to the https://help.aliyun.com/document_detail/31837.html[OSS Documentation] and fill in the endpoint for your region. + +Access-key, secret-key and the security-token need to be issued by the authentication side. For more information about STS, refer to https://help.aliyun.com/document_detail/31867.html[STS Documentation]. + +=== More Configurations for the Client + +In addition to basic configurations, Spring Cloud Alibaba Cloud OSS also supports many other configurations, which are also included in the application.properties file. + +Here are some examples. + +[source,properties] +---- +spring.cloud.alicloud.oss.authorization-mode=STS +spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com +spring.cloud.alicloud.oss.sts.access-key=Your authenticated AK +spring.cloud.alicloud.oss.sts.secret-key=Your authenticated SK +spring.cloud.alicloud.oss.sts.security-token=Your authenticated ST + +spring.cloud.alicloud.oss.config.connection-timeout=3000 +spring.cloud.alicloud.oss.config.max-connections=1000 +---- + +For more configurations, refer to the table at the bottom of https://help.aliyun.com/document_detail/32010.html[OSSClient Configurations]. + +NOTE: In most cases, you need to connect the parameter names with “-” for the parameters in the table of https://help.aliyun.com/document_detail/32010.html[OSSClient Configurations] with “-”, and all letters should be in lowercase. For example, ConnectionTimeout should be changed to connection-timeout. \ No newline at end of file diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/rocketmq.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/rocketmq.adoc index 238f0b4be..81e36a945 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/rocketmq.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/rocketmq.adoc @@ -1 +1,250 @@ -== Spring Cloud Alibaba Rocket Binder +== Spring Cloud Alibaba RocketMQ Binder + +### Introduction of RocketMQ + +https://rocketmq.apache.org[RocketMQ] is an open-source distributed message system. It is based on highly available distributed cluster technologies and provides message publishing and subscription service with low latency and high stability. RocketMQ is widely used in a variety of industries, such as decoupling of asynchronous communication, enterprise sulotions, financial settlements, telecommunication, e-commerce, logistics, marketing, social media, instant messaging, mobile applications, mobile games, vedios, IoT, and Internet of Vehicles. + +It has the following features: + +* Strict order of message sending and consumption + +* Rich modes of message pulling + +* Horizontal scalability of consumers + +* Real-time message subscription + +* Billion-level message accumulation capability + +### RocketMQ Usages + +* Download RocketMQ + +Download https://www.apache.org/dyn/closer.cgi?path=rocketmq/4.3.2/rocketmq-all-4.3.2-bin-release.zip[Latest Binary File of RocketMQ], and decompress it. + +The decompressed directory is as follows: + +``` +apache-rocketmq +├── LICENSE +├── NOTICE +├── README.md +├── benchmark +├── bin +├── conf +└── lib +``` + +* Start NameServer + +```bash +nohup sh bin/mqnamesrv & +tail -f ~/logs/rocketmqlogs/namesrv.log +``` + +* Start Broker + +```bash +nohup sh bin/mqbroker -n localhost:9876 & +tail -f ~/logs/rocketmqlogs/broker.log +``` + +* Send and Receive Messages + +Send messages: + +```bash +sh bin/tools.sh org.apache.rocketmq.example.quickstart.Producer +``` + +Output when the message is successfuly sent: `SendResult [sendStatus=SEND_OK, msgId= ...` + +Receive messages: + +```bash +sh bin/tools.sh org.apache.rocketmq.example.quickstart.Consumer +``` + +Output when the message is successfully received: `ConsumeMessageThread_%d Receive New Messages: [MessageExt...` + +* Disable Server + +```bash +sh bin/mqshutdown broker +sh bin/mqshutdown namesrv +``` + +### Introduction of Spring Cloud Stream + +Spring Cloud Stream is a microservice framework used to build architectures based on messages. It helps you to create production-ready single-server Spring applications based on SpringBoot, and connects with Broker using `Spring Integration`. + +Spring Cloud Stream provides unified abstractions of message middleware configurations, and puts forward concepts such as publish-subscribe, consumer groups and partition. + +There are two concepts in Spring Cloud Stream: Binder and Binding + +* Binder: A component used to integrate with external message middleware, and is used to create binding. Different message middleware products have their own binder implementations. + +For example, `Kafka` uses `KafkaMessageChannelBinder`, `RabbitMQ` uses `RabbitMessageChannelBinder`, while `RocketMQ` uses `RocketMQMessageChannelBinder`. + +* Binding: Includes Input Binding and Output Binding。 + +Binding serves as a bridge between message middleware and the provider and consumer of the applications. Developers only need to use the Provider or Consumer to produce or consume data, and do not need to worry about the interactions with the message middleware. + +.Spring Cloud Stream +image::https://docs.spring.io/spring-cloud-stream/docs/current/reference/htmlsingle/images/SCSt-overview.png[] + +Now let’s use Spring Cloud Stream to write a simple code for sending and receiving messages: + +```java +MessageChannel messageChannel = new DirectChannel(); + +// Message subscription +((SubscribableChannel) messageChannel).subscribe(new MessageHandler() { + @Override + public void handleMessage(Message message) throws MessagingException { + System.out.println("receive msg: " + message.getPayload()); + } +}); + +// Message sending +messageChannel.send(MessageBuilder.withPayload("simple msg").build()); +``` + +All the message types in this code are provided by the `spring-messaging`module. It shields the lower-layer implementations of message middleware. If you would like to change the message middleware, you only need to configure the related message middleware information in the configuration file and modify the binder dependency. + +**The lower layer of Spring Cloud Stream also implements various code abstractions based on the previous code.** + +### How Spring Cloud Alibaba RocketMQ Binder Works + +.RocketMQ Binder Workflow +image::https://cdn.nlark.com/lark/0/2018/png/64647/1543560843558-24525bf4-1d0e-4e10-be5f-bdde7127f6e6.png[] + + +The core of RocketMQ Binder are the 3 classes below: `RocketMQMessageChannelBinder`,`RocketMQInboundChannelAdapter` and `RocketMQMessageHandler`. + +`RocketMQMessageChannelBinder` is a standard implementation of Binder. It contains `RocketMQInboundChannelAdapter` and `RocketMQMessageHandler` as its internal constructions. + +`RocketMQMessageHandler` is used to start RocketMQ `Producer` and send messages. It creates message type of RocketMQ `org.apache.rocketmq.common.message.Message` based on the message type of `org.springframework.messaging.Message` in the `spring-messaging` module. + +When constructing `org.apache.rocketmq.common.message.Message`, it constructs `RocketMQMessageHeaderAccessor` based on the header of `org.springframework.messaging.Message`. Then, based on some of the properties in `RocketMQMessageHeaderAccessor` , it sets some of message attributes such as tags, keys, and flag in `org.apache.rocketmq.common.message.Message` of RocketMQ. + +`RocketMQInboundChannelAdapter` is used to start RocketMQ `Consumer` and receive messages. It also support the usage of https://github.com/spring-projects/spring-retry[spring-retry]. + +You can also obtain `Acknowledgement` from the Header and make some configurations. + +For example, you can set delayed message consumption when `MessageListenerConcurrently` is used for asynchronous message consumption: + +```java +@StreamListener("input") +public void receive(Message message) { + RocketMQMessageHeaderAccessor headerAccessor = new RocketMQMessageHeaderAccessor(message); + Acknowledgement acknowledgement = headerAccessor.getAcknowledgement(message); + acknowledgement.setConsumeConcurrentlyStatus(ConsumeConcurrentlyStatus.RECONSUME_LATER); + acknowledgement.setConsumeConcurrentlyDelayLevel(1); +} +``` + +You can also set delayed message consumption when `MessageListenerOrderly` is used for consuming ordered messages. + +```java +@StreamListener("input") +public void receive(Message message) { + RocketMQMessageHeaderAccessor headerAccessor = new RocketMQMessageHeaderAccessor(message); + Acknowledgement acknowledgement = headerAccessor.getAcknowledgement(message); + acknowledgement.setConsumeOrderlyStatus(ConsumeOrderlyStatus.SUSPEND_CURRENT_QUEUE_A_MOMENT); + acknowledgement.setConsumeOrderlySuspendCurrentQueueTimeMill(5000); +} +``` + +Supported Configurations of Provider: + +:frame: topbot +[width="60%",options="header"] +|==== +^|Configuration ^|Description ^| Default Value +|`spring.cloud.stream.rocketmq.bindings.your-output-binding.producer.enabled`|Whether to use producer|true +|`spring.cloud.stream.rocketmq.bindings.your-output-binding.producer.max-message-size`|Maximum bytes of messages sent|0(Take effect only when it’s bigger than 0. The default value of RocketMQ is 4M = 1024 * 1024 * 4) +|`spring.cloud.stream.rocketmq.bindings.your-output-binding.producer.transactional`|Whether to use `TransactionMQProducer` to send transaction messages|false +|`spring.cloud.stream.rocketmq.bindings.your-output-binding.producer.executer`|Full class name of the interface implementation class related to `org.apache.rocketmq.client.producer.LocalTransactionExecuter` For example, `org.test.MyExecuter`| +|`spring.cloud.stream.rocketmq.bindings.your-output-binding.producer.transaction-check-listener`|Full class name of the interface implementation class related to `org.apache.rocketmq.client.producer.TransactionCheckListener` For example, `org.test.MyTransactionCheckListener`| +|==== + +Supported Configurations of Consumer: + +:frame: topbot +[width="60%",options="header"] +|==== +^|Configuration ^|Description| Default Value +|`spring.cloud.stream.rocketmq.bindings.your-input-binding.consumer.enabled`|Whether to use consumer|true +|`spring.cloud.stream.rocketmq.bindings.your-input-binding.consumer.tags`|Consumer will only subscribe to messages with these tags Tags are separated by "\|\|" (If not specified, it means the consumer subscribes to all messages)| +|`spring.cloud.stream.rocketmq.bindings.your-input-binding.consumer.sql`|Consumer subscribes to the messages as requested in the SQL(If tags are also specified, SQL has a higher priority than tags.)| +|`spring.cloud.stream.rocketmq.bindings.your-input-binding.consumer.broadcasting`|If the consumer uses the broadcasting mode|false +|`spring.cloud.stream.rocketmq.bindings.your-input-binding.consumer.orderly`|Ordered message consumption or asychronous consumption|false +|==== + +### Endpoint Support + +Before you use the Endpoint feature, please add the `spring-boot-starter-actuator` dependency in Maven, and enable access of Endpoints in your configuration. + +* Add `management.security.enabled=false`in Spring Boot 1.x. The exposed endpoint path is `/rocketmq_binder` +* Add `management.endpoints.web.exposure.include=*`in Spring Boot 2.x. The exposed endpoint path is `/actuator/rocketmq-binder` + +Endpoint will collects data about the last message that is sent, the number of successes or failures of message sending, and the number of successes of failures of message consumption. + +```json +{ + "runtime": { + "lastSend.timestamp": 1542786623915 + }, + "metrics": { + "scs-rocketmq.consumer.test-topic.totalConsumed": { + "count": 11 + }, + "scs-rocketmq.consumer.test-topic.totalConsumedFailures": { + "count": 0 + }, + "scs-rocketmq.producer.test-topic.totalSentFailures": { + "count": 0 + }, + "scs-rocketmq.consumer.test-topic.consumedPerSecond": { + "count": 11, + "fifteenMinuteRate": 0.012163847780107841, + "fiveMinuteRate": 0.03614605351360527, + "meanRate": 0.3493213353657594, + "oneMinuteRate": 0.17099243039490175 + }, + "scs-rocketmq.producer.test-topic.totalSent": { + "count": 5 + }, + "scs-rocketmq.producer.test-topic.sentPerSecond": { + "count": 5, + "fifteenMinuteRate": 0.005540151995103271, + "fiveMinuteRate": 0.01652854617838251, + "meanRate": 0.10697493212602836, + "oneMinuteRate": 0.07995558537067671 + }, + "scs-rocketmq.producer.test-topic.sentFailuresPerSecond": { + "count": 0, + "fifteenMinuteRate": 0.0, + "fiveMinuteRate": 0.0, + "meanRate": 0.0, + "oneMinuteRate": 0.0 + }, + "scs-rocketmq.consumer.test-topic.consumedFailuresPerSecond": { + "count": 0, + "fifteenMinuteRate": 0.0, + "fiveMinuteRate": 0.0, + "meanRate": 0.0, + "oneMinuteRate": 0.0 + } + } +} +``` + +Note: To view statistics, add the https://mvnrepository.com/artifact/io.dropwizard.metrics/metrics-core[metrics-core dependency] in POM. If not added, the endpoint will return warning instead of statistics: + +```json +{ + "warning": "please add metrics-core dependency, we use it for metrics" +} +``` \ No newline at end of file diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc new file mode 100644 index 000000000..bffdc3fb8 --- /dev/null +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/schedulerx.adoc @@ -0,0 +1,131 @@ +== Spring Cloud Alibaba Cloud SchedulerX + +SchedulerX(Distributed job scheduling) is a component of EDAS, an Alibaba Cloud product. Spring Cloud Alibaba Cloud SchedulerX provides distributed job scheduling in conformity with the Spring Cloud specifications. SchedulerX provides timed job scheduling service with high accuracy with seconds, high stability and high availabiliy, and supports multiple job types, such as simple single-server jobs, simple multi-host jobs, script jobs, and grid jobs. + +=== How to Introduce Spring Cloud Alibaba Cloud SchedulerX + +We’ve released Spring Cloud Alibaba version 0.2.1. You will need to add dependency management POM first. + +[source,xml] +---- + + + + org.springframework.cloud + spring-cloud-alibaba-dependencies + 0.2.1.RELEASE + pom + import + + + +---- + +Next we need to introduce Spring Cloud AliCloud SchedulerX Starter. + +[source,xml] +---- + + org.springframework.cloud + spring-cloud-starter-alicloud-schedulerX + +---- + +=== Start SchedulerX + +After Spring Cloud Alibaba Cloud SchedulerX Starter is introduced into the client, you only need to complete a few simple configurations and you will be able to initialize the SchedulerX service automatically. + +The following is a simple example. + +[source,java] +---- +@SpringBootApplication +public class ScxApplication { + + public static void main(String[] args) { + SpringApplication.run(ScxApplication.class, args); + } + +} +---- + +Add the following configurations in the application.properties file. + +[source,properties] +---- +server.port=18033 +# cn-test is the test region of SchedulerX +spring.cloud.alicloud.scx.group-id=*** +spring.cloud.alicloud.edas.namespace=cn-test +---- + +Before getting the group-id, please https://account.aliyun.com/register/register.htm?spm=5176.8142029.388261.26.e9396d3eEIv28g&oauth_callback=https%3A%2F%2Fwww.aliyun.com%2F[Register an Alibaba Cloud account], and then https://common-buy.aliyun.com/?spm=5176.11451019.0.0.6f5965c0Uq5tue&commodityCode=edaspostpay#/buy[Sign up for EDAS] and https://edas.console.aliyun.com/#/edasTools[Sign up for SchedulerX] as well. + +To get the group-id, refer to the https://help.aliyun.com/document_detail/98784.html[SchedulerX Documentation]. + +NOTE: When you create a group, please select the “test” region. + +=== Compile a simple job + +Simple job is the most commonly used job type. You only need to implement the ScxSimpleJobProcessor interface. + +The following is a sample of a simple single-server job. + +[source,java] +---- +public class SimpleTask implements ScxSimpleJobProcessor { + + @Override + public ProcessResult process(ScxSimpleJobContext context) { + System.out.println("-----------Hello world---------------"); + ProcessResult processResult = new ProcessResult(true); + return processResult; + } + +} +---- + +=== Job Scheduling + +Go to the https://edas.console.aliyun.com/#/edasSchedulerXJob?regionNo=cn-test[SchedulerX Jobs] page, select the “Test” region, and click “Create Job” on the upper-right corner to create a job, as shown below. + +[source,text] +---- +Job Group: Test——***-*-*-**** +Job process interface:org.springframework.cloud.alibaba.cloud.examples.SimpleTask +Type: Simple Single-Server Job +Quartz Cron Expression: Default Option——0 * * * * ? +Job Description: Empty +Custom Parameters: Empty +---- + +The job above is a “Simple Single-Server Job”, and speficied a Cron expression of "0 * * * * ?" . This means that the job will be executed once and once only in every minute. + +For more job types, refer to https://help.aliyun.com/document_detail/43136.html[SchedulerX Documentation]. + +=== Usage in Production Environment + +The previous examples shows how to use SchedulerX in the “Test” region, which is mainly used for local testing. + +At the production level, you need to complete some other configurations in addition to the group-id and namespace as mentioned above. See examples below: + +[source,properties] +---- +server.port=18033 +# cn-test is the test region of SchedulerX +spring.cloud.alicloud.scx.group-id=*** +spring.cloud.alicloud.edas.namespace=*** +# If your application runs on EDAS, you do not need to configure the following. +spring.cloud.alicloud.access-key=*** +spring.cloud.alicloud.secret-key=*** +# The following configurations are not mandatory. You can refer to the SchedulerX documentation for details. +spring.cloud.alicloud.scx.domain-name=*** +---- + +The way to get the group-id is the same as described in the previous examples, and you can get the namespace by clicking “Namespaces” in the left-side navigation pane of the EDAS console. + +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. diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc index 59eaa589c..01b9225e8 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/sentinel.adoc @@ -1 +1,318 @@ == Spring Cloud Alibaba 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. + +https://github.com/alibaba/Sentinel[Sentinel] has the following features: + + +* *Rich Scenarios*: Sentinel has supported the key scenarios of Alibaba’s Double 11 Shopping Festivals for over 10 years, such as second kill(i.e., controlling sudden bursts of traffic flow so that it’s within the acceptable range of the system capacity), message load shifting, circuit breaking of unreliable downstream applications. +* *Comprehensive Real-Time Monitoring*: Sentinel provides real-time monitoring capability. You can see the monitoring data of your servers at the accuracy of seconds, and even the overall runtime status of a cluster with less than 500 nodes. +* *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 + +If you want to use Sentinel in your project, please use the starter with the group ID as `org.springframework.cloud` and the artifact ID as `spring-cloud-starter-alibaba-sentinel`. + +```xml + + org.springframework.cloud + spring-cloud-starter-alibaba-sentinel + +``` + +The following is a simple example of how to use Sentinel: + +```java +@SpringBootApplication +public class Application { + + public static void main(String[] args) { + SpringApplication.run(ServiceApplication.class, args); + } + +} + +@RestController +public class TestController { + + @GetMapping(value = "/hello") + @SentinelResource("hello") + public String hello() { + return "Hello Sentinel"; + } + +} +``` + +The @SentinelResource annotation is used to identify if a resource is rate limited or degraded. In the above sample, the 'hello' attribute of the annotation refers to the resource name. + +@SentinelResource also provides attributes such as `blockHandler`, `blockHandlerClass`, and `fallback` to identify rate limiting or degradation operations. For more details, refer to https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81[Sentinel Annotation Support]. + +##### 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. + +*Note*: The statistics overview for clusters only supports clusters with less than 500 nodes, and has a latency of about 1 to 2 seconds. + +.Sentinel Dashboard +image::https://github.com/alibaba/Sentinel/wiki/image/dashboard.png[] + +To use the Sentinel dashboard, simply complete the following 3 steps. + +###### Get the Dashboard + +You can download the latest dashboard JAR file from the https://github.com/alibaba/Sentinel/releases[Release Page]. + +You can also get the latest source code to build your own Sentinel dashboard: + +* Download the https://github.com/alibaba/Sentinel/tree/master/sentinel-dashboard[Dashboard] project. +* Run the following command to package the code into a FatJar: `mvn clean package` + + +###### Start the Dashboard + +Sentinel dashboard is a standard SpringBoot application, and you can run the JAR file in the Spring Boot mode. + +```shell +java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar +``` + +If there is conflict with the 8080 port, you can use `-Dserver.port=new port` to define a new port. + +#### Configure the Dashboard + +.application.yml +---- +spring: + cloud: + sentinel: + transport: + port: 8719 + dashboard: localhost:8080 +---- + +The port number specified in `spring.cloud.sentinel.transport.port` will start an HTTP Server on the corresponding server of the application, and this server will interact with the Sentinel dashboard. For example, if a rate limiting rule is added in the Sentinel dashboard, the the rule data will be pushed to and recieved by the HTTP Server, which in turn registers the rule to Sentinel. + +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]. + +### Feign Support + +Sentinel is compatible with the https://github.com/OpenFeign/feign[Feign] component. To use it, in addition to introducing the `sentinel-starter` dependency, complete the following 3 steps: + +* Enable the Sentinel support for feign in the properties file. `feign.sentinel.enabled=true` +* Add the `feign starter` dependency to trigger and enable `sentinel starter`: +```xml + + org.springframework.cloud + spring-cloud-starter-openfeign + +``` +* The `loadbalance` in `feign` is dependent on the `ribbon` module of Netflix (You do not need to introduce it if `loadbalance` is not used): +```xml + + org.springframework.cloud + spring-cloud-starter-netflix-ribbon + +``` + +This is an interface for `FeignClient`: + +```java +@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class) +public interface EchoService { + @RequestMapping(value = "/echo/{str}", method = RequestMethod.GET) + String echo(@PathVariable("str") String str); +} + +class FeignConfiguration { + @Bean + public EchoServiceFallback echoServiceFallback() { + return new EchoServiceFallback(); + } +} + +class EchoServiceFallback implements EchoService { + @Override + public String echo(@PathVariable("str") String str) { + return "echo fallback"; + } +} +``` + +NOTE: The resource name policy in the corresponding interface of Feign is:httpmethod:protocol://requesturl + +The corresponding resource name of the `echo` method in the `EchoService` interface is `GET:http://service-provider/echo/{str}`. + +Note: All the attributes in the `@FeignClient` annotation is supported by Sentinel. + +### 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. + +```java +@Bean +@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class) +public RestTemplate restTemplate() { + return new RestTemplate(); +} +``` + +The parameter of the `@SentinelRestTemplate` annotation and its usage is the same with `@SentinelResource`. + +Sentinel provides two granularities for resource rate limiting: + +* `schema://host:port/path`: Protocol, host, port and path + +* `schema://host:port`: Protocol, host and port + +NOTE: Take `https://www.taobao.com/test` as an example. The corresponding resource names have two levels of granularities, `https://www.taobao.com:80` and `https://www.taobao.com:80/test`. + +### Dynamic Data Source Support + +#### For 0.2.0.RELEASE or 0.1.0.RELEASE and ealier versions, + +you need to complete the following 3 steps to configure your data source. + +* Define the data source information in your properties file. For example, you can use: + +.application.properties +---- +spring.cloud.sentinel.datasource.type=file +spring.cloud.sentinel.datasource.recommendRefreshMs=3000 +spring.cloud.sentinel.datasource.bufSize=4056196 +spring.cloud.sentinel.datasource.charset=utf-8 +spring.cloud.sentinel.datasource.converter=flowConverter +spring.cloud.sentinel.datasource.file=/Users/you/yourrule.json +---- + +* Create a Converter class to implement the `com.alibaba.csp.sentinel.datasource.Converter` interface, and you need to have a bean of this class in `ApplicationContext`. + +```java +@Component("flowConverter") +public class JsonFlowRuleListParser implements Converter> { + @Override + public List convert(String source) { + return JSON.parseObject(source, new TypeReference>() { + }); + } +} +``` + +The bean name of this Converter needs to be the same with the converter in the `application.properties` file. + +* Define a `ReadableDataSource` attribute that is modified by the `@SentinelDataSource` annotation in any Spring Bean `@SentinelDataSource`. + +```java +@SentinelDataSource("spring.cloud.sentinel.datasource") +private ReadableDataSource dataSource; +``` + +The value attribute of `@SentinelDataSource` means that the data source is in the prefix of the `application.properties` file. In this example, the prefix is `spring.cloud.sentinel.datasource`. + +If there are over 1 `ReadableDataSource` beans in `ApplicationContext`, then none of the data sources in `ReadableDataSource` will be loaded. It takes effect only when there is only 1 `ReadableDataSource` in `ApplicationContext`. + +If the data source takes effect and is loaded successfully, the dashboard will print information as shown below: + +``` +[Sentinel Starter] load 3 flow rules +``` + +#### In 0.2.0.RELEASE and 0.1.0.RELEASE or later + +You only need to complete 1 step to configure your data source: + +* Configure your data source in the `application.properties` file directly. + +For example, 4 data sources are configures: + +``` +spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json + +spring.cloud.sentinel.datasource.ds2.nacos.server-addr=localhost:8848 +spring.cloud.sentinel.datasource.ds2.nacos.dataId=sentinel +spring.cloud.sentinel.datasource.ds2.nacos.groupId=DEFAULT_GROUP +spring.cloud.sentinel.datasource.ds2.nacos.data-type=json + +spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW +spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181 + +spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application +spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel +spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test + +``` + +This method follows the configuration of Spring Cloud Stream Binder. `TreeMap` is used for storage internally, and comparator is `String.CASE_INSENSITIVE_ORDER`. + +NOTE: d1, ds2, ds3, ds4 are the names of `ReadableDataSource`, and can be coded as you like. The `file` ,`zk` ,`nacos` , `apollo` refer to the specific data sources. The configurations following them are the specific configurations of these data sources respecitively. + +Every data source has two common configuration items: `data-type` and `converter-class`. + +`data-type` refers to `Converter`. Spring Cloud Alibaba Sentinel provides two embedded values by defaul: `json` and `xml` (the default is json if not specified). If you do not want to use the embedded `json` or `xml` `Converter`, you can also fill in `custom` to indicate that you will define your own `Converter`, and then configure the `converter-class`. You need to specify the full path of the class for this configuration. + +The two embedded `Converter` only supports parsing the Json array or XML array. Sentinel will determine automatically which of the 4 Sentinel rules that the Json or XML objext belongs to(`FlowRule`,`DegradeRule`,`SystemRule`,`AuthorityRule`). + +For example, if 5 rate limiting rules and 5 degradation rules in the 10 rule arrays, then the data source will not be registered, and there will be warnings in the logs. + +If there are 9 rate limiting rules among the 10 arrays, and 1 error parsing the 10th array, then there will be warning in the log indicating that there is error in one of the rules, while the other 9 rules will be registered. + +Here `jackson` is used to parse the Json or XML arrays. `ObjectMapper` or `XmlMapper` uses the default configuration and will report error if there are unrecognized fields. The reason behind this logic is that without this strict parsing, Json will also be parsed as system rules(all system rules have default values). + +In another case, the Json or XML object might match all of the 4 rules(for example, if only the `resource` field is configured in the Json object, then it will match all 4 rules). In this case, there will be warnings in the log, and this object will be filtered. + +When you use this configuration, you only need to fill in the Json or XML correctly, and any of the unreasonable information will be printed in the log. + +If the data source takes effect and is loaded successfully, the dashboard will print information as shown below: + +``` +[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule +[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule +``` + +NOTE: XML format is not supported by default. To make it effective, you need to add the `jackson-dataformat-xml` dependency. + +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]. + +### Endpoint Support + +Before you use the Endpoint feature, please add the `spring-boot-starter-actuator` dependency in Maven, and enable access of Endpoints in your configuration. + +* Add `management.security.enabled=false` in Spring Boot 1.x. The exposed endpoint path is `/sentinel`. +* Add `management.endpoints.web.exposure.include=*` in Spring Boot 2.x. The exposed endpoint path is `/actuator/sentinel`. + +### More + +The following table shows that when there are corresponding bean types in `ApplicationContext`, some actions will be taken: + +:frame: topbot +[width="60%",options="header"] +|==== +^|Existing Bean Type ^|Action ^|Function +|`UrlCleaner`|`WebCallbackManager.setUrlCleaner(urlCleaner)`|Resource cleaning(resource(for example, classify all URLs of /foo/:id to the /foo/* resource)) +|`UrlBlockHandler`|`WebCallbackManager.setUrlBlockHandler(urlBlockHandler)`|Customize rate limiting logic +|==== + +The following table shows all the configurations of Spring Cloud Alibaba Sentinel: + +:frame: topbot +[width="60%",options="header"] +|==== +^|Configuration ^|Description ^|Default Value +|`spring.cloud.sentinel.enabled`|Whether Sentinel automatic configuration takes effect|true +|`spring.cloud.sentinel.eager`|Cancel Sentinel dashboard lazy load|false +|`spring.cloud.sentinel.transport.port`|Port for the application to interact with Sentinel dashboard. An HTTP Server which uses this port will be started in the application|8721 +|`spring.cloud.sentinel.transport.dashboard`|Sentinel dashboard address| +|`spring.cloud.sentinel.transport.heartbeatIntervalMs`|Hearbeat interval between the application and Sentinel dashboard| +|`spring.cloud.sentinel.filter.order`|Loading order of Servlet Filter. The filter will be constructed in the Starter|Integer.MIN_VALUE +|`spring.cloud.sentinel.filter.spring.url-patterns`|Data type is array. Refers to the collection of Servlet Filter ULR patterns|/* +|`spring.cloud.sentinel.metric.charset`|metric file character set|UTF-8 +|`spring.cloud.sentinel.metric.fileSingleSize`|Sentinel metric single file size| +|`spring.cloud.sentinel.metric.fileTotalCount`|Sentinel metric total file number| +|`spring.cloud.sentinel.log.dir`|Directory of Sentinel log files| +|`spring.cloud.sentinel.log.switch-pid`|If PID is required for Sentinel log file names|false +|`spring.cloud.sentinel.servlet.blockPage`| Customized redirection URL. When rate limited, the request will be redirected to the pre-defined URL | +|`spring.cloud.sentinel.flow.coldFactor`| https://github.com/alibaba/Sentinel/wiki/%E9%99%90%E6%B5%81---%E5%86%B7%E5%90%AF%E5%8A%A8[冷启动因子] |3 +|==== diff --git a/spring-cloud-alibaba-docs/src/main/asciidoc/spring-cloud-alibaba.adoc b/spring-cloud-alibaba-docs/src/main/asciidoc/spring-cloud-alibaba.adoc index a8c52ae28..bbcae98b1 100644 --- a/spring-cloud-alibaba-docs/src/main/asciidoc/spring-cloud-alibaba.adoc +++ b/spring-cloud-alibaba-docs/src/main/asciidoc/spring-cloud-alibaba.adoc @@ -9,9 +9,9 @@ xiaojing; xiaolongzuo; jim fang; bingting peng == Introduction -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. +Spring Cloud Alibaba aims to provide a one-stop solution for microservices development. This prjoect includes the required components for developing distributed applications and services, so that developers can develop distributed applications easily with the Spring Cloud programming models. -With Spring Cloud Alibaba, you only need to add some annotations and a small amount of configurations to connect Spring Cloud applications to the distributed solutions of Alibaba, and build a distributed application system with Alibaba middleware. +With Spring Cloud Alibaba, you only need to add a few annotations and configurations, and you will be able to use the distributed solutions of Alibaba for your applications, and build a distributed system of your own with Alibaba middleware. include::dependency-management.adoc[] @@ -29,3 +29,4 @@ include::acm.adoc[] include::oss.adoc[] +include::schedulerx.adoc[]