File: README.md
Spring Cloud Alibaba
A project maintained by Alibaba.
See the 中文文档 for Chinese readme.
Spring Cloud Alibaba provides a one-stop solution for distributed application development. It contains all the components required to develop distributed applications, making it easy for you to develop your applications using Spring Cloud.
With Spring Cloud Alibaba, you only need to add some annotations and a small amount of configurations to connect Spring Cloud applications to the distributed solutions of Alibaba, and build a distributed application system with Alibaba middleware.
Features
- Flow control and service degradation: Flow control for HTTP services is supported by default. You can also customize flow control and service degradation rules using annotations. The rules can be changed dynamically.
- Service registration and discovery: Service can be registered and clients can discover the instances using Spring-managed beans. Load balancing is consistent with that supported by the corresponding Spring Cloud.
- Distributed configuration: Support for externalized configuration in a distributed system, auto refresh when configuration changes.
- Event-driven: Support for building highly scalable event-driven microservices connected with shared messaging systems.
- Distributed Transaction: Support for distributed transaction solution with high performance and ease of use.
- 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.
- Alibaba Cloud SchedulerX: Accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds.
- Alibaba Cloud SMS: A messaging service that covers the globe, Alibaba SMS provides convenient, efficient, and intelligent communication capabilities that help businesses quickly contact their customers.
For more features, please refer to Roadmap.
In addition to the above-mentioned features, for the needs of enterprise users' scenarios, Microservices Engine (MSE) of Spring Cloud Alibaba's enterprise version provides an enterprise-level microservices governance center, which includes more powerful governance capabilities such as Grayscale Release, Service Warm-up, Lossless Online and Offline and Outlier Ejection. At the same time, it also provides a variety of products and solutions such as enterprise-level Nacos registration / configuration center, enterprise-level cloud native gateway.
Components
Sentinel: Sentinel takes "traffic flow" as the breakthrough point, and provides solutions in areas such as flow control, concurrency, circuit breaking, and load protection to protect service stability.
Nacos: An easy-to-use dynamic service discovery, configuration and service management platform for building cloud native applications.
RocketMQ: A distributed messaging and streaming platform with low latency, high performance and reliability, trillion-level capacity and flexible scalability.
Seata: A distributed transaction solution with high performance and ease of use for microservices architecture.
Alibaba Cloud OSS: An encrypted and secure cloud storage service which stores, processes and accesses massive amounts of data from anywhere in the world.
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.
Alibaba Cloud SchedulerX: Accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds.
For more features please refer to Roadmap.
How to build
- 2025.1.x branch: Corresponds to Spring Cloud 2025.1.x & Spring Boot 4.0.x, JDK 17 or later versions are supported.
- 2025.0.x branch: Corresponds to Spring Cloud 2025.0.x & Spring Boot 3.5.x, JDK 17 or later versions are supported.
- 2023.x branch: Corresponds to Spring Cloud 2023 & Spring Boot 3.2.x, JDK 17 or later versions are supported.
- 2022.x branch: Corresponds to Spring Cloud 2022 & Spring Boot 3.0.x, JDK 17 or later versions are supported.
- 2021.x branch: Corresponds to Spring Cloud 2021 & Spring Boot 2.6.x. JDK 1.8 or later versions are supported.
- 2020.0 branch: Corresponds to Spring Cloud 2020 & Spring Boot 2.4.x. JDK 1.8 or later versions are supported.
- 2.2.x branch: Corresponds to Spring Cloud Hoxton & Spring Boot 2.2.x. JDK 1.8 or later versions are supported.
- greenwich branch: Corresponds to Spring Cloud Greenwich & Spring Boot 2.1.x. JDK 1.8 or later versions are supported.
- finchley branch: Corresponds to Spring Cloud Finchley & Spring Boot 2.0.x. JDK 1.8 or later versions are supported.
- 1.x branch: Corresponds to Spring Cloud Edgware & Spring Boot 1.x, JDK 1.7 or later versions are supported.
Spring Cloud uses Maven for most build-related activities, and you should be able to get off the ground quite quickly by cloning the project you are interested in and typing:
./mvnw installHow to Use
Add maven dependency
Release Version
These artifacts are available from Maven Central and Spring Release repository via BOM:
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2025.1.0.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>add the module in dependencies. If you want to choose an older version, you can refer to the Release Notes.
Snapshot
If you need to use the already published Snapshot Version, add the following configuration in the dependencyManagement.
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2025.1.0.1-SNAPSHOT</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>Add the following configuration in repositories.
If users in China have difficulty accessing the maven.pkg.github.com domain, consider using Alibaba Cloud Effect Artifact Repository as a proxy for GitHub Packages.
<repositories>
<repository>
github
https://maven.pkg.github.com/alibaba/spring-cloud-alibaba
<releases>
<enabled>false</enabled>
</releases>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>Add the following configuration in settings.xml.
<servers>
<server>
github
Your GitHub Username
Your GitHub Token (requires read:packages permission)
</server>
</servers>Add Gradle dependency
Release Version
Use Maven Central BOM in your build.gradle (or build.gradle.kts) via platform:
dependencies {
implementation platform("com.alibaba.cloud:spring-cloud-alibaba-dependencies:2025.1.0.0")
// choose starter(s) as needed
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config"
}Snapshot
If you need the published Snapshot Version, use snapshot BOM and add GitHub Packages repository:
repositories {
mavenCentral()
maven {
url = uri("https://maven.pkg.github.com/alibaba/spring-cloud-alibaba")
credentials {
username = findProperty("gpr.user") ?: System.getenv("GITHUB_USERNAME")
password = findProperty("gpr.key") ?: System.getenv("GITHUB_TOKEN")
}
}
}
dependencies {
implementation platform("com.alibaba.cloud:spring-cloud-alibaba-dependencies:2025.1.0.0-SNAPSHOT")
// choose starter(s) as needed
implementation "com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config"
}You can put credentials in ~/.gradle/gradle.properties:
gpr.user=Your GitHub Username
gpr.key=Your GitHub Token (requires read:packages permission)Examples
A spring-cloud-alibaba-examples module is included in our project for you to get started with Spring Cloud Alibaba quickly. It contains an example, and you can refer to the readme file in the example project for a quick walkthrough.
Examples:
Version control guidelines
The version number of the project is in the form of x.x.x, where x is a number, starting from 0, and is not limited to the range 0~9. When the project is in the incubator phase, the version number is 0.x.x.
As the interfaces and annotations of Spring Boot 1 and Spring Boot 2 have been changed significantly in the Actuator module, and spring-cloud-commons is also changed quite a lot from 1.x.x to 2.0.0, we take the same version rule as SpringBoot version number.
- 1.5.x for Spring Boot 1.5.x
- 2.0.x for Spring Boot 2.0.x
- 2.1.x for Spring Boot 2.1.x
- 2.2.x for Spring Boot 2.2.x
- 2020.x for Spring Boot 2.4.x
- 2021.x for Spring Boot 2.6.x
- 2022.x for Spring Boot 3.0.x
- 2023.x for Spring Boot 3.2.x
- 2025.0.x for Spring Boot 3.5.x
- 2025.1.x for Spring Boot 4.0.x
Code of Conduct
This project is a sub-project of Spring Cloud, it adheres to the Contributor Covenant code of conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected].
Code Conventions and Housekeeping
None of these is essential for a pull request, but they will all help. They can also be added after the original pull request but before a merge.
Use the Spring Framework code format conventions. If you use Eclipse you can import formatter settings using the eclipse-code-formatter.xml file from the Spring Cloud Build project. If using IntelliJ, you can use the Eclipse Code Formatter Plugin to import the same file.
Make sure all new .java files to have a simple Javadoc class comment with at least an @author tag identifying you, and preferably at least a paragraph on what the class is for.
Add the ASF license header comment to all new .java files (copy from existing files in the project)
Add yourself as an @author to the .java files that you modify substantially (more than cosmetic changes).
Add some Javadocs and, if you change the namespace, some XSD doc elements.
A few unit tests would help a lot as well —— someone has to do it.
If no-one else is using your branch, please rebase it against the current 2023.x (or other target branch in the main project).
When writing a commit message please follow these conventions, if you are fixing an existing issue please add Fixes gh-XXXX at the end of the commit message (where XXXX is the issue number).
Contact Us
Mailing list is recommended for discussing almost anything related to spring-cloud-alibaba.
[email protected]: You can ask questions here if you encounter any problem when using or developing spring-cloud-alibaba.
File: spring-cloud-alibaba-examples/nacos-example/readme.md
Spring Cloud Alibaba Nacos Example
Project description
This project demonstrates how to use Spring Cloud Alibaba Nacos related Starters to complete the service discovery and configuration management of Spring Cloud applications.
Nacos It is Alibaba's open source dynamic service discovery, configuration management and service management platform that is easier to build cloud-native applications.
Nacos Server 2.2.x is properly configured and started
In Nacos 2.2.x, functions related to user authentication are added. When starting Nacos Server for the first time, it needs to be configured correctly to avoid the problem of startup failure.
Download Nacos Server
The Nacos serv version used in this example is 2.2.0!
Nacos supports both direct download and source code construction. Nacos Server version 2.2.0 is recommended for Spring Cloud Alibaba 2021.x.
- Direct download: Nacos Server download page
- Source code construction: Enter Nacos Github project page, git clone the code to the local compilation and packaging 参考文档.
Configure the Nacos Server
Open the \nacos-server-2.2.0\conf\application.properties configuration file and modify the following configuration items:
Configure the data source
Take the MySQL database as an example here, and use the nacos-server-2.2.0\conf\mysql-schema.sql initialization database table file. Modify the following configuration as well
#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
spring.datasource.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
db.user.0=root
db.password.0=root
### Connection pool configuration: hikariCP
db.pool.config.connectionTimeout=30000
db.pool.config.validationTimeout=10000
db.pool.config.maximumPoolSize=20
db.pool.config.minimumIdle=2Turn on authentication
Note: If it is not enabled, login failure exception will occur in 2.2.x!
### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=nacos
### If turn on auth system:
nacos.core.auth.enabled=trueSet the server authentication key
nacos.core.auth.server.identity.key=test
nacos.core.auth.server.identity.value=testSet the default token
### The default token (Base64 String):
nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789** When using the Nacos service discovery and configuration function, be sure to configure username and password attribute, otherwise the user will not be found! **
Open API authentication
Authentication is required when using the Open api interface in nacos server 2.2.x: For more details, please refer to: Nacos api authentication
Obtain accessToken: Use username and password to log in to the nacos server:
curl -X POST '127.0.0.1:8848/nacos/v1/auth/login' -d 'username=nacos&password=nacos'If the username and password are correct, the returned information is as follows:
{"accessToken":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyOTE2Nn0.2TogGhhr11_vLEjqKko1HJHUJEmsPuCxkur-CfNojDo", "tokenTtl": 18000, "globalAdmin": true}Use accessToken to request the nacos api interface:
curl -X GET '127.0.0.1:8848/nacos/v1/cs/configs?accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyMzkyM30.O-s2yWfDSUZ7Svd3Vs7jy9tsfDNHs1SuebJB4KlNY8Q&dataId=nacos.example.1&group=nacos_group'
Start the Nacos Server
Start Nacos Server, enter the folder after downloading to the local and decompressing (enter the folder after compiling and packaging by using the source code construction method), then enter its relative folder
nacos/bin, and execute the following command according to the actual situation of the operating system. 详情参考此文档。Linux/Unix/Mac operating system, execute the command
sh startup.sh -m standaloneWindows operating system, executing command
cmd startup.cmd
Access Nacos Server Console.
The browser enters the address http://127.0.0.1:8848/nacos , The first login needs to bind the nacos user, because the new version adds authentication, and the user name and password need to be configured during application registration and configuration binding.
Nacos application example
Spring Cloud Alibaba Nacos Config
Application access
Before starting the application sample to demonstrate the project function, first understand how the Spring Cloud application accesses Nacos Config as the service configuration center.
Note that this section is only for the convenience of understanding the access method. The access work has been completed in this sample code, and no further modification is required.
First, modify the
pom.xmlfile to introduce spring-cloud-starter-alibaba-nacos-config;xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>Configuring a Nacos address in an
/src/main/resources/application.yamlapplied configuration file and introducing a service configuration;ymlspring: cloud: nacos: serverAddr: 127.0.0.1:8848 username: 'nacos' password: 'nacos' config: import: - nacos:nacos-config-example.properties?refresh=true&group=DEFAULT_GROUPAfter completing the above two steps, the application will obtain the corresponding configuration from Nacos Server and add it to the Property Sources of Spring Environment. There are four ways to save a portion of the Nacos configuration using the Nacos Configuration Center:
- BeanAutoRefres hConfig Example: An example of supporting automatic refresh of configuration changes by configuring configuration information as beans;
- ConfigListenerEx ample: example of monitoring configuration information;
- Docking Interface Example: An example of docking the Nacos interface and completing the addition, deletion, modification and query of the configuration information through the interface;
- ValueAnnotation Example: An example of obtaining configuration information through the @ Value annotation.
Add Configuration in Nacos Server
Add a configuration to the Nacos Server by executing the following command from the command line. Can be injected directly through the Nacos console!
$ curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?accessToken=XXXXXXXXXXXXXXXXXXXXXXXXXXX&dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serverAddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"Details of the added configuration are as follows:
# dataId is nacos-config-example.properties
# group is DEFAULT_GROUP
# content is:
spring.cloud.nacos.config.serveraddr=127.0.0.1:8848
spring.cloud.nacos.config.prefix=PREFIX
spring.cloud.nacos.config.group=GROUP
spring.cloud.nacos.config.namespace=NAMESPACEThe application starts
Add configuration, and add basic configuration information in the application
/src/main/resources/application.yml;ymlserver: port: 18084 management: endpoints: web: exposure: include: '*'Start the application, support IDE direct start and start after compilation and packaging.
- IDE direct startup: find the main class
NacosConfigApplicationand execute the main method to start the application. - Start after packaging and compiling: First
mvn clean package, compile and package the project, and then enter thetargetfolder tojava -jar nacos-config-example.jarstart the application.
- IDE direct startup: find the main class
Validate
Verify automatic injection
Enter http://127.0.0.1:18084/nacos/bean in the browser address bar and click turn around to see that the data is successfully obtained from the Nacos Server.
Verify dynamic refresh
Execute the following command to modify the configuration data on the Nacos Server side
shell$ curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?accessToken=XXXXXXXXXXXXXXXXXXXXXXXXXXX&dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=DEFAULT_GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"Type
http://127.0.0.1:18084/nacos/beanin the address bar of the browser and click Turn, and you can see that the application obtains the latest data from the Nacos Server, and the group becomes the DEFAULT _ GROUP.
Principle
Nacos Config Data Structure
Nacos Config uniquely identifies a piece of configuration primarily by dataId and group, assuming you already know this background. If you don't know, please refer to Nacos 文档.
When the Nacos Client obtains data from the Nacos Server, it calls this interface ConfigService.getConfig(String dataId, String group, long timeoutMs).
Spring Cloud App Get Data
dataID
In the Nacos Config Starter, the concatenation format of dataId is as follow
${prefix} - ${spring.profiles.active} . ${file-extension}The
prefixdefault value isspring.application.name. It can also be configured through configuration itemsspring.cloud.nacos.config.prefix.spring.profiles.activeThis is the profile corresponding to the current environment. For details, please refer to
** Note that when the active profile is empty, the corresponding connector - does not exist, and the concatenation format of dataId becomes ${prefix}. ${file-extension} **
file-extensionIt is used to configure the data format of content, which can be configured by configuration itemspring.cloud.nacos.config.file-extension. Currently only types are supportedproperties.
group
groupThe default isDEFAULT_GROUP, which can bespring.cloud.nacos.config.groupconfigured.
Automatic injection
The Spring Cloud Alibaba Nacos Config Starter implements the org.springframework.boot.context.config.ConfigDataLoader interface and sets the priority to the highest.
During the Spring Cloud application startup phase, it will actively obtain the corresponding data from the Nacos Server side, convert the obtained data into PropertySource, and inject it into the Property Sources attribute of the Environment. Therefore, the @ Value annotation can also be used to directly obtain the contents of the Nacos Server configuration.
Dynamic refresh
By default, the Nacos Config Starter is a refresh method that is triggered org.springframework.cloud.context.refresh.ContextRefresher in real time when the monitoring function is added to the configuration item of all Nacos that have successfully obtained data and changes in the server configuration are monitored.
If you need to refresh the Bean dynamically, refer to the Spring and Spring Cloud specifications. It is recommended that you add @RefreshScope or @ConfigurationProperties annotate the class,
For more details, please refer to ContextRefresher Java Doc.
Endpoint information viewing
Spring Boot applications support the use of Endpoints to expose relevant information, as does the Spring Cloud Alibaba Nacos Config Starter.
Before using it, you need to add spring-boot-starter-actuator a dependency in Maven and allow Endpoints access in the configuration.
Spring Boot 3.x can be accessed by visiting http://127.0.0.1:18084/actuator/nacosconfig .
As shown in the figure above, Sources indicates which Nacos Config configuration items the client has obtained information from, and RefreshHistory indicates the history of dynamic refresh, with a maximum of 20 entries saved. NacosConfig Properties is the configuration of the Nacos Config Starter itself.
More
More configuration items
| Configuration item | key | Default value | Description |
|---|---|---|---|
| Server address | spring. Cloud. Nacos. Config. Server-addr | server IP and port | |
| Prefix of DataId | spring. Cloud. Nacos. Config. Prefix | ${ spring. Application. Name } | Prefix of DataId. The default value is the application name |
| Group | spring.cloud.nacos.config.group | DEFAULT_GROUP | |
| Suffix of DataId and content file format | spring. Cloud. Nacos. Config. File -extension | properties | Suffix of DataId, which is also the file format of configuration content. Currently, only properties is supported |
| Encoding method of the configured content | spring. Cloud. Nacos. Config. Encode | UTF-8 | Configured encoding |
| Obtain the configured timeout | spring. Cloud. Nacos. Config. Timeout | 3000 | Unit: ms |
| Namespace of configuration | spring. Cloud. Nacos. Config. Namespace | One of the common scenarios is to distinguish and isolate the configurations of different environments, such as the resource isolation between the development and testing environments and the production environment. | |
| AccessKey | spring.cloud.nacos.config.access-key | ||
| SecretKey | spring.cloud.nacos.config.secret-key | ||
| Relative path | spring. Cloud. Nacos. Config. Context-path | Relative path of the server API | |
| Access point | spring. Cloud. Nacos. Config. Endpoint | The domain name of a service in a region. The server address can be obtained dynamically through this domain name | |
| Whether to enable listening and automatic refresh | spring. Cloud. Nacos. Config. Refresh -enabled | true | |
| Cluster service name | spring. Cloud. Nacos. Config. Cluster -name |
Spring Cloud Alibaba Nacos Discovery
How to access
Before launching the Nacos Discovery sample for demonstration, take a look at how Spring Cloud applications access Nacos Discovery.
Note that this section is only for your convenience to understand the access method. The access work has been completed in this sample code, and you do not need to modify it.
First, modify the
pom.xmlfile and introduce spring-cloud-alibaba-nacos-discovery-starter;xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>Configuring a Nacos Server address in an
/src/main/resources/application.propertiesapplied configuration file;propertiesspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848Use @ EnableDiscoveryClient annotation to enable service registration and discovery;
java@SpringBootApplication @EnableDiscoveryClient public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } @RestController class EchoController { @GetMapping(value = "/echo/{string}") public String echo(@PathVariable String string) { return string; } } }
The application starts
Add the configuration, and add the basic configuration information in the nacos-discovery-provider-example project
/src/main/resources/application.properties;propertiesspring.application.name=service-provider server.port=18082Start the application, support IDE direct start and start after compilation and packaging.
- IDE direct startup: Find the main class
ProviderApplicationof the nacos-discovery-provider-example project, and execute the main method to start the application. - Start after compilation: Compile and package
mvn clean packagethe project in the nacos-discovery-provider-example project, and thenjava -jar nacos-discovery-provider-example.jarstart the application.
- IDE direct startup: Find the main class
Query service validation
Enter this address http://127.0.0.1:8848/nacos/v1/ns/catalog/instances?serviceName=service-provider&clusterName=DEFAULT&pageSize=10&pageNo=1&namespaceId= in the browser and click Jump to see that the service node has been successfully registered to the Nacos Server.
Service discovery integration Spring Cloud Loadbalancer.
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
</dependencies>Add the following configuration to use the load balancing strategy provided by the Spring Cloud Alibaba community for Spring Cloud Loadbalancer load balancing dependencies, so as to use all the capabilities provided by the Spring Cloud Alibaba:
spring.cloud.loadbalancer.ribbon.enabled=false
spring.cloud.loadbalancer.nacos.enabled=trueIPv4 to IPv6 address migration schema
Dual registration of IPv4 and IPv6 addresses
After configuring the Spring Cloud Loadbalancer as a load balancing strategy, the application will register the IPv4 address and IPv6 address of the microservice in the registration center by default after starting, where the IPv4 address will be stored under the IP field in the Nacos service list. The IPv6 address is in the metadata field of Nacos, and its corresponding Key is IPv6. When the service consumer calls the service provider, it will select the appropriate IP address type to initiate the service call according to its own IP address stack support. Specific rules: (1) If the service consumer itself supports both IPv4 and IPv6 address stacks or only supports IPv6 address stacks, the service consumer will use the IPv6 address provided by the service to initiate a service call. If the IPv6 address call fails, if it also supports IPv4 address stacks, (2) When the service consumer itself only supports IPv4 single address stack, the service consumer will use the IPv4 address provided by the service to initiate a service call.
Register IPv4 only
If you want to register using only IPv4 addresses, you can use the following configuration at the application. Properties:
spring.cloud.nacos.discovery.ip-type=IPv4Register for IPv6 only
If you want to use only IPv6 addresses, you can use the following configuration on the application. Properties:
spring.cloud.nacos.discovery.ip-type=IPv6Using RestTemplate and FeignClient
Here's a look at the code for the nacos-discovery-consumer-example project to show how to RestTemplate and FeignClient.
Note that this section is only for the convenience of understanding the access method. The access work has been completed in this sample code, and you do not need to modify it. Only Ribbon, RestTemplate and FeignClient are involved here. If other service discovery components have been used, Nacos Discovery can be accessed by directly replacing dependencies.
Add the @ LoadBalanced annotation to make the RestTemplate access the Ribbon
java@Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); }FeignClient has been integrated with Ribbon by default. Here is how to configure a FeignClient.
java@FeignClient(name = "service-provider") public interface EchoService { @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); }Use the @ FeignClient annotation to wrap the Echo Service interface as a FeignClient, and the attribute name corresponds to the service name service-provider.
The @ RequestMapping annotation on the echo method corresponds the echo method to the URL "/echo/{ str}", and the @ PathVariable annotation corresponds the str in
{str}the URL path to the parameter of the echo method.After the above configuration is completed, the two are automatically injected into the TestController.
java@RestController public class TestController { @Autowired private RestTemplate restTemplate; @Autowired private EchoService echoService; @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } }Configure the necessary configuration and add the basic configuration information in the nacos-discovery-consumer-example project
/src/main/resources/application.properties.java@RestController public class TestController { @Autowired private RestTemplate restTemplate; @Autowired private EchoService echoService; @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } }
5.Start the application, support IDE direct start and start after compilation and packaging.
- IDE direct startup: Find the main class
ConsumerApplicationof the nacos-discovery-consumer-example project, and execute the main method to start the application. - Start after compilation: Compile and package
mvn clean packagethe project in the nacos-discovery-consumer-example project, and thenjava -jar nacos-discovery-consumer-example.jarstart the application.
Validate
Enter http://127.0.0.1:18083/echo-rest/1234,点击跳转,可以看到浏览器显示了 the message "hello Nacos Discovery 1234" returned by nacos-discovery-provider-example in the browser address bar to prove that the service discovery is valid.
Enter http://127.0.0.1:18083/echo-feign/12345,点击跳转,可以看到浏览器显示 the message "hello Nacos Discovery 12345" returned by nacos-discovery-provider-example in the browser address bar to prove that the service discovery is effective.
Principle
Service registration
The Spring Cloud Alibaba Nacos Discovery follows the Spring cloud Common standard. The three interfaces of AutoService Registration, Service Registry and Registration are implemented.
In the startup phase of the Spring Cloud application, the WebServerInitializedEvent event is monitored. After the Web container is initialized, that is, after the WebServerInitializedEvent event is received, the registration action is triggered. Call the register method of the Service Registry to register the service with the Nacos Server.
Endpoint information viewing
Spring Boot applications support the use of Endpoints to expose relevant information, as does the Spring Cloud Alibaba Nacos Discovery Starter.
Before using it, you need to add spring-boot-starter-actuator a dependency in Maven and allow Endpoints access in the configuration.
Spring Boot 3.x can be accessed by visiting http://127.0.0.1:18083/actuator/nacos-discovery .
As shown in the figure above, NacosDiscovery Properties refers to the configuration of the Spring Cloud Alibaba Nacos Discovery itself, including the content registered by the local machine, and subscribe refers to the subscribed service information of the local machine.
More
More configuration items
| Configuration item | key | Default value | Description |
|---|---|---|---|
| Server address | spring. Cloud. Nacos. Discovery. Server -addr | ||
| Service Name | spring. Cloud. Nacos. Discovery. Service | ${ spring. Application. Name } | The name of the service registered to Nacos. The default is the application name |
| Weight | spring. Cloud. Nacos. Discovery. Weight | 1 | Values range from 1 to 100. The larger the value, the greater the weight |
| Network card name | spring. Cloud. Nacos. Discovery. Network -interface | When IP is not configured, the registered IP is the IP address corresponding to this network card. If this item is not configured, the address of the first network card is used by default | |
| Registered IP Address | spring. Cloud. Nacos. Discovery. IP | Highest Priority | |
| Registered IP address type | spring. Cloud. Nacos. Discovery. IP -type | Dual stack address | Both IPv4 and IPv6 types can be configured. If there are multiple IP addresses of the same type in the network card and you want to designate a specific network segment address, you can configure the filtering address with spring.cloud.inetutils.preferred-networks |
| Registered port | spring. Cloud. Nacos. Discovery. Port | -1 | is not configured by default and will be detected automatically |
| Namespace | spring. Cloud. Nacos. Discovery. Namespace | One of the common scenarios is to distinguish and isolate the registration of different environments, such as the isolation of resources (such as configurations and services) between the development and testing environments and the production environment. | |
| AccessKey | spring.cloud.nacos.discovery.access-key | ||
| SecretKey | spring.cloud.nacos.discovery.secret-key | ||
| Metadata | spring. Cloud. Nacos. Discovery. Metadata | Configure using Map format | |
| Log file name | spring. Cloud. Nacos. Discovery. Log -name | ||
| Cluster | spring. Cloud. Nacos. Discovery. Cluster -name | DEFAULT | Nacos cluster name |
| Access point | spring. Cloud. Nacos. Discovery. Endpoint | The domain name of a service in a region. The server address can be obtained dynamically through this domain name | |
| Integrate LoadBalancer | spring. Cloud. Loadbalancer. Nacos. Enabled | false | |
| Nacos Watch enabled | spring. Cloud. Nacos. Discovery. Watch. Enabled | false | can be set to true to enable watch |
| Enable Nacos | spring. Cloud. Nacos. Discovery. Enabled | true | Start by default. If set to false, automatic registration with Nacos will be disabled |
Spring Cloud Alibaba Nacos integrated Spring Cloud Gateway.
How to access
Before starting the demo, learn how Spring Cloud applications connect to Spring Cloud, Nacos Discovery, and Spring Cloud Gateway.
Note that this section is only for your convenience to understand the access method. The access work has been completed in this sample code, and you do not need to modify it.
First, modify the
pom.xmlfile to introduce Spring Cloud Alibaba Nacos Discovery Starter and Spring Cloud Gateway Starter.xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>Configure the Nacos Server address in the applied
/src/main/resources/application.propertiesconfiguration filmspropertiesspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848Configure Spring Cloud Gateway routing in the application's
/src/main/resources/application.propertiesconfiguration filepropertiesspring.cloud.gateway.routes[0].id=nacos-route spring.cloud.gateway.routes[0].uri=lb://service-gateway-provider spring.cloud.gateway.routes[0].predicates[0].name=Path spring.cloud.gateway.routes[0].predicates[0].args[pattern]=/nacos/** spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1Use the @ EnableDiscoveryClient annotation to turn on service registration and discovery
java@SpringBootApplication @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } }
Spring Cloud Gateway App Launch
Start the application, support IDE direct start and start after compilation and packaging.
- IDE direct startup: Find the main class
GatewayApplicationof the nacos-gateway-discovery-example project, and execute the main method to start the application. - Start after compilation: Compile and package
mvn clean packagethe project in the nacos-gateway-discovery-example project, and thenjava -jar nacos-gateway-discovery-example.jarstart the application.
Service Provider Application Launch
Start the application, support IDE direct start and start after compilation and packaging.
- Start the IDE directly: find the main class
ProviderApplicationof the nacos-gateway-provider-example project, and execute the main method to start the application. - Start after compilation: Compile and package
mvn clean packagethe project in the nacos-gateway-provider-example project, and thenjava -jar nacos-gateway-provider-example.jarstart the application.
Validate
curl 'http://127.0.0.1:18085/nacos/echo/hello-world'
hello Nacos Discovery hello-world⏎curl 'http://127.0.0.1:18085/nacos/divide?a=6&b=2'
3⏎Native Image build
Please refer to the Spring Cloud Alibaba website
More introduction
Nacos provides users with service infrastructure including dynamic service discovery, configuration management, service management, etc., to help users build, deliver and manage their microservice platforms more flexibly and easily. Based on Nacos, users can build modern cloud native applications centered on "services" more quickly. Nacos can be seamlessly integrated with Spring Cloud, Kubernetes/CNCF, Dubbo and other micro-service ecosystems to provide users with a better experience. For more information about Nacos, see the Nacos 项目.
If you have any suggestions or ideas about Spring Cloud Nacos Discovery, please feel free to send them to us in the issue or through other community channels.
File: spring-cloud-alibaba-examples/nacos-example/readme-zh.md
Spring Cloud Alibaba Nacos Example
项目说明
本项目演示如何使用 Spring Cloud Alibaba Nacos 相关 Starter 完成 Spring Cloud 应用的服务发现和配置管理。
Nacos 是阿里巴巴开源的一个更易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
正确配置并启动 Nacos Server 2.2.x
在 Nacos 2.2.x 中,加入了用户鉴权相关的功能,在首次启动 Nacos Server 时,需要正确配置,避免出现启动失败的问题。
下载 Nacos Server
本示例中使用 Nacos Server 版本为 2.2.0!
Nacos 支持直接下载和源码构建两种方式。推荐在 Spring Cloud Alibaba 2021.x 中使用 Nacos Server 2.2.0 版本。
- 直接下载:Nacos Server 下载页
- 源码构建:进入 Nacos Github 项目页面,将代码 git clone 到本地自行编译打包,参考文档。
配置 Nacos Server
打开 \nacos-server-2.2.0\conf\application.properties 配置文件,修改以下配置项:
配置数据源
此处以 MySQL 数据库为例,使用 nacos-server-2.2.0\conf\mysql-schema.sql 初始化数据库表文件。同时修改以下配置
#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
spring.datasource.platform=mysql
### Count of DB:
db.num=1
### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
db.user.0=root
db.password.0=root
### Connection pool configuration: hikariCP
db.pool.config.connectionTimeout=30000
db.pool.config.validationTimeout=10000
db.pool.config.maximumPoolSize=20
db.pool.config.minimumIdle=2开启鉴权
注意:不开启在 2.2.x 中会出现登陆失败异常!
### The auth system to use, currently only 'nacos' and 'ldap' is supported:
nacos.core.auth.system.type=nacos
### If turn on auth system:
nacos.core.auth.enabled=true设置服务端验证 key
nacos.core.auth.server.identity.key=test
nacos.core.auth.server.identity.value=test设置默认 token
### The default token (Base64 String):
nacos.core.auth.plugin.nacos.token.secret.key=SecretKey012345678901234567890123456789012345678901234567890123456789在使用 Nacos 服务发现和配置功能时,一定要配置 username 和 password 属性,否则会出现用户未找到异常!
Open API 鉴权
在 nacos server 2.2.x 中使用 Open api 接口时需要鉴权:更多细节请参考:Nacos api 鉴权
获取 accessToken:使用用户名和密码登陆 nacos server:
curl -X POST '127.0.0.1:8848/nacos/v1/auth/login' -d 'username=nacos&password=nacos'若用户名和密码正确,返回信息如下:
{"accessToken":"eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyOTE2Nn0.2TogGhhr11_vLEjqKko1HJHUJEmsPuCxkur-CfNojDo","tokenTtl":18000,"globalAdmin":true}使用 accessToken 请求 nacos api 接口:
curl -X GET '127.0.0.1:8848/nacos/v1/cs/configs?accessToken=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJuYWNvcyIsImV4cCI6MTYwNTYyMzkyM30.O-s2yWfDSUZ7Svd3Vs7jy9tsfDNHs1SuebJB4KlNY8Q&dataId=nacos.example.1&group=nacos_group'
启动 Nacos Server
启动 Nacos Server,进入下载到本地并解压完成后的文件夹(使用源码构建的方式则进入编译打包好的文件夹),再进去其相对文件夹
nacos/bin,并对照操作系统实际情况执行如下命令。详情参考此文档。Linux/Unix/Mac 操作系统,执行命令
sh startup.sh -m standaloneWindows 操作系统,执行命令
cmd startup.cmd
访问 Nacos Server Console
浏览器输入地址 http://127.0.0.1:8848/nacos ,首次登陆需要绑定 nacos 用户,因为新版本增加了鉴权,需要应用注册和配置绑定时配置用户名和密码。
Nacos 应用示例
Spring Cloud Alibaba Nacos Config
应用接入
在启动应用示例进行项目功能演示之前,先了解一下 Spring Cloud 应用如何接入 Nacos Config 作为服务配置中心。
注意 本章节只是为了便于理解接入方式,本示例代码中已经完成接入工作,无需再进行修改。
首先,修改
pom.xml文件,引入 spring-cloud-starter-alibaba-nacos-config ;xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>在应用的
/src/main/resources/application.yaml配置文件中配置 Nacos 地址并引入服务配置;ymlspring: cloud: nacos: serverAddr: 127.0.0.1:8848 # 以下配置项必须填写 username: 'nacos' password: 'nacos' config: import: - nacos:nacos-config-example.properties?refresh=true&group=DEFAULT_GROUP完成上述两步后,应用会从 Nacos Server 中获取相应的配置,并添加在 Spring Environment 的 PropertySources 中。使用 Nacos 配置中心保存 Nacos 的部分配置时,有以下四种方式:
- BeanAutoRefreshConfigExample: 通过将配置信息配置为bean,支持配置变自动刷新的例子;
- ConfigListenerExample: 监听配置信息的例子;
- DockingInterfaceExample: 对接 Nacos 接口,通过接口完成对配置信息增删改查的例子;
- ValueAnnotationExample: 通过 @Value 注解进行配置信息获取的例子。
Nacos Server 中添加配置
在命令行执行如下命令,向 Nacos Server 中添加一条配置。可直接通过 Nacos 控制台注入!
注意:需要替换 accessToken。
$ curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?accessToken=XXXXXXXXXXXXXXXXXXXXXXXX&dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serverAddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"添加的配置详情如下:
# dataId 为 nacos-config-example.properties
# group 为 DEFAULT_GROUP
# 内容如下:
spring.cloud.nacos.config.serveraddr=127.0.0.1:8848
spring.cloud.nacos.config.prefix=PREFIX
spring.cloud.nacos.config.group=GROUP
spring.cloud.nacos.config.namespace=NAMESPACE应用启动
增加配置,在应用的
/src/main/resources/application.yml中添加基本配置信息;ymlserver: port: 18084 management: endpoints: web: exposure: include: '*'启动应用,支持 IDE 直接启动和编译打包后启动。
- IDE直接启动:找到主类
NacosConfigApplication,执行 main 方法启动应用。 - 打包编译后启动:首先执行
mvn clean package将工程编译打包,进入target文件夹执行java -jar nacos-config-example.jar启动应用。
- IDE直接启动:找到主类
验证
验证自动注入
在浏览器地址栏输入 http://127.0.0.1:18084/nacos/bean,并点击调转,可以看到成功从 Nacos Server 中获取了数据。
验证动态刷新
执行如下命令,修改 Nacos Server 端的配置数据
shell$ curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?accessToken=XXXXXXXXXXXXXXXXXXXXXXXXXXX&dataId=nacos-config-example.properties&group=DEFAULT_GROUP&content=spring.cloud.nacos.config.serveraddr=127.0.0.1:8848%0Aspring.cloud.nacos.config.prefix=PREFIX%0Aspring.cloud.nacos.config.group=DEFAULT_GROUP%0Aspring.cloud.nacos.config.namespace=NAMESPACE"在浏览器地址栏输入
http://127.0.0.1:18084/nacos/bean,并点击调转,可以看到应用从 Nacos Server 中获取了最新的数据,group 变成了 DEFAULT_GROUP。
原理
Nacos Config 数据结构
Nacos Config 主要通过 dataId 和 group 来唯一确定一条配置,假定您已经了解此背景。如果不了解,请参考 Nacos 文档。
Nacos Client 从 Nacos Server 端获取数据时,调用的是此接口 ConfigService.getConfig(String dataId, String group, long timeoutMs)。
Spring Cloud 应用获取数据
dataID
在 Nacos Config Starter 中,dataId 的拼接格式如下
${prefix} - ${spring.profiles.active} . ${file-extension}prefix默认为spring.application.name的值,也可以通过配置项spring.cloud.nacos.config.prefix来配置。spring.profiles.active即为当前环境对应的 profile,详情可以参考 Spring Boot文档注意,当 active profile 为空时,对应的连接符
-也将不存在,dataId 的拼接格式变成${prefix}.${file-extension}file-extension为配置内容的数据格式,可以通过配置项spring.cloud.nacos.config.file-extension来配置。
目前只支持properties类型。
group
group默认为DEFAULT_GROUP,可以通过spring.cloud.nacos.config.group配置。
自动注入
Spring Cloud Alibaba Nacos Config Starter 实现了 org.springframework.boot.context.config.ConfigDataLoader 接口,并将优先级设置成了最高。
在 Spring Cloud 应用启动阶段,会主动从 Nacos Server 端获取对应的数据,并将获取到的数据转换成 PropertySource 且注入到 Environment 的 PropertySources 属性中,所以使用 @Value 注解也能直接获取 Nacos Server 端配置的内容。
动态刷新
Nacos Config Starter 默认为所有获取数据成功的 Nacos 的配置项添加了监听功能,在监听到服务端配置发生变化时会实时触发 org.springframework.cloud.context.refresh.ContextRefresher 的 refresh 方法 。
如果需要对 Bean 进行动态刷新,请参照 Spring 和 Spring Cloud 规范。推荐给类添加 @RefreshScope 或 @ConfigurationProperties 注解,
更多详情请参考 ContextRefresher Java Doc。
Endpoint 信息查看
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,Spring Cloud Alibaba Nacos Config Starter 也支持这一点。
在使用之前需要在 maven 中添加 spring-boot-starter-actuator依赖,并在配置中允许 Endpoints 的访问。
Spring Boot 3.x 可以通过访问 http://127.0.0.1:18084/actuator/nacosconfig 来访问。
如上图所示,Sources 表示此客户端从哪些 Nacos Config 配置项中获取了信息,RefreshHistory 表示动态刷新的历史记录,最多保存20条,NacosConfigProperties 则为 Nacos Config Starter 本身的配置。
More
更多配置项
| 配置项 | key | 默认值 | 说明 |
|---|---|---|---|
| 服务端地址 | spring.cloud.nacos.config.server-addr | 服务器ip和端口 | |
| DataId前缀 | spring.cloud.nacos.config.prefix | ${spring.application.name} | DataId的前缀,默认值为应用名称 |
| Group | spring.cloud.nacos.config.group | DEFAULT_GROUP | |
| DataId后缀及内容文件格式 | spring.cloud.nacos.config.file-extension | properties | DataId的后缀,同时也是配置内容的文件格式,目前只支持 properties |
| 配置内容的编码方式 | spring.cloud.nacos.config.encode | UTF-8 | 配置的编码 |
| 获取配置的超时时间 | spring.cloud.nacos.config.timeout | 3000 | 单位为 ms |
| 配置的命名空间 | spring.cloud.nacos.config.namespace | 常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源隔离等。 | |
| AccessKey | spring.cloud.nacos.config.access-key | ||
| SecretKey | spring.cloud.nacos.config.secret-key | ||
| 相对路径 | spring.cloud.nacos.config.context-path | 服务端 API 的相对路径 | |
| 接入点 | spring.cloud.nacos.config.endpoint | 地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址 | |
| 是否开启监听和自动刷新 | spring.cloud.nacos.config.refresh-enabled | true | |
| 集群服务名 | spring.cloud.nacos.config.cluster-name |
Spring Cloud Alibaba Nacos Discovery
如何接入
在启动 Nacos Discovery 示例进行演示之前,了解一下 Spring Cloud 应用如何接入 Nacos Discovery。
注意 本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。
首先,修改
pom.xml文件,引入 spring-cloud-alibaba-nacos-discovery-starter;xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>在应用的
/src/main/resources/application.properties配置文件中配置 Nacos Server 地址;propertiesspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848使用 @EnableDiscoveryClient 注解开启服务注册与发现功能;
java@SpringBootApplication @EnableDiscoveryClient public class ProviderApplication { public static void main(String[] args) { SpringApplication.run(ProviderApplication.class, args); } @RestController class EchoController { @GetMapping(value = "/echo/{string}") public String echo(@PathVariable String string) { return string; } } }
应用启动
增加配置,在 nacos-discovery-provider-example 项目的
/src/main/resources/application.properties中添加基本配置信息;propertiesspring.application.name=service-provider server.port=18082启动应用,支持 IDE 直接启动和编译打包后启动。
- IDE直接启动:找到 nacos-discovery-provider-example 项目的主类
ProviderApplication,执行 main 方法启动应用。 - 打包编译后启动:在 nacos-discovery-provider-example 项目中执行
mvn clean package将工程编译打包,然后执行java -jar nacos-discovery-provider-example.jar启动应用。
- IDE直接启动:找到 nacos-discovery-provider-example 项目的主类
查询服务验证
在浏览器输入此地址 http://127.0.0.1:8848/nacos/v1/ns/catalog/instances?serviceName=service-provider&clusterName=DEFAULT&pageSize=10&pageNo=1&namespaceId=,并点击跳转,可以看到服务节点已经成功注册到 Nacos Server。
服务发现集成 Spring Cloud Loadbalancer
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-loadbalancer</artifactId>
</dependency>
</dependencies>增加如下配置,使用 Spring Cloud Alibaba 社区针对 Spring Cloud Loadbalancer 负载均衡依赖提供的负载均衡策略,以便使用 Spring Cloud Alibaba 提供的所有的能力:
spring.cloud.loadbalancer.ribbon.enabled=false
spring.cloud.loadbalancer.nacos.enabled=trueIPv4 至 IPv6 地址迁移方案
IPv4 和 IPv6 地址双注册
在配置完成 Spring Cloud Loadbalancer 作为负载均衡策略后,应用启动后会默认将微服务的 IPv4 地址和 IPv6 地址注册到注册中心中,其中 IPv4 地址会存放在 Nacos 服务列表中的 IP 字段下,IPv6 地址在 Nacos 的 metadata 字段中,其对应的 Key 为 IPv6。当服务消费者调用服务提供者时,会根据自身的 IP 地址栈支持情况,选择合适的 IP 地址类型发起服务调用。具体规则:
(1)服务消费者本身支持 IPv4 和 IPv6 双地址栈或仅支持 IPv6 地址栈的情况下,服务消费者会使用服务提供的 IPv6 地址发起服务调用,IPv6 地址调用失败如本身还同事支持 IPv4 地址栈时,暂不支持切换到 IPv4 再发起重试调用;
(2)服务消费者本身仅支持 IPv4 单地址栈的情况下,服务消费者会使用服务提供的 IPv4 地址发起服务调用。
仅注册 IPv4
如果您只想使用 IPv4 地址进行注册,可以在 application.properties 使用以下配置:
spring.cloud.nacos.discovery.ip-type=IPv4仅注册 IPv6
如果您只想使用 IPv6 地址,可以在 application.properties 使用以下配置:
spring.cloud.nacos.discovery.ip-type=IPv6使用 RestTemplate 和 FeignClient
下面将分析 nacos-discovery-consumer-example 项目的代码,演示如何 RestTemplate 与 FeignClient。
注意 本章节只是为了便于理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。此处只涉及 Ribbon、RestTemplate、FeignClient 相关的内容,如果已经使用了其他服务发现组件,可以通过直接替换依赖来接入 Nacos Discovery。
添加 @LoadBalanced 注解,使得 RestTemplate 接入 Ribbon
java@Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); }FeignClient 已经默认集成了 Ribbon ,此处演示如何配置一个 FeignClient。
java@FeignClient(name = "service-provider") public interface EchoService { @GetMapping(value = "/echo/{str}") String echo(@PathVariable("str") String str); }使用 @FeignClient 注解将 EchoService 这个接口包装成一个 FeignClient,属性 name 对应服务名 service-provider。
echo 方法上的 @RequestMapping 注解将 echo 方法与 URL "/echo/{str}" 相对应,@PathVariable 注解将 URL 路径中的
{str}对应成 echo 方法的参数 str。完成以上配置后,将两者自动注入到 TestController 中。
java@RestController public class TestController { @Autowired private RestTemplate restTemplate; @Autowired private EchoService echoService; @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } }配置必要的配置,在 nacos-discovery-consumer-example 项目的
/src/main/resources/application.properties中添加基本配置信息java@RestController public class TestController { @Autowired private RestTemplate restTemplate; @Autowired private EchoService echoService; @GetMapping(value = "/echo-rest/{str}") public String rest(@PathVariable String str) { return restTemplate.getForObject("http://service-provider/echo/" + str, String.class); } @GetMapping(value = "/echo-feign/{str}") public String feign(@PathVariable String str) { return echoService.echo(str); } }
5.启动应用,支持 IDE 直接启动和编译打包后启动。
- IDE 直接启动:找到 nacos-discovery-consumer-example 项目的主类
ConsumerApplication,执行 main 方法启动应用。 - 打包编译后启动:在 nacos-discovery-consumer-example 项目中执行
mvn clean package将工程编译打包,然后执行java -jar nacos-discovery-consumer-example.jar启动应用。
验证
在浏览器地址栏中输入 http://127.0.0.1:18083/echo-rest/1234,点击跳转,可以看到浏览器显示了 nacos-discovery-provider-example 返回的消息 "hello Nacos Discovery 1234",证明服务发现生效。
在浏览器地址栏中输入 http://127.0.0.1:18083/echo-feign/12345,点击跳转,可以看到浏览器显示 nacos-discovery-provider-example 返回的消息 "hello Nacos Discovery 12345",证明服务发现生效。
原理
服务注册
Spring Cloud Alibaba Nacos Discovery 遵循了 Spring Cloud Common 标准,实现了 AutoServiceRegistration、ServiceRegistry、Registration 这三个接口。
在 Spring Cloud 应用的启动阶段,监听了 WebServerInitializedEvent 事件,当 Web 容器初始化完成后,即收到 WebServerInitializedEvent 事件后,会触发注册的动作,调用 ServiceRegistry 的 register 方法,将服务注册到 Nacos Server。
Endpoint 信息查看
Spring Boot 应用支持通过 Endpoint 来暴露相关信息,Spring Cloud Alibaba Nacos Discovery Starter 也支持这一点。
在使用之前需要在 maven 中添加 spring-boot-starter-actuator依赖,并在配置中允许 Endpoints 的访问。
Spring Boot 3.x 可以通过访问 http://127.0.0.1:18083/actuator/nacos-discovery 来访问。
如上图所示,NacosDiscoveryProperties 则为 Spring Cloud Alibaba Nacos Discovery 本身的配置,也包括本机注册的内容,subscribe 为本机已订阅的服务信息。
More
更多配置项
| 配置项 | key | 默认值 | 说明 |
|---|---|---|---|
| 服务端地址 | spring.cloud.nacos.discovery.server-addr | ||
| 服务名 | spring.cloud.nacos.discovery.service | ${spring.application.name} | 注册到Nacos上的服务名称,默认值为应用名称 |
| 权重 | spring.cloud.nacos.discovery.weight | 1 | 取值范围 1 到 100,数值越大,权重越大 |
| 网卡名 | spring.cloud.nacos.discovery.network-interface | 当IP未配置时,注册的IP为此网卡所对应的IP地址,如果此项也未配置,则默认取第一块网卡的地址 | |
| 注册的IP地址 | spring.cloud.nacos.discovery.ip | 优先级最高 | |
| 注册的IP地址类型 | spring.cloud.nacos.discovery.ip-type | 双栈地址 | 可以配置IPv4和IPv6两种类型,如果网卡同类型IP地址存在多个,希望制定特定网段地址,可使用spring.cloud.inetutils.preferred-networks配置筛选地址 |
| 注册的端口 | spring.cloud.nacos.discovery.port | -1 | 默认情况下不用配置,会自动探测 |
| 命名空间 | spring.cloud.nacos.discovery.namespace | 常用场景之一是不同环境的注册的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。 | |
| AccessKey | spring.cloud.nacos.discovery.access-key | ||
| SecretKey | spring.cloud.nacos.discovery.secret-key | ||
| Metadata | spring.cloud.nacos.discovery.metadata | 使用Map格式配置 | |
| 日志文件名 | spring.cloud.nacos.discovery.log-name | ||
| 集群 | spring.cloud.nacos.discovery.cluster-name | DEFAULT | Nacos集群名称 |
| 接入点 | spring.cloud.nacos.discovery.endpoint | 地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址 | |
| 是否集成LoadBalancer | spring.cloud.loadbalancer.nacos.enabled | false | |
| 是否开启Nacos Watch | spring.cloud.nacos.discovery.watch.enabled | false | 可以设置成true来开启 watch |
| 是否启用Nacos | spring.cloud.nacos.discovery.enabled | true | 默认启动,设置为false时会关闭自动向Nacos注册的功能 |
Spring Cloud Alibaba Nacos 集成 Spring Cloud Gateway
如何接入
在启动示例进行演示之前,了解一下 Spring Cloud 应用如何接入 Spring Cloud 如何接入 Nacos Discovery、Spring Cloud Gateway。
注意 本章节只是为了便于您理解接入方式,本示例代码中已经完成接入工作,您无需再进行修改。
首先,修改
pom.xml文件,引入 Spring Cloud Alibaba Nacos Discovery Starter、Spring Cloud Gateway Starter。xml<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>在应用的
/src/main/resources/application.properties配置文件中配置 Nacos Server 地址propertiesspring.cloud.nacos.discovery.server-addr=127.0.0.1:8848在应用的
/src/main/resources/application.properties配置文件中配置 Spring Cloud Gateway 路由propertiesspring.cloud.gateway.routes[0].id=nacos-route spring.cloud.gateway.routes[0].uri=lb://service-gateway-provider spring.cloud.gateway.routes[0].predicates[0].name=Path spring.cloud.gateway.routes[0].predicates[0].args[pattern]=/nacos/** spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1使用 @EnableDiscoveryClient 注解开启服务注册与发现功能
java@SpringBootApplication @EnableDiscoveryClient public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class, args); } } ```c
Spring Cloud Gateway 应用启动
启动应用,支持 IDE 直接启动和编译打包后启动。
- IDE直接启动:找到 nacos-gateway-discovery-example 项目的主类
GatewayApplication,执行 main 方法启动应用。 - 打包编译后启动:在 nacos-gateway-discovery-example 项目中执行
mvn clean package将工程编译打包,然后执行java -jar nacos-gateway-discovery-example.jar启动应用。
服务提供方应用启动
启动应用,支持 IDE 直接启动和编译打包后启动。
- IDE 直接启动:找到 nacos-gateway-provider-example 项目的主类
ProviderApplication,执行 main 方法启动应用。 - 打包编译后启动:在 nacos-gateway-provider-example 项目中执行
mvn clean package将工程编译打包,然后执行java -jar nacos-gateway-provider-example.jar启动应用。
验证
curl 'http://127.0.0.1:18085/nacos/echo/hello-world'
hello Nacos Discovery hello-world⏎curl 'http://127.0.0.1:18085/nacos/divide?a=6&b=2'
3⏎Native Image构建
请参考 Spring Cloud Alibaba 官网中的 Graalvm 快速开始
更多介绍
Nacos 为用户提供包括动态服务发现,配置管理,服务管理等服务基础设施,帮助用户更灵活,更轻松地构建,交付和管理他们的微服务平台,基于 Nacos, 用户可以更快速的构建以“服务”为中心的现代云原生应用。Nacos 可以和 Spring Cloud、Kubernetes/CNCF、Dubbo 等微服务生态无缝融合,为用户提供更卓越的体验。更多 Nacos 相关的信息,请参考 Nacos 项目。
如果您对 Spring Cloud Nacos Discovery 有任何建议或想法,欢迎在 issue 中或者通过其他社区渠道向我们提出。
File: spring-cloud-alibaba-examples/integrated-example/docs/zh/docker-compose-deploy-zh.md
Spring Cloud Alibaba 容器化部署最佳实践 | Docker-Compose 版本
准备工作
Note: 使用 Docker-Compose 方式体验 Demo 时,请确保本地机器内存资源 >= 24G!
如果您还没有安装 Docker 和 Docker-Compose,请按照官方文档来构建运行环境:
- Docker:https://docs.docker.com/desktop/install/linux-install/
- Docker-Compose:https://docs.docker.com/compose/install/
Hosts 配置
为确保代码能够正常启动,请先配置本地主机映射,将以下映射添加到配置文件中。
# for integrated-example
127.0.0.1 integrated-mysql
127.0.0.1 nacos-server
127.0.0.1 seata-server
127.0.0.1 rocketmq
127.0.0.1 gateway-service
127.0.0.1 integrated-frontend准备 jar 包
进入 spring-cloud-alibaba-examples 目录下,执行 mvn package 命令编译项目生成 jar 包,为后续 Docker 构建服务镜像做准备。
快速启动
组件启动
进入 spring-cloud-alibaba-examples/integrated-example 目录下,在终端中执行以下命令 docker-compose -f ./docker-compose/docker-compose-env.yml up -d 来快速部署运行 example 所需组件。
添加配置
docker-compose-env.yml 文件运行成功之后,添加 Nacos 配置:
- 进入
spring-cloud-alibaba-examples/integrated-example目录下; - 在终端中执行
config-init/scripts/nacos-config-quick.sh脚本文件。
完成所有微服务配置的一键导入。
注意:windows 操作系统可以通过
git bash执行 shell 脚本文件完成配置导入。
服务启动
进入 spring-cloud-alibaba-examples/integrated-example 目录下,在终端中执行以下命令 docker-compose -f ./docker-compose/docker-compose-service.yml up -d 来快速部署运行 example 所需服务。
停止所有容器
停止服务容器
进入 spring-cloud-alibaba-examples/integrated-example 目录下,在终端中执行以下命令 docker-compose -f ./docker-compose/docker-compose-service.yml down 来停止正在运行的 example 服务容器。
停止组件容器
进入 spring-cloud-alibaba-examples/integrated-example 目录下,在终端中执行以下命令 docker-compose -f ./docker-compose/docker-compose-env.yml down 来停止正在运行的 example 组件容器。
在容器启动时,可以通过
docker-compose -f docker-compose-*.yml up观察容器的启动过程!
体验 Demo
分布式事务能力
场景说明
针对分布式事务能力,SCA 社区提供了用户下单购买货物的场景,下单后:
- 先请求库存模块,扣减库存
- 扣减账户余额
- 生成订单信息返回响应
启动测试
访问 http://integrated-frontend:8080/order 来体验对应场景。
直接点击下单按钮提交表单,应用模拟客户端向网关发送了一个创建订单的请求。
- 用户的 userId 为 admin
- 用户下单的商品编号为1号
- 此次订单购买的商品个数为1个
在本 demo 示例中,为了便于演示,每件商品的单价都为2。
而在前面的准备工作中,初始化业务数据库表的时候应用新建了一个用户,用户 userId 为 admin,余额为 3 元;同时新建了一个编号为 1 号的商品,库存为 100 件。
因此通过上述的操作,应用会创建一个订单,扣减对应商品编号为 1 号的库存个数(100-1=99),扣减 admin 用户的余额(3-2=1)。
如果再次请求相同的接口,同样是先扣减库存(99-1=98),但是会因为 admin 用户余额不足而抛出异常,并被 Seata 捕获,执行分布式事务二阶段提交,回滚事务。
可以看到数据库中库存的记录因为回滚之后仍然为 99 件。
熔断限流,削峰填谷能力
场景说明
针对大流量背景下的服务熔断限流,削峰填谷,SCA 社区提供了用户为商品进行点赞的场景。在此场景下,SCA 社区提供了两种应对大流量的处理方式。
- Sentinel 在网关侧绑定指定网关路由进行服务的熔断降级。
- RocketMQ 进行流量削峰填谷,在大流量请求下,生产者向 RocketMQ 发送消息,而消费者则通过可配置的消费速率进行拉取消费,减少大流量直接请求数据库增加点赞请求的压力。
启动测试
- Sentinel 服务熔断降级
访问 http://integrated-frontend:8080/sentinel 体验对应场景。
网关路由点赞服务的限流规则为 5,而在前端通过异步处理模拟了 10 次并发请求。
因此可以看到 Sentinel 在 Gateway 侧针对多出的流量进行了服务熔断返回 fallback 给客户端,同时数据库的点赞数进行了更新(+5)。
- RocketMQ 进行流量削峰填谷
访问 http://integrated-frontend:8080/rocketmq 体验对应场景。
由于之前在 Nacos 中配置了 integrated-praise-consumer 消费者模块的消费速率以及间隔,在点击按钮时应用模拟 1000 个点赞请求,针对 1000 个点赞请求,integrated-praise-provider
会将 1000 次请求都向 Broker 投递消息,而在消费者模块中会根据配置的消费速率进行消费,向数据库更新点赞的商品数据,模拟大流量下 RocketMQ 削峰填谷的特性。
可以看到数据库中点赞的个数正在动态更新。
其他
本示例仅是针对各个组件选取出了较为典型的功能特性来服务应用场景
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些,如果您感兴趣或是想要深入了解,欢迎学习各个组件的独立 example 相关文档。
- Nacos examples
- Sentinel core example
- Seata example
- RocketMQ example
File: spring-cloud-alibaba-examples/integrated-example/docs/zh/kubernetes-deployment-zh.md
Spring Cloud Alibaba容器化部署最佳实践 | Kubernetes Helm-Chart 版本
准备工作
此版本为 Spring Cloud Alibaba (后文简称为SCA)最佳实践 Kubernetes 部署版本,运行示例需要准备如下环境:
- Kubernetes(建议使用 Docker Desktop 内置集成的 Kubernetes 环境进行体验。)
- Helm
如果测试机器上还未具备如上环境,请移步至对应官方文档进行环境搭建。
在这里通过 NodePort 的方式来向外界暴露 Kubernetes 中 Pod 的服务,在启动测试前还需配置好 Kubernetes 集群节点的 ip 映射。
# 实际情况请结合您的 K8S 节点的公网 ip 进行调整
120.24.xxx.xxx integrated-frontend
120.24.xxx.xxx gateway-service
120.24.xxx.xxx integrated-mysql-web
120.24.xxx.xxx nacos-mysql-web
120.24.xxx.xxx nacos-svc启动测试
进入到 spring-cloud-alibaba-examples/integrated-example 目录下,执行如下命令利用 Helm 部署应用程序。
helm package helm-chart
helm install integrated-example integrated-example-1.0.0.tgz通过运行上述命令,根据SCA社区提供的 Helm Chart 文档通过 Helm 快速完成最佳实践示例的部署。
可以通过 Kubernetes 提供的 kubectl 命令查看各容器资源部署的情况,耐心等待所有容器完成启动后即可到对应页面体验各个组件的使用场景及能力。
如果您想停止体验,输入如下命令。
helm uninstall integrated-example分布式事务能力
场景说明
针对分布式事务能力,SCA社区提供了用户下单购买货物的场景,下单后:
- 先请求库存模块,扣减库存
- 扣减账户余额
- 生成订单信息返回响应
启动测试
访问 http://integrated-frontend:30080/order 来体验对应场景。
直接点击下单按钮提交表单,模拟客户端向网关发送了一个创建订单的请求。
- 用户的 userId 为 admin
- 用户下单的商品编号为1号
- 此次订单购买的商品个数为1个
在本 demo 示例中,为了便于演示,每件商品的单价都为2。
而在 integrated-mysql 容器的初始化时,初始化业务数据库表的时候新建了一个用户,用户的userId为admin,余额为 3 元;同时新建了一个编号为 1 号的商品,库存为 100 件。
因此通过上述的操作,应用会创建一个订单,扣减对应商品编号为 1 号的库存个数(100-1=99),扣减 admin 用户的余额(3-2=1)。
如果再次请求相同的接口,同样是先扣减库存(99-1=98),但是会因为 admin 用户余额不足而抛出异常,并被 Seata 捕获,执行分布式事务二阶段提交,回滚事务。
可以看到数据库中库存的记录因为回滚之后仍然为 99 件。
熔断限流,削峰填谷能力
场景说明
针对大流量背景下的服务熔断限流,削峰填谷,SCA社区提供了用户为商品进行点赞的场景。在此场景下,SCA社区提供了两种应对大流量的处理方式。
- Sentinel 在网关侧绑定指定网关路由进行服务的熔断降级。
- RocketMQ 进行流量削峰填谷,在大流量请求下,生产者向 RocketMQ 发送消息,而消费者则通过可配置的消费速率进行拉取消费,减少大流量直接请求数据库增加点赞请求的压力。
启动测试
- Sentinel 服务熔断降级
访问 http://integrated-frontend:30080/sentinel 体验对应场景。
网关路由点赞服务的限流规则为 5,而在前端通过异步处理模拟了 10 次并发请求。
因此可以看到 Sentinel 在 Gateway 侧针对多出的流量进行了服务熔断返回 fallback 给客户端,同时数据库的点赞数进行了更新(+5)。
- RocketMQ 进行流量削峰填谷
访问 http://integrated-frontend:30080/rocketmq 体验对应场景。
由于之前在 Nacos 中配置了 integrated-praise-consumer 消费者模块的消费速率以及间隔,在点击按钮时应用将会模拟 1000 个点赞请求,针对 1000 个点赞请求,integrated-praise-provider
会将 1000 次请求都向 Broker 投递消息,而在消费者模块中会根据配置的消费速率进行消费,向数据库更新点赞的商品数据,模拟大流量下 RocketMQ 削峰填谷的特性。
可以看到数据库中点赞的个数正在动态更新。
其他
本示例仅是针对各个组件选取出了较为典型的功能特性来服务应用场景。
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些,如果您对SCA感兴趣或是想要深入了解SCA项目,欢迎阅览各个组件的独立 example 相关文档。
- Nacos examples
- Sentinel core example
- Seata example
- RocketMQ example
File: spring-cloud-alibaba-examples/integrated-example/docs/zh/local-deployment-zh.md
Spring Cloud Alibaba 容器化部署最佳实践 | 本地部署版本
准备工作
环境声明
在运行本地示例之前,需要保证本机具备以下的基础环境,如果您的本地没有当前的环境,下面会一步步进行搭建,演示搭建过程。
当然您也可以通过 Spring Cloud Alibaba (下文简称为SCA)社区提供的docker-compose文件快速启动相应组件。
- Nacos 服务端
- Seata 服务端
- RocketMQ 服务端
- MySQL 服务端
组件服务版本
本项目的各个组件版本请移步至各个社区的 release 页面进行下载并解压运行。
- Nacos: 2.1.0 版本
- Seata: 1.5.1 版本
- RocketMQ: 4.9.4 版本
- MySQL: 5.7 版本
Hosts配置
为了保证代码可以正常启动,请先配置好本机的 host 映射,在配置文件中新增如下的映射。
# for integrated-example
127.0.0.1 integrated-mysql
127.0.0.1 nacos-server
127.0.0.1 seata-server
127.0.0.1 rocketmq
127.0.0.1 gateway-service
127.0.0.1 integrated-frontend数据库配置
下面开始本地环境搭建准备,在数据库配置开始之前,请确保 MySQL 的服务端开启。
初始化业务表
针对第一个场景,订单、账户、库存微服务都需要各自的数据库,而第二个场景模拟点赞也需要存储点赞信息的数据库。
运行 spring-cloud-alibaba-examples/integrated-example/config-init/sql/init.sql 的 sql 脚本一键创建业务所需的环境以及 Seata 相关的表。
Nacos配置
至此,数据库的服务配置完毕,下面需要配置 Nacos 的配置中心有关所有的微服务配置文件。
Nacos启动
为了便于 example 的演示,这里采用 Nacos 的 standalone 模式启动,进入到 Nacos 解压后的目录下,执行如下命令。
#Linux/Mac环境
sh bin/startup.sh -m standalone
#如果您是Ubuntu环境,执行上述命令启动报错提示[[符号找不到,可以执行如下的命令
bash bin/startup.sh -m standalone
#Win环境
.\bin\startup.cmd -m standalone新增配置文件
在批量导入配置之前,请先修改 spring-cloud-alibaba-examples/integrated-example/config-init/config/datasource-config.yaml 中的数据源配置**(用户名和密码)**。
之后运行 spring-cloud-alibaba-examples/integrated-example/config-init/scripts/nacos-config-quick.sh 来完成所有微服务配置的一键导入。
# linux
sh nacos-config-quick.sh
# windows 可以使用git bash来完成配置的导入 执行命令同上Seata 配置
Nacos 服务注册中心以及配置中心部署完毕之后,下面是 Seata 服务端的配置。
Seata 的 db 模式需要额外配置数据库信息以及修改 Seata 服务端的配置文件,且在新版本中配置文件相较于旧版本进行了合并,因此这里为了便于演示方便,采用 Seata 单机的file模式启动 Seata Server。
启动 Seata Server
进入到 release 解压后的 seata 目录中,执行如下命令。
#Linux/Mac环境
sh ./bin/seata-server.sh
#Win环境
bin\seata-server.batRocketMQ 配置
Seata 服务启动后可以启动 RocketMQ 的 NameServer 以及 Broker 服务。
进入到 release 解压后的 rocketmq 目录中,执行如下命令。
启动 NameServer
#Linux/Mac环境
sh bin/mqnamesrv
#Win环境
.\bin\mqnamesrv.cmd启动 Broker
#Linux/Mac环境
sh bin/mqbroker
#Win环境
.\bin\mqbroker.cmd -n localhost:9876运行 Demo 示例
准备工作完成后可以运行 demo 示例,主要根据不同的使用场景,可以分别体验用户下单(分布式事务能力)以及模拟高流量点赞(熔断限流以及削峰填谷的能力)。
首先需要分别启动 integrated-frontend 以及 integrated-gateway 微服务应用。
integrated-gateway模块是整个最佳实践示例的网关。integrated-frontend为最佳实践示例的简易前端页面。
分布式事务能力
场景说明
针对分布式事务能力,SCA社区提供了用户下单购买货物的场景,下单后:
- 先请求库存模块,扣减库存
- 扣减账户余额
- 生成订单信息返回响应
启动测试
分别启动 integrated-storage,integrated-account,integrated-order 三个微服务应用。
访问 http://integrated-frontend:8080/order 来体验对应场景。
直接点击下单按钮提交表单,应用模拟客户端向网关发送了一个创建订单的请求。
- 用户的 userId 为 admin
- 用户下单的商品编号为1号
- 此次订单购买的商品个数为1个
在本 demo 示例中,为了便于演示,每件商品的单价都为2。
而在前面的准备工作中,初始化业务数据库表的时候应用新建了一个用户,用户userId 为 admin,余额为 3 元;同时新建了一个编号为 1 号的商品,库存为 100 件。
因此通过上述的操作,应用会创建一个订单,扣减对应商品编号为 1 号的库存个数(100-1=99),扣减 admin 用户的余额(3-2=1)。
如果再次请求相同的接口,同样是先扣减库存(99-1=98),但是会因为 admin 用户余额不足而抛出异常,并被 Seata 捕获,执行分布式事务二阶段提交,回滚事务。
可以看到数据库中库存的记录因为回滚之后仍然为 99 件。
熔断限流,削峰填谷能力
场景说明
针对大流量背景下的服务熔断限流,削峰填谷,SCA社区提供了用户为商品进行点赞的场景。在此场景下,SCA社区提供了两种应对大流量的处理方式。
- Sentinel 在网关侧绑定指定网关路由进行服务的熔断降级。
- RocketMQ 进行流量削峰填谷,在大流量请求下,生产者向 RocketMQ 发送消息,而消费者则通过可配置的消费速率进行拉取消费,减少大流量直接请求数据库增加点赞请求的压力。
启动测试
分别启动 integrated-praise-provider 以及 integrated-praise-consumer 模块。
- Sentinel 服务熔断降级
访问 http://integrated-frontend:8080/sentinel 体验对应场景。
网关路由点赞服务的限流规则为 5,而在前端通过异步处理模拟了 10 次并发请求。
因此可以看到 Sentinel 在 Gateway 侧针对多出的流量进行了服务熔断返回 fallback 给客户端,同时数据库的点赞数进行了更新(+5)。
- RocketMQ 进行流量削峰填谷
访问 http://integrated-frontend:8080/rocketmq 体验对应场景。
由于之前在 Nacos 中配置了 integrated-praise-consumer 消费者模块的消费速率以及间隔,在点击按钮时应用模拟 1000 个点赞请求,针对 1000 个点赞请求,integrated-praise-provider
会将 1000 次请求都向 Broker 投递消息,而在消费者模块中会根据配置的消费速率进行消费,向数据库更新点赞的商品数据,模拟大流量下 RocketMQ 削峰填谷的特性。
可以看到数据库中点赞的个数正在动态更新。
其他
本示例仅是针对各个组件选取出了较为典型的功能特性来服务应用场景
当然各个组件的功能特性不仅仅只包含最佳实践中演示的这些,如果您感兴趣或是想要深入了解,欢迎学习各个组件的独立 example 相关文档。
- Nacos examples
- Sentinel core example
- Seata example
- RocketMQ example
File: spring-cloud-alibaba-examples/integrated-example/docs/zh/readme-zh.md
Integrated Example
项目说明
本项目为 Spring Cloud Alibaba (后文简称为 SCA)容器化部署最佳实践的 Demo 演示项目,是整合了 SCA 相关组件(Nacos, Sentinel, Seata, RocketMQ)的 Example 示例项目。
主要使用的组件及及其使用特性如下:
- Spring Cloud Gateway 网关
- Nacos 配置中心和服务注册中心
- Sentinel 熔断限流
- Seata 分布式事务
- RocketMQ 消息队列削峰填谷
- Docker 微服务容器化部署
- Kubernetes Helm Chart
应用场景说明
在本 demo 示例中,SCA 社区提供了两种业务场景。
- 用户下单购买货物的场景,下单后:
先请求库存模块,扣减库存
扣减账户余额
生成订单信息返回响应
- 用户为商品进行点赞(模拟 MQ 的生产者消费者应用场景)返回商品点赞后的详细信息(点赞数等)。
组件详细说明
其中,用户下单购买货物的场景主要使用 Seata 来进行分布式事务的能力体现。
用户为商品进行点赞的场景,模拟大流量环境下通过 Sentinel 进行限流或是 RocketMQ 进行削峰填谷。在此场景下,SCA社区提供了两种应对大流量的处理方式:
Sentinel 在网关侧绑定指定网关路由进行服务的熔断降级。
RocketMQ 进行流量削峰填谷,在大流量请求下,生产者向 RocketMQ 发送消息,而消费者则通过可配置的消费速率进行拉取消费,减少大流量直接请求数据库增加点赞请求的压力。
Spring Cloud Gateway
微服务模块的网关。
Spring Cloud GateWay 整合 Nacos,实现动态路由配置。
通过监听 Nacos 配置的改变,实现服务网关路由配置动态刷新,每次路由信息变更,无需修改配置文件而后重启服务。
Nacos
各个微服务的配置中心,服务注册中心。
配置中心
- 共享配置:MySQL 数据源相关信息配置。
注册中心
- 所有的微服务模块都注册到 Nacos 中进行服务注册与发现。
- 整合 Spring Cloud Gateway 网关。
Seata
基于 Seata 的 AT 模式,用于库存模块,账户模块,订单模块的分布式事务处理。
只要库存不足/账户余额不足,回滚事务。
Sentinel
用于点赞场景的服务熔断限流。
整合 Nacos 配置中心与 Spring Cloud Gateway,实现指定路由规则熔断限流规则动态配置。
RocketMQ
用于进行点赞服务流量的削峰填谷。
通过将大流量的点赞请求从生产者发送到 mq,消费者模块从 mq 中拉取进行一定频率的消费,不是简单的直接服务熔断限流降级,实现 RocketMQ 针对大流量的削峰填谷能力。
版本说明
本项目提供了本地部署运行版本、docker-compose 版本以及 Kubernetes Helm-Chart 版本。
如果想要了解具体如何配置各项组件以及完整环境搭建,推荐学习本地部署运行版本。
如果只想运行示例代码,避免繁琐的本地环境搭建过程,又不想使用 k8s 集群。您可以尝试使用 docker-compose 版本。
如果想要在 K8S 集群上快速体验组件效果,跳过各个组件环境部署等过程,请查看 Kubernetes Helm-Chart 版本。
File: spring-cloud-alibaba-examples/integrated-example/docs/en/docker-compose-deployment.md
Spring Cloud Alibaba Containerized Deployment Best Practices | Docker-Compose Edition
Preparation
If you have not installed Docker or Docker-Compose, please follow the official documentation to build the environment
Note: When using Docker-Compose to experience the demo, please make sure that the local machine memory resource is >= 24G!
- Docker:https://docs.docker.com/desktop/install/linux-install/
- Docker-Compose:https://docs.docker.com/compose/install/
Hosts configuration
To ensure that the code can start properly, please configure the local host mapping first, add the following mapping to the configuration file.
# for integrated-example
127.0.0.1 integrated-mysql
127.0.0.1 nacos-server
127.0.0.1 seata-server
127.0.0.1 rocketmq
127.0.0.1 gateway-service
127.0.0.1 integrated-frontendPreparing jar packages
Go to the spring-cloud-alibaba-examples directory and run the mvn package command to compile the project and generate the jar package, so as to prepare for the subsequent construction of the docker service image.
Quickly start
Component start
Enter spring-cloud-alibaba-examples/integration-example directory, run the following command in the terminal to quickly deploy the components required to run example: docker-compose -f ./docker-compose/docker-compose-env.yml up -d.
Add configuration
After docker-compose-env.yml is run successfully, add the Nacos configuration:
- Enter
spring-cloud-alibaba-examples/integration-exampledirectory; - Execute the
config-init/scripts/nacos-config-quick.shscript file in the terminal.
The one-click import of all micro-service configurations is complete.
Note: windows operating systems can use
git bashto execute shell script files to complete the configuration import.
Service start
Enter spring-cloud-alibaba-examples/integration-example directory, Run the following command in the terminal to quickly deploy the services required for running example: docker-compose -f ./docker-compose/docker-compose-service.yml up -d.
Stop all containers
Stops the service container
Enter spring-cloud-alibaba-examples/integration-examplee directory, Run the following command in the terminal to docker-compose -f ./docker-compose/docker-compose-service.yml down to stop the running example service container.
Stops the component container
Enter spring-cloud-alibaba-examples/integration-example directory, Run the following command in the terminal to docker-compose -f ./docker-compose/docker-compose-env.yml down to stop the running example component container.
When the container starts, you can observe the startup process of the container through
docker-compose- f docker-compose-*.yml up!
Experience Demo
Distributed Transaction Capabilities
Scenario Description
For the distributed transaction capability, we provide the scenario where a user places an order for goods and after placing the order.
- First request the inventory module and deduct the inventory
- Deduct the account balance
- Generate order information to return a response
Start test
Visit http://integrated-frontend:8080/order to experience the corresponding scenario.
By clicking the order button directly to submit the form, we simulate the client sending a request to the gateway to create an order.
- The user's userId is admin
- The item number of the user's order is 1
- The number of items purchased in this order is 1
In this demo example, the unit price of each item is 2 for demonstration purposes.
And in the previous preparation, initialize business database table we created a new user userId = admin with a balance of $3, and a new item numbered 1 with 100 units in stock.
So by doing the above, we will create an order, deduct the number of items in stock corresponding to item number 1 (100-1=99), and deduct the balance of the admin user (3-2=1).
If the same interface is requested again, again the inventory is deducted first (99-1=98), but an exception is thrown because the admin user's balance is insufficient and is caught by Seata, which performs a two-stage commit of the distributed transaction and rolls back the transaction.
You can see that the database still has 99 records in stock because of the rollback.
Fused flow limiting, peak shaving capability
Scenario Description
For service fusion limiting and peak and valley cutting in the context of high traffic, we provide a scenario where users make likes for products. In this scenario, we provide two ways to deal with high traffic.
- Sentinel binds specified gateway routes on the gateway side for fusion degradation of services.
- RocketMQ performs traffic clipping, where the producer sends messages to RocketMQ under high traffic requests, while the consumer pulls and consumes through a configurable consumption rate, reducing the pressure of high traffic direct requests to the database to increase the number of likes requests.
Start test
- Sentinel service meltdown degradation
Visit http://integrated-frontend:8080/sentinel to experience the corresponding scenario.
The Gateway routing point service has a flow limit rule of 5, while 10 concurrent requests are simulated on the front end through asynchronous processing.
Therefore, we can see that Sentinel performs a service fusion on the Gateway side to return the fallback to the client for the extra traffic, while the number of likes in the database is updated (+5).
- RocketMQ is performing peak and valley reduction
Visit http://integrated-frontend:8080/rocketmq to experience the corresponding scenario.
Since we previously configured the consumption rate and interval of the integrated-praise-consumer consumer module in Nacos, we simulate 1000 requests for likes at the click of a button, and the integrated-praise-provider
will deliver 1000 requests to the Broker, and the consumer module will consume them according to the configured consumption rate, and update the database with the product data of the likes, simulating the characteristics of RocketMQ to cut the peaks and fill the valleys under high traffic.
You can see that the number of likes in the database is being dynamically updated.
Other
This example is just a selection of typical features for each component to serve the application scenario.
If you are interested or want to go deeper, you are welcome to study the individual example documentation for each component.
- Nacos examples
- Sentinel core example
- Seata example
- RocketMQ example
File: spring-cloud-alibaba-examples/integrated-example/docs/en/kubernetes-deployment.md
Spring Cloud Alibaba Containerized Deployment Best Practices | Kubernetes Helm-Chart Edition
Preparation
This is the Spring Cloud Alibaba (hereinafter referred to as SCA) Best Practices Kubernetes deployment version, which requires you to prepare the following environment.
- Kubernetes (We recommend using Docker Desktop's built-in integrated Kubernetes environment for this experience.)
- Helm
If the test machine does not already have the above environment, please go to the official documentation to build the environment.
Here expose the services of the Pod in Kubernetes to the outside world by means of NodePort, and configure the ip mapping of the Kubernetes cluster node before starting the test.
# Please adjust with the public ip of your K8S node
120.24.xxx.xxx integrated-frontend
120.24.xxx.xxx gateway-service
120.24.xxx.xxx integrated-mysql-web
120.24.xxx.xxx nacos-mysql-web
120.24.xxx.xxx nacos-svcStart the test
Go to the spring-cloud-alibaba-examples/integrated-example directory and execute the following command to deploy the application using Helm.
helm package helm-chart
helm install integrated-example integrated-example-1.0.0.tgzBy running the above command, quickly deploy the best practice example through Helm according to the Helm Chart documentation provided by the SCA community.
You can check the deployment status of each container resource through the kubectl command provided by Kubernetes, and wait patiently for all containers to finish starting to experience the usage scenarios and capabilities of each component on the corresponding page.
If you want to stop the experience, enter the following command.
helm uninstall integrated-exampleDistributed Transaction Capabilities
Scenario Description
For the distributed transaction capability, SCA community provide a scenario where a user places an order to purchase goods and after placing the order.
- First request the inventory module and deduct the inventory
- Deduct the account balance
- Generate order information to return a response
Start test
Visit http://integrated-frontend:30080/order to experience the corresponding scenario.
By clicking directly on the order button to submit the form, simulate the client sending a request to the gateway to create an order.
- The user's userId is admin
- The user places an order with item number 1
- The number of items purchased in this order is 1
In this demo example, the unit price of each item is 2 for demonstration purposes.
While initializing the integrated-mysql container, initializing the business database table creates a new user, the user's userId is admin, with a balance of $3; and a new item numbered 1 with 100 units in stock.
So by doing the above, application will create an order, deduct the number of items in stock corresponding to item number 1 (100-1=99), and deduct the balance of the admin user (3-2=1).
If the same interface is requested again, again the inventory is deducted first (99-1=98), but an exception is thrown because the admin user's balance is insufficient and is caught by Seata, which performs a two-stage commit of the distributed transaction and rolls back the transaction.
You can see that the database still has 99 records in stock because of the rollback.
Fused flow limiting, peak shaving capability
Scenario Description
For service fusion limiting and peak and valley cutting in the context of high traffic, SCA community provide a scenario** where users make likes for products**. In this scenario, we provide two ways to deal with high traffic.
- Sentinel binds specified gateway routes on the gateway side for fusion degradation of services.
- RocketMQ performs traffic clipping, where the producer sends messages to RocketMQ under high traffic requests, while the consumer pulls and consumes through a configurable consumption rate, reducing the pressure of high traffic direct requests to the database to increase the number of likes requests.
Startup test
- Sentinel Service Meltdown Degradation
Visit http://integrated-frontend:30080/sentinel to experience the corresponding scenario.
The Gateway routing point service has a flow limit rule of 5, while 10 concurrent requests are simulated on the front end through asynchronous processing.
Therefore, we can see that Sentinel performs a service fusion on the Gateway side to return the fallback to the client for the extra traffic, while the number of likes in the database is updated (+5).
- RocketMQ is performing peak and valley reduction
Visit http://integrated-frontend:30080/rocketmq to experience the corresponding scenario.
Since the consumption rate and interval of the integrated-praise-consumer consumer module is configured in Nacos before, the application will simulate 1000 "like" requests when clicking the button, integrated-praise-provider
will deliver 1000 requests to the Broker, and the consumer module will consume them according to the configured consumption rate, and update the database with the product data of the likes, simulating the characteristics of RocketMQ to cut the peaks and fill the valleys under high traffic.
You can see that the number of likes in the database is being dynamically updated.
Other
This example is just a selection of typical features for each component to serve the application scenario.
Of course, there is more to each component than just what is demonstrated in the best practices, so if you are interested or want to go deeper, feel free to read the individual example documentation for each component.
- Nacos examples
- Sentinel core example
- Seata example
- RocketMQ example
File: spring-cloud-alibaba-examples/integrated-example/docs/en/local-deployment.md
Spring Cloud Alibaba Containerized Deployment Best Practices | Local Deployment Edition
Preparation
Environment Declaration
Before running the local example, you need to ensure that the local machine has the following basic environment. If you do not have the current local environment, the following steps to demonstrate the construction process.
You can also quickly launch the component through the docker-compose file provided by the Spring Cloud Alibaba (SCA) community.
- Nacos server
- Seata server
- RocketMQ server
- MySQL server
Component Service Versions
For each component version of this project, please go to the release page of each community to download and decompression run.
- Nacos: version 2.1.0
- Seata: version 1.5.1
- RocketMQ: version 4.9.4
- MySQL: version 5.7
Hosts configuration
To ensure that the code can start properly, please configure the local host mapping first, add the following mapping to the configuration file.
# for integrated-example
127.0.0.1 integrated-mysql
127.0.0.1 nacos-server
127.0.0.1 seata-server
127.0.0.1 rocketmq
127.0.0.1 gateway-service
127.0.0.1 integrated-frontendDatabase configuration
Before you start the database configuration, please make sure the MySQL server is on.
Initialize business tables
For the first scenario, the order, account, and inventory microservices all need their own databases, while the second scenario simulates a database for storing like information as well.
Run the sql script spring-cloud-alibaba-examples/integrated-example/config-init/sql/init.sql to create the environment required for the business and the Seata-related tables in one click.
Nacos Configuration
At this point, the database services are configured and you need to configure the Nacos configuration center for all the microservice configuration files.
Nacos startup
For the sake of example, here we use the standalone mode of Nacos, go to the unpacked directory of Nacos and execute the following command.
#Linux/Mac environment
sh bin/startup.sh -m standalone
#If you are in Ubuntu and the above command gives you an error [[symbol not found, you can run the following command
bash bin/startup.sh -m standalone
#Win environment
. \bin\startup.cmd -m standaloneAdding configuration files
Before bulk importing the configuration, please modify the datasource configuration (username and password) in spring-cloud-alibaba-examples/integrated-example/config-init/config/datasource-config.yaml.
After that, run spring-cloud-alibaba-examples/integrated-example/config/scripts/nacos-config-quick.sh to complete the one-click import of all microservice configurations.
# linux
sh nacos-config-quick.sh
# windows can use git bash to import the configuration, run the command as aboveSeata Configuration
After the Nacos service registry and configuration center are deployed, here is the configuration of the Seata server.
Seata's db mode requires additional configuration of database information and modification of the Seata Server configuration file, and the configuration file has been merged in the new version compared to the old version, so for demonstration purposes, Seata Server is started in file mode on Seata standalone.
Start Seata Server
Go to the seata directory after the release and execute the following command.
#Linux/Mac environment
sh . /bin/seata-server.sh
#Win environment
bin\seata-server.batRocketMQ configuration
After the Seata service starts, you can start the RocketMQ NameServer and Broker services.
Go to the unpacked rocketmq directory after the release and execute the following command.
Start the NameServer
#Linux/Mac environment
sh bin/mqnamesrv
#Win environment
. \bin\mqnamesrv.cmdStart Broker
#Linux/Mac environment
sh bin/mqbroker
#Win environment
. \bin\mqbroker.cmdRun the demo example
After the preparation work is done, you can run the demo, mainly according to different usage scenarios, you can experience the user order (distributed transaction capability) and simulate the high traffic point (meltdown and limit the flow as well as the ability to cut the peak and fill the valley) respectively.
First, you need to start the integrated-frontend and integrated-gateway projects separately.
integrated-frontendmodule is front page for best practice examples.integral-gatewaymodule is the gateway for the entire best practice example.
Distributed Transaction Capabilities
Scenario Description
For the distributed transaction capability, we provide the scenario where a user places an order for goods and after placing the order.
- First request the inventory module and deduct the inventory
- Deduct the account balance
- Generate order information to return a response
Start test
Start integrated-storage,integrated-account,integrated-order microservices respectively.
Visit http://integrated-frontend:8080/order to experience the corresponding scenario.
By clicking the order button directly to submit the form, application simulate the client sending a request to the gateway to create an order.
- The user's userId is admin
- The item number of the user's order is 1
- The number of items purchased in this order is 1
In this demo example, the unit price of each item is 2 for demonstration purposes.
And in the previous preparation, initialize business database table application created a new user, the user's userId is admin with a balance of $3, and a new item numbered 1 with 100 units in stock.
So by doing the above, we will create an order, deduct the number of items in stock corresponding to item number 1 (100-1=99), and deduct the balance of the admin user (3-2=1).
If the same interface is requested again, again the inventory is deducted first (99-1=98), but an exception is thrown because the admin user's balance is insufficient and is caught by Seata, which performs a two-stage commit of the distributed transaction and rolls back the transaction.
You can see that the database still has 99 records in stock because of the rollback.
Fused flow limiting, peak shaving capability
Scenario Description
For service fusion limiting and peak and valley cutting in the context of high traffic, SCA community provide a scenario where users make likes for products. In this scenario, we provide two ways to deal with high traffic.
- Sentinel binds specified gateway routes on the gateway side for fusion degradation of services.
- RocketMQ performs traffic clipping, where the producer sends messages to RocketMQ under high traffic requests, while the consumer pulls and consumes through a configurable consumption rate, reducing the pressure of high traffic direct requests to the database to increase the number of likes requests.
Startup test
Start the integrated-praise-provider and integrated-praise-consumer modules separately.
- Sentinel service meltdown degradation
Visit http://integrated-frontend:8080/sentinel to experience the corresponding scenario.
The Gateway routing point service has a flow limit rule of 5, while 10 concurrent requests are simulated on the front end through asynchronous processing.
Therefore, we can see that Sentinel performs a service fusion on the Gateway side to return the fallback to the client for the extra traffic, while the number of likes in the database is updated (+5).
- RocketMQ is performing peak and valley reduction
Visit http://integrated-frontend:8080/rocketmq to experience the corresponding scenario.
Since previously configured the consumption rate and interval of the integrated-praise-consumer consumer module in Nacos, simulate 1000 requests for likes at the click of a button, and the integrated-praise-provider
will deliver 1000 requests to the Broker, and the consumer module will consume them according to the configured consumption rate, and update the database with the product data of the likes, simulating the characteristics of RocketMQ to cut the peaks and fill the valleys under high traffic.
You can see that the number of likes in the database is being dynamically updated.
Other
This example is just a selection of typical features for each component to serve the application scenario.
If you are interested or want to go deeper, you are welcome to study the individual example documentation for each component.