mirror of
https://gitee.com/mirrors/Spring-Cloud-Alibaba.git
synced 2021-06-26 13:25:11 +08:00
update docs
This commit is contained in:
@@ -1,34 +1,19 @@
|
||||
== 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 AliCloud 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.
|
||||
Use Spring Cloud AliCloud ACM to quickly access ACM configuration management capabilities based on Spring Cloud's programming model.
|
||||
|
||||
NOTE: Currently EDAS already supports direct deployment of the Nacos Config app.
|
||||
|
||||
=== 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]
|
||||
----
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
|
||||
Next we need to introduce Spring Cloud Alibaba Cloud ACM Starter.
|
||||
If you want to use ACM in your project, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alicloud-acm`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-acm</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
@@ -68,18 +53,18 @@ 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
|
||||
==== 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.
|
||||
ACM uses two types of configuration centers. One is lightweight configuration center, 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
|
||||
===== Use 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.
|
||||
NOTE: You only need to perform step 1(Download lightweight configuration center) and step 2(Start lightweight configuration center).
|
||||
|
||||
|
||||
==== Use ACM on the Cloud
|
||||
===== Use ACM on the Alibaba 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.
|
||||
|
||||
@@ -88,7 +73,7 @@ The following is a simple sample of using ACM. You can view configuration detail
|
||||
[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
|
||||
spring.application.name=acm-config
|
||||
# Configure your own port number
|
||||
server.port=18081
|
||||
# The following is the IP and port number of the configuration center.
|
||||
@@ -99,9 +84,9 @@ 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.
|
||||
NOTE: EDAS provides application hosting service and will fill in all configurations about ACM automatically for the hosted applications.
|
||||
|
||||
=== Add Configuration in the Configuration Center
|
||||
==== Add Configuration in the Configuration Center
|
||||
|
||||
1. After you start the lightweight configuration center, add the following configuration on the console.
|
||||
|
||||
@@ -117,7 +102,7 @@ Content: user.name=james
|
||||
|
||||
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 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.
|
||||
|
||||
@@ -129,20 +114,20 @@ 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.
|
||||
You can set the file extension using spring.cloud.alicloud.acm.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
|
||||
=== Dynamic Configuration Refresh
|
||||
|
||||
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.
|
||||
spring-cloud-starter-alicloud-acm supports dynamic configuration updates. RefreshEvent in Spring is published when you update configuration in the configuration center.
|
||||
All classes with @RefreshScope and @ConfigurationProperties annotations will be refreshed automatically.
|
||||
|
||||
NOTE: You can disable automatic refresh by this setting: spring.cloud.nacos.config.refresh.enabled=false
|
||||
NOTE: You can disable automatic refresh by this setting: spring.cloud.alicloud.acm.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.
|
||||
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.
|
||||
|
||||
@@ -154,17 +139,21 @@ 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 ACM Timeout
|
||||
|
||||
the default timeout of ACM client get config from sever is 3000 ms . If you need to define a timeout, set configuration `spring.cloud.alicloud.acm.timeout`,the unit is millisecond.
|
||||
|
||||
|
||||
=== 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:
|
||||
DEFAULT_GROUP is used by default when no `{spring.cloud.alicloud.acm.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
|
||||
spring.cloud.alicloud.acm.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`.
|
||||
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.alicloud.acm.group`.
|
||||
|
||||
==== Support Shared Configurations
|
||||
|
||||
@@ -175,11 +164,15 @@ ACM provides a solution to share the same configuration across multiple applicat
|
||||
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。
|
||||
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: The default suffix of DataId is properties, and you can change it using spring.cloud.alicloud.acm.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}`
|
||||
|
||||
=== Actuator Endpoint
|
||||
|
||||
the Actuator endpoint of ACM is `/acm`, `config` represents the ACM metadata configuration information, `runtime.sources` corresponds to the configuration information obtained from the ACM server and the last refresh time, `runtime.refreshHistory` corresponds to the dynamic refresh history.
|
@@ -2,31 +2,16 @@
|
||||
|
||||
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.
|
||||
|
||||
NOTE: EDAS currently supports direct deployment of Nacos Discovery applications
|
||||
|
||||
=== 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]
|
||||
----
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
|
||||
Next we need to introduce Spring Cloud AliCloud ANS Starter.
|
||||
If you want to use ANS in your project, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alicloud-ans`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-ans</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
@@ -108,4 +93,3 @@ 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.
|
||||
|
||||
|
@@ -1,38 +1,19 @@
|
||||
== Dependency Management
|
||||
|
||||
The Spring Cloud Alibaba Bill of Materials (BOM) contains the versions of all the dependencies it uses.
|
||||
If you’re a Maven Central user, add our BOM to your pom.xml <dependencyManagement> section. This will allow you to omit versions for any of the Maven dependencies and instead delegate versioning to the BOM.
|
||||
|
||||
Version 0.2.1.RELEASE is compatible with the Spring Cloud Finchley. Version 0.1.2.BUILD-SNAPSHOT is compatible with the Spring Cloud Edgware.
|
||||
|
||||
These artifacts are available from Maven Central and Spring Release repository via BOM:
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
```xml
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<version>1.0.0.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
```
|
||||
|
||||
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
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<repositories>
|
||||
<repository>
|
||||
<id>spring-snapshot</id>
|
||||
<name>Spring Snapshot Repository</name>
|
||||
<url>https://repo.spring.io/snapshot</url>
|
||||
<snapshots>
|
||||
<enabled>true</enabled>
|
||||
</snapshots>
|
||||
</repository>
|
||||
</repositories>
|
||||
----
|
||||
In the following sections, it will be assumed you are using the Spring Cloud Alibaba BOM and the dependency snippets will not contain versions.
|
||||
|
@@ -0,0 +1,18 @@
|
||||
## Introduction
|
||||
|
||||
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 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.
|
||||
|
||||
The features of Spring Cloud Alibaba:
|
||||
|
||||
1. **Flow control and service degradation**:support WebServlet, WebFlux, OpenFeign, RestTemplate, Dubbo access to the function of limiting and degrading flow. It can modify the rules of limiting and degrading flow in real time through the console at run time, and it also supports the monitoring of limiting and degrading Metrics.
|
||||
2. **Service registration and discovery**:Service can be registered and clients can discover the instances using Spring-managed beans, auto integration Ribbon.
|
||||
3. **Distributed configuration**:support for externalized configuration in a distributed system, auto refresh when configuration changes.
|
||||
4. **Event-driven**:support for building highly scalable event-driven microservices connected with shared messaging systems.
|
||||
5. **Distributed Transaction**:support for distributed transaction solution with high performance and ease of use.
|
||||
6. **Alibaba Cloud Object Storage**:massive, secure, low-cost, and highly reliable cloud storage services. Support for storing and accessing any type of data in any application, anytime, anywhere.
|
||||
7. **Alibaba Cloud SchedulerX**:accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds.
|
||||
8. **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.
|
||||
|
||||
Spring Cloud Alibaba also provide rich https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples[examples].
|
@@ -1,16 +1,35 @@
|
||||
== 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.
|
||||
Nacos is an easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications.
|
||||
|
||||
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.
|
||||
Use Spring Cloud Alibaba Nacos Config to quickly access Nacos configuration management capabilities based on Spring Cloud's programming model.
|
||||
|
||||
=== How to Introduce Nacos Config for configuration
|
||||
|
||||
please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alibaba-nacos-config`.
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
=== Quickstart
|
||||
|
||||
===== Initialize Nacos Server
|
||||
Nacos Config uses DataId and GROUP to determine a configuration.
|
||||
|
||||
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.
|
||||
The following figure shows that the DataId uses `myDataid`, GROUP uses `DEFAULT_GROUP`, and configures a configuration item of the format Properties:
|
||||
|
||||
2. Add the following configurations in Nacos:
|
||||
.Nacos Config Item
|
||||
image::https://img.alicdn.com/tfs/TB1N2nxbRr0gK0jSZFnXXbRRXXa-2448-1194.png[]
|
||||
|
||||
==== Initialize Nacos Server
|
||||
|
||||
For specific startup methods, refer to the "Nacos Server Startup" section of the Spring Cloud Alibaba Nacos Discovery section.
|
||||
|
||||
After the Nacos Server is started, add how to configure it:
|
||||
|
||||
[source,subs="normal"]
|
||||
----
|
||||
@@ -24,59 +43,18 @@ Configuration content: user.name=nacos-config-properties
|
||||
user.age=90
|
||||
----
|
||||
|
||||
NOTE: The default file extension of dataid is properties.
|
||||
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:
|
||||
If you want to use Nacos to manage externalized configurations for your applications, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alibaba-nacos-config`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.5.RELEASE</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Finchley.SR1</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
Now we can create a standard Spring Boot application.
|
||||
@@ -84,10 +62,10 @@ Now we can create a standard Spring Boot application.
|
||||
[source,java]
|
||||
----
|
||||
@SpringBootApplication
|
||||
public class ProviderApplication {
|
||||
public class NacosConfigApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.class, args);
|
||||
String userName = applicationContext.getEnvironment().getProperty("user.name");
|
||||
String userAge = applicationContext.getEnvironment().getProperty("user.age");
|
||||
System.err.println("user name :" +userName+"; age: "+userAge);
|
||||
@@ -100,6 +78,7 @@ Before running this example, we need to configure the address of the Nacos serve
|
||||
.bootstrap.properties
|
||||
[source,properties]
|
||||
----
|
||||
# DataId By default, the `spring.application.name` configuration is combined with the file extension (the configuration format uses properties by default), and the GROUP is not configured to use DEFAULT_GROUP by default. Therefore, the Nacos Config configuration corresponding to the configuration file has a DataId of nacos-config.properties and a GROUP of DEFAULT_GROUP
|
||||
spring.application.name=nacos-config
|
||||
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
|
||||
----
|
||||
@@ -112,17 +91,16 @@ 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)
|
||||
2018-11-02 14:24:51.638 INFO 32700 --- [main] c.a.demo.provider.NacosConfigApplication : Started NacosConfigApplication 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.
|
||||
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:
|
||||
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]
|
||||
@@ -130,7 +108,7 @@ spring-cloud-starter-alibaba-nacos-config supports yaml format as well. You only
|
||||
spring.cloud.nacos.config.file-extension=yaml
|
||||
----
|
||||
|
||||
2. Add a configuration with the dataId in yaml format on the Nacos console, as shown below:
|
||||
2. Add a configuration with the DataId in yaml format on the Nacos console, as shown below:
|
||||
|
||||
[source,subs="normal"]
|
||||
----
|
||||
@@ -141,29 +119,29 @@ Group : DEFAULT_GROUP
|
||||
Configuration format: YAML
|
||||
|
||||
Configuration content: user.name: nacos-config-yaml
|
||||
user.age: 68
|
||||
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)
|
||||
2018-11-02 14:59:00.484 INFO 32928 --- [main] c.a.demo.provider.NacosConfigApplication:Started NacosConfigApplication 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:
|
||||
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 class NacosConfigApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.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");
|
||||
@@ -194,7 +172,7 @@ NOTE: You can disable automatic refresh with this setting`spring.cloud.nacos.con
|
||||
|
||||
=== 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.
|
||||
When configurations are loaded by 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]
|
||||
----
|
||||
@@ -203,7 +181,7 @@ 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:
|
||||
Add a basic configuration in Nacos, with a DataId of nacos-config-develop.yaml, as shown below:
|
||||
|
||||
[source,subs="normal"]
|
||||
----
|
||||
@@ -221,10 +199,10 @@ Run the following Spring Boot application testing code:
|
||||
[source,java]
|
||||
----
|
||||
@SpringBootApplication
|
||||
public class ProviderApplication {
|
||||
public class NacosConfigApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
|
||||
ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.class, args);
|
||||
while(true) {
|
||||
String userName = applicationContext.getEnvironment().getProperty("user.name");
|
||||
String userAge = applicationContext.getEnvironment().getProperty("user.age");
|
||||
@@ -251,7 +229,7 @@ To switch to the production environment, you only need to change the parameter o
|
||||
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:
|
||||
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"]
|
||||
----
|
||||
@@ -359,4 +337,88 @@ we agree on the following priority between the shared configurations: Priorities
|
||||
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.
|
||||
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.
|
||||
|
||||
=== Nacos Config Endpoint
|
||||
|
||||
Nacos Config provides an Endpoint internally with a corresponding endpoint id of `nacos-config`.
|
||||
|
||||
Endpoint exposed json contains three properties:
|
||||
|
||||
1. Sources: Current application configuration data information
|
||||
|
||||
2. RefreshHistory: Configuration refresh history
|
||||
|
||||
3. NacosConfigProperties: Shows the current basic Nacos configurations of the current service
|
||||
|
||||
The followings shows how a service instance accesses the Endpoint:
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"NacosConfigProperties": {
|
||||
"serverAddr": "127.0.0.1:8848",
|
||||
"encode": null,
|
||||
"group": "DEFAULT_GROUP",
|
||||
"prefix": null,
|
||||
"fileExtension": "properties",
|
||||
"timeout": 3000,
|
||||
"endpoint": null,
|
||||
"namespace": null,
|
||||
"accessKey": null,
|
||||
"secretKey": null,
|
||||
"contextPath": null,
|
||||
"clusterName": null,
|
||||
"name": null,
|
||||
"sharedDataids": "base-common.properties,common.properties",
|
||||
"refreshableDataids": "common.properties",
|
||||
"extConfig": null
|
||||
},
|
||||
"RefreshHistory": [{
|
||||
"timestamp": "2019-07-29 11:20:04",
|
||||
"dataId": "nacos-config-example.properties",
|
||||
"md5": "7d5d7f1051ff6571e2ec9f90887d9d91"
|
||||
}],
|
||||
"Sources": [{
|
||||
"lastSynced": "2019-07-29 11:19:04",
|
||||
"dataId": "common.properties"
|
||||
}, {
|
||||
"lastSynced": "2019-07-29 11:19:04",
|
||||
"dataId": "base-common.properties"
|
||||
}, {
|
||||
"lastSynced": "2019-07-29 11:19:04",
|
||||
"dataId": "nacos-config-example.properties"
|
||||
}]
|
||||
}
|
||||
----
|
||||
|
||||
|
||||
=== Disable Nacos Config AutoConfiguration
|
||||
|
||||
set spring.cloud.nacos.config.enabled = false to disable Spring Cloud Nacos Config AutoConfiguration.
|
||||
|
||||
=== More Information about Nacos Config Starter Configurations
|
||||
|
||||
The following shows the other configurations of the starter of Nacos Config:
|
||||
|
||||
:frame: topbot
|
||||
[width="60%",options="header"]
|
||||
|====
|
||||
^|Configuration ^|Key ^|Default Value ^|Description
|
||||
|Server address|`spring.cloud.nacos.config.server-addr`|| IP and port of the Nacos Server listener
|
||||
|Dataid from nacos config|`spring.cloud.nacos.config.name`|| First take the prefix, then go to the name, and finally take spring.application.name
|
||||
|Dataid from nacos config|`spring.cloud.nacos.config.prefix`|| First take the prefix, then go to the name, and finally take spring.application.name
|
||||
|Encode for nacos config content|`spring.cloud.nacos.config.encode`||Encode for nacos config content
|
||||
|GROUP for nacos config|`spring.cloud.nacos.config.group`|`DEFAULT_GROUP`|GROUP for nacos config
|
||||
|The suffix of nacos config dataId, also the file extension of config content.|`spring.cloud.nacos.config.fileExtension`|`properties`|The suffix of nacos config dataId, also the file extension of config content(now support properties or yaml(yml))
|
||||
|Timeout for get config from nacos|`spring.cloud.nacos.config.timeout`|`3000`|Timeout for get config from nacos
|
||||
|Endpoint|`spring.cloud.nacos.config.endpoint`||Endpoint
|
||||
|Namespace|`spring.cloud.nacos.config.namespace`||Namespace
|
||||
|AccessKey|`spring.cloud.nacos.config.accessKey`||Alibaba Cloud account accesskey
|
||||
|SecretKey|`spring.cloud.nacos.config.secretKey`||Alibaba Cloud account secretkey
|
||||
|The context path of Nacos Server|`spring.cloud.nacos.config.contextPath`||The context path of Nacos Server
|
||||
|Cluster name|`spring.cloud.nacos.config.clusterName`||Cluster name
|
||||
|Dataid for Shared Configuration|`spring.cloud.nacos.config.sharedDataids`||Dataid for Shared Configuration, split by ","
|
||||
|Dynamic refresh dataid for Shared Configuration|`spring.cloud.nacos.config.refreshableDataids`||Dynamic refresh dataid for Shared Configuration, split by ","
|
||||
|custom dataid|`spring.cloud.nacos.config.extConfig`||It's a List,build up by `Config` POJO. `Config` has 3 attributes, `dataId`, `group` and `refresh`
|
||||
|====
|
@@ -1,52 +1,47 @@
|
||||
== 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.
|
||||
Nacos is an easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications.
|
||||
|
||||
=== Service Registration and Discovery: Nacos Discovery Starter
|
||||
With Spring Cloud Alibaba Nacos Discovery, you can quickly access the Nacos service registration feature based on Spring Cloud's programming model.
|
||||
|
||||
=== Service Registration/Discovery: Nacos Discovery
|
||||
|
||||
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]。
|
||||
Nacos Discovery 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 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
|
||||
=== How to Introduce Nacos Discovery for service registration/discovery
|
||||
|
||||
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:
|
||||
please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alibaba-nacos-discovery`.
|
||||
|
||||
[source,xml,indent=0]
|
||||
----
|
||||
<! -- dependency management-->
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<! -- dependencies -->
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
=== An example of using Nacos Discovery for service registration/discovery and call
|
||||
|
||||
Nacos Discovery integrate with the Netflix Ribbon, RestTemplate or OpenFeign can be used for service-to-service calls.
|
||||
|
||||
==== Nacos Server Startup
|
||||
|
||||
For details about how to download and start Nacos, refer to the https://nacos.io/zh-cn/docs/quick-start.html[Nacos Website].
|
||||
|
||||
After Nacos Server starts, go to http://ip:8848 to view the console (default account name/password is nacos/nacos):
|
||||
|
||||
.Nacos Dashboard
|
||||
image::https://img.alicdn.com/tfs/TB1XEfwbQH0gK0jSZPiXXavapXa-2790-1060.png[]
|
||||
|
||||
For more Nacos Server versions, you can download the latest version from https://github.com/alibaba/nacos/releases[release page].
|
||||
|
||||
==== 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:
|
||||
* Configuration of pom.xml The following is a complete example of pom.xml:
|
||||
[source, xml]
|
||||
----
|
||||
<?xml version="1.0" encoding="UTF-8"? >
|
||||
@@ -62,7 +57,7 @@ The following sample illustrates how to register a service to Nacos.
|
||||
<parent>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-parent</artifactId>
|
||||
<version>2.0.6.RELEASE</version>
|
||||
<version>${spring.boot.version}</version>
|
||||
<relativePath/>
|
||||
</parent>
|
||||
|
||||
@@ -77,14 +72,14 @@ The following sample illustrates how to register a service to Nacos.
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-dependencies</artifactId>
|
||||
<version>Finchley.SR1</version>
|
||||
<version>${spring.cloud.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<version>${spring.cloud.alibaba.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -103,7 +98,7 @@ The following sample illustrates how to register a service to Nacos.
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
@@ -119,7 +114,7 @@ The following sample illustrates how to register a service to Nacos.
|
||||
</project>
|
||||
----
|
||||
|
||||
2. Configuration of application.properties Some of the basic configurations of Nacos must be included in application.properties(or application.yaml), as shown below:
|
||||
* 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]
|
||||
----
|
||||
@@ -132,7 +127,7 @@ 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:
|
||||
* The following is a sample for starting Provider:
|
||||
[source,java,indent=0]
|
||||
----
|
||||
@SpringBootApplication
|
||||
@@ -157,15 +152,78 @@ 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
|
||||
==== Start a Consumer Application
|
||||
|
||||
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:
|
||||
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.
|
||||
|
||||
1. Subscribe: Shows the current service subscribers
|
||||
2. NacosDiscoveryProperties: Shows the current basic Nacos configurations of the current service
|
||||
NOTE: You can also access the service by using RestTemplate and FeignClient with load balancing.
|
||||
|
||||
The followings shows how a service instance accesses the EndPoint:
|
||||
[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 path = String.format("http://%s:%s/echo/%s",serviceInstance.getHost(),serviceInstance.getPort(),appName);
|
||||
System.out.println("request path:" +path);
|
||||
return restTemplate.getForObject(path,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
|
||||
|
||||
|
||||
=== Nacos Discovery Endpoint
|
||||
|
||||
Nacos Discovery provides an Endpoint internally with a corresponding endpoint id of `nacos-discovery`.
|
||||
|
||||
Endpoint exposed json contains two properties:
|
||||
|
||||
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]
|
||||
----
|
||||
@@ -232,86 +290,26 @@ The followings shows how a service instance accesses the EndPoint:
|
||||
}
|
||||
----
|
||||
|
||||
=== Start a Consumer Application
|
||||
=== More Information about Nacos Discovery Starter Configurations
|
||||
|
||||
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:
|
||||
The following shows the other configurations of the starter of 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`
|
||||
|Server address|`spring.cloud.nacos.discovery.server-addr`||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`||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`||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`||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`||Alibaba Cloud account accesskey
|
||||
|SecretKey|`spring.cloud.nacos.discovery.secret-key`||Alibaba Cloud account secretkey
|
||||
|Metadata|`spring.cloud.nacos.discovery.metadata`||You can define some of the metadata for your services in the Map format
|
||||
|Log file name|`spring.cloud.nacos.discovery.log-name`||
|
||||
|Endpoint|`spring.cloud.nacos.discovery.endpoint`||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
|
||||
|Enable Nacos Watch|`spring.cloud.nacos.discovery.watch.enabled`|`true`|set to false to close watch
|
||||
|====
|
||||
|
||||
|
@@ -11,9 +11,9 @@ We’ve released Spring Cloud Alibaba version 0.2.1. You will need to add depend
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<version>0.2.2.BUILD-SNAPSHOT</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
@@ -26,7 +26,7 @@ Next we need to introduce Spring Cloud Alibaba Cloud OSS Starter.
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
|
@@ -86,7 +86,7 @@ There are two concepts in Spring Cloud Stream: Binder and Binding
|
||||
|
||||
For example, `Kafka` uses `KafkaMessageChannelBinder`, `RabbitMQ` uses `RabbitMessageChannelBinder`, while `RocketMQ` uses `RocketMQMessageChannelBinder`.
|
||||
|
||||
* Binding: Includes Input Binding and Output Binding。
|
||||
* 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.
|
||||
|
||||
@@ -114,137 +114,169 @@ All the message types in this code are provided by the `spring-messaging`module.
|
||||
|
||||
**The lower layer of Spring Cloud Stream also implements various code abstractions based on the previous code.**
|
||||
|
||||
### How to use Spring Cloud Alibaba RocketMQ Binder ###
|
||||
|
||||
For using the Spring Cloud Alibaba RocketMQ Binder, you just need to add it to your Spring Cloud Stream application, using the following Maven coordinates:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-stream-binder-rocketmq</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
Alternatively, you can also use the Spring Cloud Stream RocketMQ Starter:
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### 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[]
|
||||
This is the implementation architecture of Spring Cloud Stream RocketMQ Binder:
|
||||
|
||||
.SCS RocketMQ Binder
|
||||
image::https://img.alicdn.com/tfs/TB1v8rcbUY1gK0jSZFCXXcwqXXa-1236-773.png[]
|
||||
|
||||
The core of RocketMQ Binder are the 3 classes below: `RocketMQMessageChannelBinder`,`RocketMQInboundChannelAdapter` and `RocketMQMessageHandler`.
|
||||
The implementation of RocketMQ Binder depend on the https://github.com/apache/rocketmq-spring[RocketMQ-Spring] framework.
|
||||
|
||||
`RocketMQMessageChannelBinder` is a standard implementation of Binder. It contains `RocketMQInboundChannelAdapter` and `RocketMQMessageHandler` as its internal constructions.
|
||||
RocketMQ Spring framework is an integration of RocketMQ and Spring Boot. It provides three main features:
|
||||
|
||||
`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.
|
||||
1. `RocketMQTemplate`: Sending messages, including synchronous, asynchronous, and transactional messages.
|
||||
2. `@RocketMQTransactionListener`: Listen and check for transaction messages.
|
||||
3. `@RocketMQMessageListener`: Consume messages.
|
||||
|
||||
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.
|
||||
`RocketMQMessageChannelBinder` is a standard implementation of Binder, it will build `RocketMQInboundChannelAdapter` and `RocketMQMessageHandler` internally.
|
||||
|
||||
`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].
|
||||
`RocketMQMessageHandler` will construct `RocketMQTemplate` based on the Binding configuration. `RocketMQTemplate` will convert the `org.springframework.messaging.Message` message class of `spring-messaging` module to the RocketMQ message class `org.apache.rocketmq.common .message.Message` internally, then send it out.
|
||||
|
||||
You can also obtain `Acknowledgement` from the Header and make some configurations.
|
||||
`RocketMQInboundChannelAdapter` will also construct `RocketMQListenerBindingContainer` based on the Binding configuration, and `RocketMQListenerBindingContainer` will start the RocketMQ `Consumer` to receive the messages.
|
||||
|
||||
For example, you can set delayed message consumption when `MessageListenerConcurrently` is used for asynchronous message consumption:
|
||||
NOTE: RocketMQ Binder Application can also be used to configure rocketmq.** to trigger RocketMQ Spring related AutoConfiguration
|
||||
|
||||
Currently Binder supports setting the relevant key in `Header` to set the properties of the RocketMQ message.
|
||||
|
||||
For example, `TAGS`, `DELAY`, `TRANSACTIONAL_ARG`, `KEYS`, `WAIT_STORE_MSG_OK`, `FLAG` represent the labels corresponding to the RocketMQ message.
|
||||
|
||||
```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);
|
||||
}
|
||||
MessageBuilder builder = MessageBuilder.withPayload(msg)
|
||||
.setHeader(RocketMQHeaders.TAGS, "binder")
|
||||
.setHeader(RocketMQHeaders.KEYS, "my-key")
|
||||
.setHeader("DELAY", "1");
|
||||
Message message = builder.build();
|
||||
output().send(message);
|
||||
```
|
||||
|
||||
You can also set delayed message consumption when `MessageListenerOrderly` is used for consuming ordered messages.
|
||||
### Configuration Options
|
||||
|
||||
```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);
|
||||
}
|
||||
```
|
||||
#### RocketMQ Binder Properties
|
||||
|
||||
Supported Configurations of Provider:
|
||||
spring.cloud.stream.rocketmq.binder.name-server::
|
||||
The name server of RocketMQ Server(Older versions use the namesrv-addr configuration item).
|
||||
+
|
||||
Default: `127.0.0.1:9876`.
|
||||
spring.cloud.stream.rocketmq.binder.access-key::
|
||||
The AccessKey of Alibaba Cloud Account.
|
||||
+
|
||||
Default: null.
|
||||
spring.cloud.stream.rocketmq.binder.secret-key::
|
||||
The SecretKey of Alibaba Cloud Account.
|
||||
+
|
||||
Default: null.
|
||||
spring.cloud.stream.rocketmq.binder.enable-msg-trace::
|
||||
Enable Message Trace feature for all producers and consumers.
|
||||
+
|
||||
Default: `true`.
|
||||
spring.cloud.stream.rocketmq.binder.customized-trace-topic::
|
||||
The trace topic for message trace.
|
||||
+
|
||||
Default: `RMQ_SYS_TRACE_TOPIC`.
|
||||
|
||||
: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:
|
||||
#### RocketMQ Consumer Properties
|
||||
|
||||
: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
|
||||
|====
|
||||
The following properties are available for RocketMQ producers only and must be prefixed with `spring.cloud.stream.rocketmq.bindings.<channelName>.consumer.`.
|
||||
|
||||
### Endpoint Support
|
||||
enable::
|
||||
Enable Consumer Binding.
|
||||
+
|
||||
Default: `true`.
|
||||
tags::
|
||||
Consumer subscription tags expression, tags split by `||`.
|
||||
+
|
||||
Default: empty.
|
||||
sql::
|
||||
Consumer subscription sql expression.
|
||||
+
|
||||
Default: empty.
|
||||
broadcasting::
|
||||
Control message mode, if you want all subscribers receive message all message, broadcasting is a good choice.
|
||||
+
|
||||
Default: `false`.
|
||||
orderly::
|
||||
Receiving message concurrently or orderly.
|
||||
+
|
||||
Default: `false`.
|
||||
delayLevelWhenNextConsume::
|
||||
Message consume retry strategy for concurrently consume:
|
||||
* -1,no retry,put into DLQ directly
|
||||
* 0,broker control retry frequency
|
||||
* >0,client control retry frequency
|
||||
+
|
||||
Default: `0`.
|
||||
suspendCurrentQueueTimeMillis::
|
||||
Time interval of message consume retry for orderly consume.
|
||||
+
|
||||
Default: `1000`.
|
||||
|
||||
Before you use the Endpoint feature, please add the `spring-boot-starter-actuator` dependency in Maven, and enable access of Endpoints in your configuration.
|
||||
#### RocketMQ Provider Properties
|
||||
|
||||
* 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`
|
||||
The following properties are available for RocketMQ producers only and must be prefixed with `spring.cloud.stream.rocketmq.bindings.<channelName>.producer.`.
|
||||
|
||||
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"
|
||||
}
|
||||
```
|
||||
enable::
|
||||
Enable Producer Binding.
|
||||
+
|
||||
Default: `true`.
|
||||
group::
|
||||
Producer group name.
|
||||
+
|
||||
Default: empty.
|
||||
maxMessageSize::
|
||||
Maximum allowed message size in bytes.
|
||||
+
|
||||
Default: `8249344`.
|
||||
transactional::
|
||||
Send Transactional Message.
|
||||
+
|
||||
Default: `false`.
|
||||
sync::
|
||||
Send message in synchronous mode.
|
||||
+
|
||||
Default: `false`.
|
||||
vipChannelEnabled::
|
||||
Send message with vip channel.
|
||||
+
|
||||
Default: `true`.
|
||||
sendMessageTimeout::
|
||||
Millis of send message timeout.
|
||||
+
|
||||
Default: `3000`.
|
||||
compressMessageBodyThreshold::
|
||||
Compress message body threshold, namely, message body larger than 4k will be compressed on default.
|
||||
+
|
||||
Default: `4096`.
|
||||
retryTimesWhenSendFailed::
|
||||
Maximum number of retry to perform internally before claiming sending failure in synchronous mode.
|
||||
+
|
||||
Default: `2`.
|
||||
retryTimesWhenSendAsyncFailed::
|
||||
Maximum number of retry to perform internally before claiming sending failure in asynchronous mode.
|
||||
+
|
||||
Default: `2`.
|
||||
retryNextServer::
|
||||
Indicate whether to retry another broker on sending failure internally.
|
||||
+
|
||||
Default: `false`.
|
@@ -4,29 +4,12 @@ SchedulerX(Distributed job scheduling) is a component of EDAS, an Alibaba Cl
|
||||
|
||||
=== 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]
|
||||
----
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
|
||||
<version>0.2.1.RELEASE</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
----
|
||||
|
||||
Next we need to introduce Spring Cloud AliCloud SchedulerX Starter.
|
||||
If you want to use SchedulerX in your project, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alicloud-schedulerX`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-schedulerX</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
@@ -128,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.
|
||||
Domain-name is not mandatory. You can refer to https://help.aliyun.com/document_detail/35359.html[SchedulerX Documentation] for details.
|
@@ -14,11 +14,11 @@ https://github.com/alibaba/Sentinel[Sentinel] has the following features:
|
||||
|
||||
### 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`.
|
||||
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`.
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
@@ -98,27 +98,20 @@ 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].
|
||||
|
||||
### Feign Support
|
||||
### OpenFeign 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:
|
||||
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:
|
||||
|
||||
* 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`:
|
||||
* Add the `openfeign starter` dependency to trigger and enable `sentinel starter`:
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
* 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
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
This is an interface for `FeignClient`:
|
||||
This is a simple usage of `FeignClient`:
|
||||
|
||||
```java
|
||||
@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
|
||||
@@ -142,12 +135,10 @@ class EchoServiceFallback implements EchoService {
|
||||
}
|
||||
```
|
||||
|
||||
NOTE: The resource name policy in the corresponding interface of Feign is:httpmethod:protocol://requesturl
|
||||
NOTE: The resource name policy in the corresponding interface of Feign is:httpmethod:protocol://requesturl. All the attributes in the `@FeignClient` annotation is supported by Sentinel.
|
||||
|
||||
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.
|
||||
@@ -160,14 +151,13 @@ public RestTemplate restTemplate() {
|
||||
}
|
||||
```
|
||||
|
||||
The parameter of the `@SentinelRestTemplate` annotation support flow control(`blockHandler`, `blockHandlerClass`) and circuit breaking(`fallback`, `fallbackClass`).
|
||||
The attribute of the `@SentinelRestTemplate` annotation support flow control(`blockHandler`, `blockHandlerClass`) and circuit breaking(`fallback`, `fallbackClass`).
|
||||
|
||||
==
|
||||
|
||||
The `blockHandler` or `fallback` is the static method of `blockHandlerClass` or `fallbackClass`.
|
||||
|
||||
The parameter of method in `@SentinelRestTemplate` is same as `ClientHttpRequestInterceptor`, but it has one more parameter `BlockException` and its value of return type should be `ClientHttpResponse`.
|
||||
If you do not continue to execute the following Http request interceptor after being restricted, you can use the instance of `SentinelClientHttpResponse` to customize the return value result after the current limit.
|
||||
The parameter and return value of method in `@SentinelRestTemplate` is same as `org.springframework.http.client.ClientHttpRequestInterceptor#interceptor`, but it has one more parameter `BlockException` to catch the exception by Sentinel.
|
||||
|
||||
The method signature of `handleException` in `ExceptionUtil` above should be like this:
|
||||
|
||||
@@ -179,130 +169,192 @@ public class ExceptionUtil {
|
||||
}
|
||||
```
|
||||
|
||||
It will return `RestTemplate request block by sentinel` when you do not write any flow control(`blockHandler`, `blockHandlerClass`) configuration or circuit breaking configuration(`fallback`, `fallbackClass`), you can override it by using your own method.
|
||||
NOTE: When the application starts, it will check if the `@SentinelRestTemplate` annotation corresponding to the flow control or circuit breaking method exists, if it does not exist, it will throw an exception.
|
||||
|
||||
The attribute of the `@SentinelRestTemplate` annotation is optional.
|
||||
|
||||
It will return `RestTemplate request block by sentinel` when you using `RestTemplate` blocked by Sentinel. You can override it by your own logic. We provide `SentinelClientHttpResponse` to handle the response.
|
||||
|
||||
Sentinel RestTemplate provides two granularities for resource rate limiting:
|
||||
|
||||
* `schema://host:port/path`: Protocol, host, port and path
|
||||
* `httpmethod:schema://host:port/path`: Protocol, host, port and path
|
||||
|
||||
* `schema://host:port`: Protocol, host and port
|
||||
* `httpmethod: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` and `https://www.taobao.com/test`.
|
||||
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
|
||||
|
||||
#### The usage of our first version 0.2.0.RELEASE or 0.1.0.RELEASE
|
||||
|
||||
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<String, List<FlowRule>> {
|
||||
@Override
|
||||
public List<FlowRule> convert(String source) {
|
||||
return JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
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
|
||||
```
|
||||
|
||||
#### The usage after first version
|
||||
|
||||
You only need to complete 1 step to configure your data source:
|
||||
|
||||
* Configure your data source in the `application.properties` file directly.
|
||||
`SentinelProperties` provide `datasource` attribute to configure datasource.
|
||||
|
||||
For example, 4 data sources are configures:
|
||||
|
||||
```
|
||||
spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
|
||||
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
|
||||
|
||||
#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
|
||||
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
|
||||
#spring.cloud.sentinel.datasource.ds1.file.converter-class=JsonFlowRuleListConverter
|
||||
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
|
||||
|
||||
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-id=sentinel
|
||||
spring.cloud.sentinel.datasource.ds2.nacos.group-id=DEFAULT_GROUP
|
||||
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
|
||||
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade
|
||||
|
||||
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.ds3.zk.rule-type=authority
|
||||
|
||||
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
|
||||
|
||||
spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow
|
||||
```
|
||||
|
||||
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`.
|
||||
Every data source has 3 common configuration items: `data-type`, `converter-class` and `rule-type`.
|
||||
|
||||
`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.
|
||||
`data-type` refers to `Converter`. Spring Cloud Alibaba Sentinel provides two embedded values by default: `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`, `ParamFlowRule`).
|
||||
|
||||
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
|
||||
```
|
||||
`rule-type` refers to the rule type in datasource(`flow`,`degrade`,`authority`,`system`, `param-flow`, `gw-flow`, `gw-api-group`).
|
||||
|
||||
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
|
||||
### Support Zuul
|
||||
|
||||
Before you use the Endpoint feature, please add the `spring-boot-starter-actuator` dependency in Maven, and enable access of Endpoints in your configuration.
|
||||
https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流]
|
||||
|
||||
* 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`.
|
||||
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:
|
||||
|
||||
### More
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
### Sentinel Endpoint
|
||||
|
||||
Sentinel provides an Endpoint internally with a corresponding endpoint id of `sentinel`.
|
||||
|
||||
Endpoint exposed json contains multi properties:
|
||||
|
||||
1. appName: application name
|
||||
2. logDir: the directory of log
|
||||
3. logUsePid: log name with pid ot not
|
||||
4. blockPage: redirect page after sentinel block
|
||||
5. metricsFileSize: the size of metrics file
|
||||
6. metricsFileCharset: metrics file charset
|
||||
7. totalMetricsFileCount: the total file count of of metrics file
|
||||
8. consoleServer: sentinel dashboard address
|
||||
9. clientIp: client ip
|
||||
10. heartbeatIntervalMs: client heartbeat interval with dashboard
|
||||
11. clientPort: the client needs to expose the port to interact with the dashboard
|
||||
12. coldFactor: cold factor
|
||||
13. filter: CommonFilter related properties, such as order, urlPatterns and enable
|
||||
14. datasource: datasource configuration info by client
|
||||
15. rules: the rule that the client takes effect internally contains flowRules, degradeRules, systemRules, authorityRule, paramFlowRule
|
||||
|
||||
The followings shows how a service instance accesses the Endpoint:
|
||||
|
||||
[source,json,indent=0]
|
||||
----
|
||||
{
|
||||
"blockPage": null,
|
||||
"appName": "sentinel-example",
|
||||
"consoleServer": "localhost:8080",
|
||||
"coldFactor": "3",
|
||||
"rules": {
|
||||
"flowRules": [{
|
||||
"resource": "GET:http://www.taobao.com",
|
||||
"limitApp": "default",
|
||||
"grade": 1,
|
||||
"count": 0.0,
|
||||
"strategy": 0,
|
||||
"refResource": null,
|
||||
"controlBehavior": 0,
|
||||
"warmUpPeriodSec": 10,
|
||||
"maxQueueingTimeMs": 500,
|
||||
"clusterMode": false,
|
||||
"clusterConfig": null
|
||||
}, {
|
||||
"resource": "/test",
|
||||
"limitApp": "default",
|
||||
"grade": 1,
|
||||
"count": 0.0,
|
||||
"strategy": 0,
|
||||
"refResource": null,
|
||||
"controlBehavior": 0,
|
||||
"warmUpPeriodSec": 10,
|
||||
"maxQueueingTimeMs": 500,
|
||||
"clusterMode": false,
|
||||
"clusterConfig": null
|
||||
}, {
|
||||
"resource": "/hello",
|
||||
"limitApp": "default",
|
||||
"grade": 1,
|
||||
"count": 1.0,
|
||||
"strategy": 0,
|
||||
"refResource": null,
|
||||
"controlBehavior": 0,
|
||||
"warmUpPeriodSec": 10,
|
||||
"maxQueueingTimeMs": 500,
|
||||
"clusterMode": false,
|
||||
"clusterConfig": null
|
||||
}]
|
||||
},
|
||||
"metricsFileCharset": "UTF-8",
|
||||
"filter": {
|
||||
"order": -2147483648,
|
||||
"urlPatterns": ["/*"],
|
||||
"enabled": true
|
||||
},
|
||||
"totalMetricsFileCount": 6,
|
||||
"datasource": {
|
||||
"ds1": {
|
||||
"file": {
|
||||
"dataType": "json",
|
||||
"ruleType": "FLOW",
|
||||
"converterClass": null,
|
||||
"file": "...",
|
||||
"charset": "utf-8",
|
||||
"recommendRefreshMs": 3000,
|
||||
"bufSize": 1048576
|
||||
},
|
||||
"nacos": null,
|
||||
"zk": null,
|
||||
"apollo": null,
|
||||
"redis": null
|
||||
}
|
||||
},
|
||||
"clientIp": "30.5.121.91",
|
||||
"clientPort": "8719",
|
||||
"logUsePid": false,
|
||||
"metricsFileSize": 52428800,
|
||||
"logDir": "...",
|
||||
"heartbeatIntervalMs": 10000
|
||||
}
|
||||
----
|
||||
|
||||
### Configuration
|
||||
|
||||
The following table shows that when there are corresponding bean types in `ApplicationContext`, some actions will be taken:
|
||||
|
||||
@@ -312,6 +364,7 @@ The following table shows that when there are corresponding bean types in `Appli
|
||||
^|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
|
||||
|`RequestOriginParser`|`WebCallbackManager.setRequestOriginParser(requestOriginParser)`|Setting the origin
|
||||
|====
|
||||
|
||||
The following table shows all the configurations of Spring Cloud Alibaba Sentinel:
|
||||
@@ -320,18 +373,27 @@ The following table shows all the configurations of Spring Cloud Alibaba Sentine
|
||||
[width="60%",options="header"]
|
||||
|====
|
||||
^|Configuration ^|Description ^|Default Value
|
||||
|`spring.application.name` or `project.name`|Project Name Of Sentinel|
|
||||
|`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.eager`|Whether to trigger Sentinel initialization in advance|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|8719
|
||||
|`spring.cloud.sentinel.transport.dashboard`|Sentinel dashboard address|
|
||||
|`spring.cloud.sentinel.transport.heartbeatIntervalMs`|Hearbeat interval between the application and Sentinel dashboard|
|
||||
|`spring.cloud.sentinel.transport.client-ip`|The client IP of this configuration will be registered to the Sentinel Server side.|
|
||||
|`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.filter.url-patterns`|Data type is array. Refers to the collection of Servlet Filter ULR patterns|/*
|
||||
|`spring.cloud.sentinel.filter.enabled`|Enable to instance CommonFilter|true
|
||||
|`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
|
||||
|`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[ColdFactor] |3
|
||||
|`spring.cloud.sentinel.zuul.order.pre`| The order of SentinelZuulPreFilter | 10000
|
||||
|`spring.cloud.sentinel.zuul.order.post`| The order of SentinelZuulPostFilter | 1000
|
||||
|`spring.cloud.sentinel.zuul.order.error`| The order of SentinelZuulErrorFilter | -1
|
||||
|====
|
||||
|
||||
|
||||
NOTE: These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations.
|
209
spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc
Normal file
209
spring-cloud-alibaba-docs/src/main/asciidoc/sms.adoc
Normal file
@@ -0,0 +1,209 @@
|
||||
== Spring Cloud Alibaba Cloud SMS
|
||||
|
||||
SMS(Short Message Service)is a messaging service that covers the globe, Alibaba SMS provides convenient, efficient, and intelligent communication capabilities that help businesses quickly contact their customers.
|
||||
|
||||
Spring Cloud Alibaba Cloud SMS provide an easier-to-use API for quick access to Alibaba Cloud's SMS service based on Spring Cloud Alibaba SMS.
|
||||
|
||||
=== How to Introduce Spring Cloud Alibaba Cloud SMS
|
||||
|
||||
If you want to use SMS in your project, please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alicloud-sms`.
|
||||
|
||||
[source,xml]
|
||||
----
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alicloud-sms</artifactId>
|
||||
</dependency>
|
||||
----
|
||||
|
||||
=== How to use SMS API
|
||||
|
||||
==== Configure SMS
|
||||
|
||||
Before you start to use Spring Cloud Alibaba Cloud SMS, please add the following configurations in application.properties.
|
||||
|
||||
[source,properties]
|
||||
----
|
||||
spring.cloud.alicloud.access-key=AK
|
||||
spring.cloud.alicloud.secret-key=SK
|
||||
----
|
||||
|
||||
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.
|
||||
|
||||
==== Introduce SMS API
|
||||
|
||||
The SMS API in Spring Cloud Alicloud SMS is based on Alibaba Cloud SMS SDK. It has a single SMS sending, multiple SMS bulk sending, SMS query, SMS message (SMS receipt message and Upstream SMS message) class operation API.
|
||||
|
||||
The following is a simple example of how to use SMS api to send short message:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@SpringBootApplication
|
||||
public class SmsApplication {
|
||||
|
||||
@Autowired
|
||||
private ISmsService smsService;
|
||||
|
||||
@RequestMapping("/batch-sms-send.do")
|
||||
public SendBatchSmsResponse batchsendCheckCode(
|
||||
@RequestParam(name = "code") String code) {
|
||||
|
||||
SendSmsRequest request = new SendSmsRequest();
|
||||
// Required:the mobile number
|
||||
request.setPhoneNumbers("152******");
|
||||
// Required:SMS-SignName-could be found in sms console
|
||||
request.setSignName("******");
|
||||
// Required:Template-could be found in sms console
|
||||
request.setTemplateCode("******");
|
||||
// Required:The param of sms template.For exmaple, if the template is "Hello,your verification code is ${code}". The param should be like following value
|
||||
request.setTemplateParam("{\"code\":\"" + code + "\"}");
|
||||
SendSmsResponse sendSmsResponse ;
|
||||
try {
|
||||
sendSmsResponse = smsService.sendSmsRequest(request);
|
||||
}
|
||||
catch (ClientException e) {
|
||||
e.printStackTrace();
|
||||
sendSmsResponse = new SendSmsResponse();
|
||||
}
|
||||
return sendSmsResponse ;
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws URISyntaxException {
|
||||
SpringApplication.run(SmsApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
----
|
||||
|
||||
Before you send your messages, 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://dysms.console.aliyun.com/dysms.htm?spm=5176.8195934.1283918..18924183bHPct2&accounttraceid=c8cb4243-3080-4eb1-96b0-1f2316584269#/[Turn on SMS Service].
|
||||
|
||||
For more information about SMS , please refer to the SMS official https://help.aliyun.com/document_detail/55284.html?spm=a2c4g.11186623.6.568.715e4f30ZiVkbI[SMS] (SendSms)---JAVA] docs .
|
||||
|
||||
NOTE: Due to an issue with the earlier SMS sdk version, if the text message fails to be sent, please delete the line of code that contains the explicit MethodType as POST. If you still have problems, please contact us as soon as possible.
|
||||
|
||||
=== The Advanced Features of SMS Api
|
||||
|
||||
In order to reduce the cost of learning, the API interface of the Spring Cloud Alicloud SMS package is kept as consistent as the API and Example provided by the official website.
|
||||
|
||||
* Batch SMS sending
|
||||
|
||||
Refer to the following example to quickly develop a feature with bulk SMS sending. Add the following code in the Controller or create a new Controller:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@RequestMapping("/batch-sms-send.do")
|
||||
public SendBatchSmsResponse batchsendCheckCode(
|
||||
@RequestParam(name = "code") String code) {
|
||||
SendBatchSmsRequest request = new SendBatchSmsRequest();
|
||||
request.setMethod(MethodType.GET);
|
||||
request.setPhoneNumberJson("[\"177********\",\"130********\"]");
|
||||
request.setSignNameJson("[\"*******\",\"*******\"]");
|
||||
request.setTemplateCode("******");
|
||||
request.setTemplateParamJson(
|
||||
"[{\"code\":\"" + code + "\"},{\"code\":\"" + code + "\"}]");
|
||||
SendBatchSmsResponse sendSmsResponse ;
|
||||
try {
|
||||
sendSmsResponse = smsService
|
||||
.sendSmsBatchRequest(request);
|
||||
return sendSmsResponse;
|
||||
}
|
||||
catch (ClientException e) {
|
||||
e.printStackTrace();
|
||||
sendSmsResponse = new SendBatchSmsResponse();
|
||||
}
|
||||
return sendSmsResponse ;
|
||||
}
|
||||
----
|
||||
|
||||
NOTE: The MethodType of the request is set to GET, which is somewhat different from the example given by the official website. This is because the inconsistent version of the dependent Alibaba Cloud POP API version causes incompatibility issues, set to GET.
|
||||
|
||||
More parameter descriptions can be https://help.aliyun.com/document_detail/66041.html?spm=a2c4g.11186623.6.571.631315e8AauJhP[reference here]
|
||||
|
||||
* SMS Query
|
||||
|
||||
Refer to the following example to quickly develop a history of sending SMS messages based on a specified number. Add the following code in the Controller or create a new Controller:
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@RequestMapping("/query.do")
|
||||
public QuerySendDetailsResponse querySendDetailsResponse(
|
||||
@RequestParam(name = "tel") String telephone) {
|
||||
QuerySendDetailsRequest request = new QuerySendDetailsRequest();
|
||||
request.setPhoneNumber(telephone);
|
||||
request.setSendDate("20190103");
|
||||
request.setPageSize(10L);
|
||||
request.setCurrentPage(1L);
|
||||
try {
|
||||
QuerySendDetailsResponse response = smsService.querySendDetails(request);
|
||||
return response;
|
||||
}
|
||||
catch (ClientException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return new QuerySendDetailsResponse();
|
||||
}
|
||||
|
||||
----
|
||||
|
||||
More parameter descriptions can be found at https://help.aliyun.com/document_detail/55289.html?spm=a2c4g.11186623.6.569.4f852c78mugEfx[reference here]
|
||||
|
||||
* SMS receipt message
|
||||
|
||||
By subscribing to the SmsReport SMS status report, you can know the status of each SMS message and whether it knows the status and related information of the terminal user. These efforts have been encapsulated internally by Spring Cloud AliCloud SMS. You only need to complete the following two steps.
|
||||
|
||||
1、Configure the queue name for SmsReport in the `application.properties` configuration file (which can also be application.yaml).
|
||||
|
||||
.application.properties
|
||||
----
|
||||
spring.cloud.alicloud.sms.report-queue-name=Alicom-Queue-********-SmsReport
|
||||
----
|
||||
|
||||
2、Implement the SmsReportMessageListener interface and initialize a Spring Bean.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Component
|
||||
public class SmsReportMessageListener
|
||||
implements SmsReportMessageListener {
|
||||
|
||||
@Override
|
||||
public boolean dealMessage(Message message) {
|
||||
//do something
|
||||
System.err.println(this.getClass().getName() + "; " + message.toString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].
|
||||
|
||||
* Upstream SMS message
|
||||
|
||||
By subscribing to the SmsUp upstream SMS message, you can know the content of the end user replying to the SMS. These efforts have also been packaged by Spring Cloud AliCloud SMS. You only need to complete the following two steps.
|
||||
|
||||
1、Configure the queue name for SmsReport in the `application.properties` configuration file (which can also be application.yaml).
|
||||
|
||||
.application.properties
|
||||
----
|
||||
spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp
|
||||
----
|
||||
|
||||
2、Implement the SmsUpMessageListener interface and initialize a Spring Bean.
|
||||
|
||||
[source,java]
|
||||
----
|
||||
@Component
|
||||
public class SmsUpMessageListener
|
||||
implements org.springframework.cloud.alicloud.sms.SmsUpMessageListener {
|
||||
|
||||
@Override
|
||||
public boolean dealMessage(Message message) {
|
||||
//do something
|
||||
System.err.println(this.getClass().getName() + "; " + message.toString());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
----
|
||||
|
||||
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].
|
@@ -1,17 +1,13 @@
|
||||
[[spring-cloud-alibaba-reference]]
|
||||
= Spring Cloud Alibaba Reference Documentation
|
||||
xiaojing; xiaolongzuo; jim fang; bingting peng; wangyuxin
|
||||
Jim Fang, Jing Xiao, Mercy Ma, Xiaolong Zuo, Bingting Peng, Yuxin Wang
|
||||
:doctype: book
|
||||
:toc:
|
||||
:toclevels: 4
|
||||
:source-highlighter: prettify
|
||||
:numbered:
|
||||
|
||||
== Introduction
|
||||
|
||||
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 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::introduction.adoc[]
|
||||
|
||||
include::dependency-management.adoc[]
|
||||
|
||||
@@ -29,4 +25,6 @@ include::acm.adoc[]
|
||||
|
||||
include::oss.adoc[]
|
||||
|
||||
include::schedulerx.adoc[]
|
||||
include::schedulerx.adoc[]
|
||||
|
||||
include::sms.adoc[]
|
Reference in New Issue
Block a user