1
0
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:
fangjian0423 2019-07-29 17:35:35 +08:00
parent 301d133238
commit 4f56165658
26 changed files with 1224 additions and 503 deletions

View File

@ -1,8 +1,10 @@
== Spring Cloud Alibaba Cloud ACM
== Spring Cloud AliCloud ACM
Spring Cloud AliCloud ACM 是阿里云提供的商业版应用配置管理(Application Configuration Management) 产品 在 Spring Cloud 应用侧的客户端实现,且目前完全免费。
Spring Cloud AliCloud ACM 是 Config Server 和 Client 的替代方案,客户端和服务器上的概念与 Spring Environment 和 PropertySource 有着一致的抽象,在特殊的 bootstrap 阶段,配置被加载到 Spring 环境中。当应用程序通过部署管道从开发到测试再到生产时,您可以管理这些环境之间的配置,并确保应用程序具有迁移时需要运行的所有内容。
使用 Spring Cloud AliCloud ACM可基于 Spring Cloud 的编程模型快速接入 ACM 配置管理功能。
NOTE: 目前 EDAS 已经支持直接部署 Nacos Config 应用
=== 如何引入 Spring Cloud AliCloud ACM
@ -171,4 +173,4 @@ NOTE: 如果设置了 `spring.profiles.active` DataId 的格式还支持 `{sp
=== Actuator 监控
ACM 对应的 Actuator 监控地址为 `/acm`,其中 config 代表了 ACM 元数据配置的信息,`runtime.sources` 对应的是从 ACM 服务端获取的配置的信息及最后刷新时间, `runtime.refreshHistory` 对应的是动态刷新的历史记录。
ACM 对应的 Actuator 监控地址为 `/acm`,其中 `config` 代表了 ACM 元数据配置的信息,`runtime.sources` 对应的是从 ACM 服务端获取的配置的信息及最后刷新时间, `runtime.refreshHistory` 对应的是动态刷新的历史记录。

View File

@ -1,7 +1,9 @@
== Spring Cloud Alibaba Cloud ANS
== Spring Cloud AliCloud ANS
ANSApplication Naming Service 是隶属于阿里云 EDAS 产品的组件, Spring Cloud AliCloud ANS 提供了 Spring Cloud 规范下商业版的服务注册与发现,可以让用户方便的在本地开发,同时也可以运行在云环境里。
NOTE: 目前 EDAS 已经支持直接部署 Nacos Discovery 应用
=== 如何引入 Spring Cloud AliCloud ANS
如果要在您的项目中引入 ANS使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alicloud-ans` 的 starter。
@ -91,4 +93,3 @@ access-key 和 secret-key 则是阿里云账号的 AK/SK需要首先注册阿
namespace 是阿里云 EDAS 产品的概念,用于隔离不同的环境,比如测试环境和生产环境。要获取 namespace 需要 https://common-buy.aliyun.com/?spm=5176.11451019.0.0.6f5965c0Uq5tue&commodityCode=edaspostpay#/buy[开通 EDAS 服务],按量计费模式下开通是免费的,开通以后进入 https://edas.console.aliyun.com/#/namespaces?regionNo=cn-hangzhou[EDAS控制台],即可看到对应的 namespace比如 cn-hangzhou。
NOTE: EDAS 提供应用托管服务,如果你将应用托管到 EDAS那么 EDAS 将会自动为你填充所有配置。

View File

@ -2,8 +2,6 @@
Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。
### Spring Cloud Alibaba Bill of Materials (BOM)
如果您是 Maven Central 用户,请将我们的 BOM 添加到您的 pom.xml 中的 <dependencyManagement> 部分。 这将允许您省略任何Maven依赖项的版本而是将版本控制委派给BOM。
```xml
@ -12,7 +10,7 @@ Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<version>1.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -20,23 +18,5 @@ Spring Cloud Alibaba BOM 包含了它所使用的所有依赖的版本。
</dependencyManagement>
```
### Spring Snapshots Maven Repository
如果要使用最新的 BUILD-SNAPSHOT 版本,请在 pom.xml 中添加 Spring Snapshot Repository注意BUILD-SNAPSHOT随时可能更新:
```xml
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring SnapShots</name>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
```
举个例子, 0.2.0.BUILD-SNAPSHOT 版本就在这个仓库中可用。
在下面的章节中,假设您使用的是 Spring Cloud Alibaba bom相关 starter 依赖将不包含版本号。

View File

@ -0,0 +1,47 @@
== Spring Cloud Alibaba Dubbo
=== 简介
Dubbo Spring Cloud 基于 Dubbo Spring Boot 2.7.3[1] 和 Spring Cloud 2.x 开发,无论开发人员是 Dubbo 用户还是 Spring Cloud 用户,
都能轻松地驾驭并以接近“零”成本的代价使应用向上迁移。Dubbo Spring Cloud 致力于简化 Cloud Native 开发成本,提高研发效能以及提升应用性能等目的。
=== 功能
由于 Dubbo Spring Cloud 构建在原生的 Spring Cloud 之上,其服务治理方面的能力可认为是 Spring Cloud Plus
不仅完全覆盖 Spring Cloud 原生特性[5],而且提供更为稳定和成熟的实现,特性比对如下表所示:
:frame: topbot
[width="60%",options="header"]
|====
^|功能组件 ^|Spring Cloud ^|Dubbo Spring Cloud
| 分布式配置Distributed configuration | Git、Zookeeper、Consul、JDBC | Spring Cloud 分布式配置 + Dubbo 配置中心[6]
| 服务注册与发现Service registration and discovery | Eureka、Zookeeper、Consul | Spring Cloud 原生注册中心[7] + Dubbo 原生注册中心[8]
| 负载均衡Load balancing | Ribbon随机、轮询等算法 | Dubbo 内建实现(随机、轮询等算法 + 权重等特性)
| 服务熔断Circuit Breakers | Spring Cloud Hystrix | Spring Cloud Hystrix + Alibaba Sentinel[9] 等
| 服务调用Service-to-service calls | Open Feign、`RestTemplate` | Spring Cloud 服务调用 + Dubbo `@Reference`
| 链路跟踪Tracing | Spring Cloud Sleuth[10] + Zipkin[11] | Zipkin、opentracing 等
|====
=== Reference 说明
[1]: 从 2.7.0 开始Dubbo Spring Boot 与 Dubbo 在版本上保持一致
[2]: Preview releases of Spring Cloud Alibaba are available: 0.9.0, 0.2.2, and 0.1.2 - https://spring.io/blog/2011/04/11/preview-releases-of-spring-cloud-alibaba-are-available-0-9-0-0-2-2-and-0-1-2
[3]: 目前最新的 Spring Cloud “F” 版的版本为:`Finchley.SR2` - https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html
[4]: 当前Spring Cloud “G” 版为 `Greenwich.RELEASE`
[5]: Spring Cloud 特性列表 - https://cloud.spring.io/spring-cloud-static/Greenwich.RELEASE/single/spring-cloud.html#_features
[6]: Dubbo 2.7 开始支持配置中心,可自定义适配 - http://dubbo.apache.org/zh-cn/docs/user/configuration/config-center.html
[7]: Spring Cloud 原生注册中心,除 Eureka、Zookeeper、Consul 之外,还包括 Spring Cloud Alibaba 中的 Nacos
[8]: Dubbo 原生注册中心 - http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html
[9]: Alibaba SentinelSentinel 以流量为切入点,从流量控制、熔断降级、系统负载保护等多个维度保护服务的稳定性 - https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B%E7%BB%8D ,目前 Sentinel 已被 Spring Cloud 项目纳为 Circuit Breaker 的候选实现 - https://spring.io/blog/2011/04/8/introducing-spring-cloud-circuit-breaker
[10]:Spring Cloud Sleuth - https://spring.io/projects/spring-cloud-sleuth
[11]: Zipkin - https://github.com/apache/incubator-zipkin

View File

@ -0,0 +1,19 @@
## 介绍
Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。
依托 Spring Cloud Alibaba您只需要添加一些注解和少量配置就可以将 Spring Cloud 应用接入阿里分布式应用解决方案,通过阿里中间件来迅速搭建分布式应用系统。
目前 Spring Cloud Alibaba 提供了如下功能:
1. **服务限流降级**:支持 WebServlet、WebFlux, OpenFeign、RestTemplate、Dubbo 限流降级功能的接入,可以在运行时通过控制台实时修改限流降级规则,还支持查看限流降级 Metrics 监控。
2. **服务注册与发现**:适配 Spring Cloud 服务注册与发现标准,默认集成了 Ribbon 的支持。
3. **分布式配置管理**:支持分布式系统中的外部化配置,配置更改时自动刷新。
4. **Rpc服务**:扩展 Spring Cloud 客户端 RestTemplate 和 OpenFeign支持调用 Dubbo RPC 服务
5. **消息驱动能力**:基于 Spring Cloud Stream 为微服务应用构建消息驱动能力。
6. **分布式事务**:使用 @GlobalTransactional 注解, 高效并且对业务零侵入地解决分布式事务问题。
7. **阿里云对象存储**:阿里云提供的海量、安全、低成本、高可靠的云存储服务。支持在任何应用、任何时间、任何地点存储和访问任意类型的数据。
8. **分布式任务调度**:提供秒级、精准、高可靠、高可用的定时(基于 Cron 表达式)任务调度服务。同时提供分布式的任务执行模型,如网格任务。网格任务支持海量子任务均匀分配到所有 Workerschedulerx-client上执行。
9. **阿里云短信服务**:覆盖全球的短信服务,友好、高效、智能的互联化通讯能力,帮助企业迅速搭建客户触达通道。
Spring Cloud Alibaba 也提供了丰富的 https://github.com/alibaba/spring-cloud-alibaba/tree/master/spring-cloud-alibaba-examples[examples]。

View File

@ -1,116 +0,0 @@
= SCA Nacos Config 共享配置方案设计
随着社区的回馈,发现 Spring Cloud Alibaba Nacos Config Starter 目前不能完美的来支持多个应用间的一些共享配置。
在实际的业务场景中应用和共享配置间的关系可能如下图所示:
image::http://edas.oss-cn-hangzhou.aliyuncs.com/sca/sca_shared_01.png[]
* 从单个应用的角度来看: 应用可能会有多套(develop/beta/product)发布环境,多套发布环境之间有不同的基础配置,例如数据库。
* 从多个应用的角度来看多个应用间可能会有一些共享通用的配置比如多个应用之间共用一套zookeeper集群。
目前 SCA Nacos Config 可以灵活的支持单个应用间在多套环境可灵活的切换,但是在多个应用间共享一些通用的配置支持的还不是很完美。
本方案设计的目标就是来解决这个问题。目前有三种设计方案,分别是:
* 新增一个应用分组的配置,分组命名的格式是 通过域名的命名方式,来自动的生成共享配置的 Data Id。
* 自定义命名的方式来命名 Data Id 。
* 通过类似面向对象的方式自定义配置(相对于第二种的升级版)。
下面分别来分析三种方案的具体实现和优缺点。
== 基于域名的配置方式给应用分组
通过一个配置参数(例如:${spring.application.group}) 来指明当前应用所属的分组(或者说所属的域)。
例如我有两个应用分别为Order_Application和Auth_Application给这两个应用配置的分组名(域)是:
.bootstrap.properties
----
spring.application.group=com.alibaba.aliware.edas
----
那对于Spring Cloud Alibaba Nacos Config 来说,多个应用可以属于 com.alibaba 这个应用分组(域),也可以属于
com.alibaba.aliware 这个应用分组(域),当然也可以属于 com.alibaba.aliware.edas 这个应用分组(域)。
罗里吧嗦了这么多,目的就是 Data Id 通过以这个分组(域)来命名,从而实现多个应用间在某个分组(域)下的共享配置。如下图所示:
image::http://edas.oss-cn-hangzhou.aliyuncs.com/sca/sca_shared_02.png[]
以这种方式来实现多个应用间的配置共享,可以看出他具有天然的局限性。
* 受到 ${spring.application.group }配置的影响Data Id 的表现力是非常有限的(当然85%的场景应该够用了)。
** 一方面是Data Id 的命名个数受到了限制。
** 另一方面如果两个应用的 file-extension 不一致(一个是properties,一个是yaml)那这个时候共享配置的Data Id 必须同时要含有 properties 和 yaml 为扩展名的配置。
** Data Id 的命名也受到了 ${spring.application.group } 配置的束缚。
* 学习成本偏高(当然还是可以学会的)。学习成本偏高体现在:
** 要知道Data Id 的命名规则,才能在项目实施过程中对 Data Id 的命名运用自如。
** 此外对于域名命名的层次个数也不太好把握。少了的话担心dataid的个数不够用多了的话看上去有显得的比较冗余。
** 还需要学习并理解这里配置的优先级,不然在程序中有可能就会拿到意想不到的配置。
* 易出错(当然是可以克服的)。对于多级应用分组的配置共享这个时候Data Id 的命名要格外注意了。注意他们的层次关系Data Id 书写时不要张冠李戴。
* 实现起来稍微复杂
当然他的好处也非常明显,当你理解了他背后的设计理念时,这个共享配置的层次也非常明显。因为层次的关系天然依托于域名的层次关系。
== 自定义的方式来命名 Data Id
这种方式实现简单易懂,即 SCA Nacos Config 会新增加一个配置,用来配置可实现共享配置所有的 Data Id。如下所示
.bootstrap.properties
----
spring.cloud.nacos.shared.dataids=global.yaml,app-common.yaml,app-local-common.yaml
----
NOTE: 为了尽可能的和Nacos使用方式(即Data Id 是一个带有额外文件扩展名的)保持一致这里配置的Data Id 是一定需要带上文件扩展名的。
这个时候两个应用(或多个应用)之间共享配置的 Data Id 关系如下图所示:
image::http://edas.oss-cn-hangzhou.aliyuncs.com/sca/sca_shared_03.png[]
Spring Boot 提倡约定大于配置。当使用这种方式来实现应用间的共享配置时我们也继承了Spring Boot的这个优良传统多个共享配置间的一个优先级的关系我们约定按照配置出现的先后顺序即后面的优先级要高于前面的。
这种方式的优点在于:
* dataid的命名方式完全交给业务方本身不受 SCA Nacos Config Starter 实现的束缚。
* dataid的命名方式既可以参考第一种方式来命名又可以充分的发挥主观能动性结合自己实际的业务给dataid命名。
* 减少了多个应用间如果file-extension不一致为每个 file-extension 多加这么一个配置的麻烦。
* 当使用这种方式时,不会为这些共享配置强制绑定一个 file-extenson即可以直接在我们暴露出来的一个变量中 dataid以file-extension 结尾。如果没有显示的说明这个时候就会以file-extenson为准。
当然这种方案的缺点在于扩展性不强。即如果对于某个共享配置需要做额外的配置例如额外配置Group/是否需要刷新/是否需要从本地缓存加载等等。因此为了应对这种类型的场景,小组内讨论出了第三种方案。
== 通过类似面向对象方式的自定义配置
说明Spring 可以支持在加了 ConfigurationProperties 注解配置类的内部某个对象实例来注入应用中的一些配置。
这种使用方式查了一下官方和网络上没有一个大的标题总结,结合这种方式很像给某个实例中的字段赋值,所以这里先暂时取名:
类似面向对象方式的自定义配置(有更好能够形象的标明其含义的命名可以在下面留下评论-_-)。
这种方案沿用了第二种设计方案的优点,同时又弥补了第二种方案的不足。我们通过内部定义一个对象,来支持一些灵活的扩展配置。
我们给这个对象可以预留一些可扩展的配置字段。例如:
.Config.java
----
public class Config{
private String dataId;
private String group = "DEFAULT_GROUP";
private Boolean refresh = false;
//.....后期可能还有其他的一些配置
//省略 set/get 方法
}
----
最终在实现时是可以支持以list的方式来配置其值。如下是两个扩展配置的实例
.bootstrap.properties
----
spring.cloud.nacos.config.ext-config[0].data-id=global-shared.properties # group 和referesh 使用默认值
spring.cloud.nacos.config.ext-config[1].data-id=app-common.properties
spring.cloud.nacos.config.ext-config[1].group=DEVELOP_GROUP #配置自定义所在的组
spring.cloud.nacos.config.ext-config[1].refresh=true #需要刷新
----
NOTE: 为了尽可能的和Nacos使用方式(即data id是一个带有额外文件扩展名的)保持一致这里配置的dataid是一定需要带上文件扩展名的。
== 最终的实现
SCA Nacos Config 在第二种方案和第三种方案的实现上是并存的。如果你觉得第三种方案配置的比较麻烦,同时第二种方案就可以满足你的需求,这个时候就可以选择第二种方案。
如果你需外可读性好、层级感比较明显、后期的扩展性更强那这个时候第三种方案也是OK的。

View File

@ -1,16 +1,35 @@
== Spring Cloud Alibaba Nacos Config
Nacos 提供用于存储配置和其他元数据的 key/value 存储,为分布式系统中的外部化配置提供服务器端和客户端支持。使用 Spring Cloud Alibaba Nacos Config您可以在 Nacos Server 集中管理你 Spring Cloud 应用的外部属性配置
Nacos 是一个 Alibaba 开源的、易于构建云原生应用的动态服务发现、配置管理和服务管理平台
Spring Cloud Alibaba Nacos Config 是 Config Server 和 Client 的替代方案,客户端和服务器上的概念与 Spring Environment 和 PropertySource 有着一致的抽象,在特殊的 bootstrap 阶段,配置被加载到 Spring 环境中。当应用程序通过部署管道从开发到测试再到生产时,您可以管理这些环境之间的配置,并确保应用程序具有迁移时需要运行的所有内容。
使用 Spring Cloud Alibaba Nacos Config可基于 Spring Cloud 的编程模型快速接入 Nacos 配置管理功能。
=== 如何引入 Nacos Config 进行配置管理
如果要在您的项目中使用 Nacos 来实现配置管理,使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alibaba-nacos-config` 的 starter。
[source,xml,indent=0]
----
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
----
=== 快速开始
===== Nacos 服务端初始化
Nacos Config 使用 DataId 和 GROUP 确定一个配置。
1、启动Nacos Server。启动方式可见 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]
下图表示 DataId 使用 `myDataid`, GROUP 使用 `DEFAULT_GROUP`,配置格式为 Properties 的一个配置项:
2、启动好Nacos之后在Nacos添加如下的配置
.Nacos Config Item
image::https://img.alicdn.com/tfs/TB1Yli3bUY1gK0jSZFMXXaWcVXa-2436-1138.png[]
==== Nacos 服务端初始化
具体启动方式参考 Spring Cloud Alibaba Nacos Discovery 小节的 "Nacos Server 启动" 章节。
Nacos Server 启动完毕后,添加如何配置:
[source,subs="normal"]
----
@ -24,9 +43,9 @@ Group : DEFAULT_GROUP
user.age=90
----
NOTE: 注意dataid是以 properties(默认的文件扩展名方式)为扩展名。
NOTE: 注意DataId是以 properties(默认的文件扩展名方式)为扩展名。
===== 客户端使用方式
==== 客户端使用方式
如果要在您的项目中使用 Nacos 来实现应用的外部化配置,使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alibaba-nacos-config` 的 starter。
@ -38,15 +57,15 @@ NOTE: 注意dataid是以 properties(默认的文件扩展名方式)为扩展名
</dependency>
----
现在就可以创建一个标准的 Spring Boot 应用。
现在创建一个标准的 Spring Boot 应用。
[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(ConfigApplication.class, args);
String userName = applicationContext.getEnvironment().getProperty("user.name");
String userAge = applicationContext.getEnvironment().getProperty("user.age");
System.err.println("user name :"+userName+"; age: "+userAge);
@ -54,11 +73,12 @@ public class ProviderApplication {
}
----
在运行此 Example 之前, 必须使用 bootstrap.properties 配置文件来配置Nacos Server 地址,例如:
在运行此 NacosConfigApplication 之前, 必须使用 `bootstrap.properties` 配置文件来配置 Nacos Server 地址,例如:
.bootstrap.properties
[source,properties]
----
# DataId 默认使用 `spring.application.name` 配置跟文件扩展名结合(配置格式默认使用 properties), GROUP 不配置默认使用 DEFAULT_GROUP。因此该配置文件对应的 Nacos Config 配置的 DataId 为 nacos-config.properties, GROUP 为 DEFAULT_GROUP
spring.application.name=nacos-config
spring.cloud.nacos.config.server-addr=127.0.0.1:8848
----
@ -71,17 +91,16 @@ NOTE: 注意当你使用域名的方式来访问 Nacos 时,`spring.cloud.nacos
[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.ConfigApplication : Started ConfigApplication 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
----
=== 基于 dataid 为 yaml 的文件扩展名配置方式
=== 基于 DataId 为 yaml 的文件扩展名配置方式
spring-cloud-starter-alibaba-nacos-config 对于 yaml 格式也是完美支持的。这个时候只需要完成以下两步:
Nacos Config 除了支持 properties 格式以外,也支持 yaml 格式。这个时候只需要完成以下两步:
1、在应用的 bootstrap.properties 配置文件中显示的声明 dataid 文件扩展名。如下所示
1、在应用的 bootstrap.properties 配置文件中显示的声明 DataId 文件扩展名。如下所示
.bootstrap.properties
[source,yaml]
@ -89,7 +108,7 @@ spring-cloud-starter-alibaba-nacos-config 对于 yaml 格式也是完美支持
spring.cloud.nacos.config.file-extension=yaml
----
2、在 Nacos 的控制台新增一个dataid为yaml为扩展名的配置如下所示
2、在 Nacos 的控制台新增一个DataId为yaml为扩展名的配置如下所示
[source,subs="normal"]
----
@ -107,22 +126,22 @@ Group : DEFAULT_GROUP
[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.ConfigApplication:Started ConfigApplication 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
----
=== 支持配置的动态更新
spring-cloud-starter-alibaba-nacos-config 也支持配置的动态更新,启动 Spring Boot 应用测试的代码如下:
Nacos Config 默认支持配置的动态更新,启动 Spring Boot 应用测试的代码如下:
[source,java]
----
@SpringBootApplication
public class ProviderApplication {
public class ConfigApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigApplication.class, args);
while(true) {
//当动态配置刷新时,会更新到 Enviroment中因此这里每隔一秒中从Enviroment中获取配置
String userName = applicationContext.getEnvironment().getProperty("user.name");
@ -151,9 +170,9 @@ user name :nacos-config-yaml-update; age: 68
NOTE: 你可以通过配置 `spring.cloud.nacos.config.refresh.enabled=false` 来关闭动态刷新
=== 支持profile粒度的配置
=== 支持profile粒度的配置
spring-cloud-starter-alibaba-nacos-config 在加载配置的时候,不仅仅加载了以 dataid 为 `${spring.application.name}.${file-extension:properties}` 为前缀的基础配置,还加载了dataid为 `${spring.application.name}-${profile}.${file-extension:properties}` 的基础配置。在日常开发中如果遇到多套环境下的不同配置可以通过Spring 提供的 `${spring.profiles.active}` 这个配置项来配置。
Nacos Config 在加载配置的时候,不仅仅加载了以 DataId 为 `${spring.application.name}.${file-extension:properties}` 为前缀的基础配置,还加载了DataId为 `${spring.application.name}-${profile}.${file-extension:properties}` 的基础配置。在日常开发中如果遇到多套环境下的不同配置可以通过Spring 提供的 `${spring.profiles.active}` 这个配置项来配置。
[source,properties]
----
@ -162,7 +181,7 @@ spring.profiles.active=develop
NOTE: ${spring.profiles.active} 当通过配置文件来指定时必须放在 bootstrap.properties 文件中。
Nacos 上新增一个dataid为nacos-config-develop.yaml的基础配置如下所示
Nacos 上新增一个DataId为nacos-config-develop.yaml的基础配置如下所示
[source,subs="normal"]
----
@ -180,10 +199,10 @@ Group : DEFAULT_GROUP
[source,java]
----
@SpringBootApplication
public class ProviderApplication {
public class ConfigApplication {
public static void main(String[] args) {
ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
ConfigurableApplicationContext applicationContext = SpringApplication.run(ConfigApplication.class, args);
while(true) {
String userName = applicationContext.getEnvironment().getProperty("user.name");
String userAge = applicationContext.getEnvironment().getProperty("user.age");
@ -210,7 +229,7 @@ in develop-env enviroment; user name :nacos-config-yaml-update; age: 68
spring.profiles.active=product
----
同时生产环境上 Nacos 需要添加对应 dataid 的基础配置。例如,在生成环境下的 Naocs 添加了dataid为nacos-config-product.yaml的配置
同时生产环境上 Nacos 需要添加对应 DataId 的基础配置。例如,在生成环境下的 Naocs 添加了DataId为nacos-config-product.yaml的配置
[source,subs="normal"]
----
@ -235,7 +254,8 @@ in product-env enviroment; user name :nacos-config-yaml-update; age: 68
NOTE: 此案例中我们通过 `spring.profiles.active=<profilename>` 的方式写死在配置文件中,而在真正的项目实施过程中这个变量的值是需要不同环境而有不同的值。这个时候通常的做法是通过 `-Dspring.profiles.active=<profile>` 参数指定其配置来达到环境间灵活的切换。
=== 支持自定义 namespace 的配置
首先看一下 Nacos 的 Namespace 的概念, https://nacos.io/zh-cn/docs/concepts.html[Nacos 概念]
Nacos 内部有 https://nacos.io/zh-cn/docs/concepts.html[Namespace 的概念]:
[quote]
用于进行租户粒度的配置隔离。不同的命名空间下,可以存在相同的 Group 或 Data ID 的配置。Namespace 的常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等。
@ -261,7 +281,7 @@ NOTE: 该配置必须放在 bootstrap.properties 文件中。并且在添加配
=== 支持自定义扩展的 Data Id 配置
Spring Cloud Alibaba Nacos Config 从 0.2.1 版本后,可支持自定义 Data Id 的配置。关于这部分详细的设计可参考 https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/141[这里]。
Nacos Config 从 0.2.1 版本后,可支持自定义 Data Id 的配置。关于这部分详细的设计可参考 https://github.com/spring-cloud-incubator/spring-cloud-alibaba/issues/141[这里]。
一个完整的配置案例如下所示:
[source,properties]
@ -318,4 +338,98 @@ NOTE: 通过 `spring.cloud.nacos.config.shared-dataids` 来支持多个共享配
NOTE: 通过 `spring.cloud.nacos.config.shared-dataids` 来配置时Data Id 必须带文件扩展名,文件扩展名既可支持 properties也可以支持 yaml/yml。
此时 `spring.cloud.nacos.config.file-extension` 的配置对自定义扩展配置的 Data Id 文件扩展名没有影响。
NOTE: `spring.cloud.nacos.config.refreshable-dataids` 给出哪些需要支持动态刷新时Data Id 的值也必须明确给出文件扩展名。
NOTE: `spring.cloud.nacos.config.refreshable-dataids` 给出哪些需要支持动态刷新时Data Id 的值也必须明确给出文件扩展名。
=== 配置的优先级
Nacos Config 目前提供了三种配置能力从 Nacos 拉取相关的配置
* A: 通过 `spring.cloud.nacos.config.shared-dataids` 支持多个共享 Data Id 的配置
* B: 通过 `spring.cloud.nacos.config.ext-config[n].data-id` 的方式支持多个扩展 Data Id 的配置
* C: 通过内部相关规则(应用名、应用名+ Profile )自动生成相关的 Data Id 配置
当三种方式共同使用时,他们的一个优先级关系是:A < B < C
=== Nacos Config 对外暴露的 Endpoint
Nacos Config 内部提供了一个 Endpoint, 对应的 endpoint id 为 `nacos-config`。
Endpoint 暴露的 json 中包含了三种属性:
1. Sources: 当前应用配置的数据信息
2. RefreshHistory: 配置刷新的历史记录
3. NacosConfigProperties: 当前应用 Nacos 的基础配置信息
这是 Endpoint 暴露的 json 示例:
[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"
}]
}
----
=== 完全关闭 Nacos Config 的自动化配置
通过设置 spring.cloud.nacos.config.enabled = false 来完全关闭 Spring Cloud Nacos Config
=== 关于 Nacos Config Starter 更多的配置项信息
更多关于 Nacos Config Starter 的配置项如下所示:
:frame: topbot
[width="60%",options="header"]
|====
^|配置项 ^|Key ^|默认值 ^|说明
|服务端地址|`spring.cloud.nacos.config.server-addr`|| Nacos Server 启动监听的ip地址和端口
|配置对应的 DataId|`spring.cloud.nacos.config.name`|| 先取 prefix再去 name最后取 spring.application.name
|配置对应的 DataId|`spring.cloud.nacos.config.prefix`|| 先取 prefix再去 name最后取 spring.application.name
|配置内容编码|`spring.cloud.nacos.config.encode`||读取的配置内容对应的编码
|GROUP|`spring.cloud.nacos.config.group`|`DEFAULT_GROUP`|配置对应的组
|文件扩展名|`spring.cloud.nacos.config.fileExtension`|`properties`|配置项对应的文件扩展名,目前支持 properties 和 yaml(yml)
|获取配置超时时间|`spring.cloud.nacos.config.timeout`|`3000`|客户端获取配置的超时时间(毫秒)
|接入点|`spring.cloud.nacos.config.endpoint`||地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址
|命名空间|`spring.cloud.nacos.config.namespace`||常用场景之一是不同环境的配置的区分隔离,例如开发测试环境和生产环境的资源(如配置、服务)隔离等
|AccessKey|`spring.cloud.nacos.config.accessKey`||当要上阿里云时,阿里云上面的一个云账号名
|SecretKey|`spring.cloud.nacos.config.secretKey`||当要上阿里云时,阿里云上面的一个云账号密码
|Nacos Server 对应的 context path|`spring.cloud.nacos.config.contextPath`||Nacos Server 对外暴露的 context path
|集群|`spring.cloud.nacos.config.clusterName`||配置成Nacos集群名称
|共享配置|`spring.cloud.nacos.config.sharedDataids`||共享配置的 DataId, "," 分割
|共享配置动态刷新|`spring.cloud.nacos.config.refreshableDataids`||共享配置中需要动态刷新的 DataId, "," 分割
|自定义 Data Id 配置|`spring.cloud.nacos.config.extConfig`||属性是个集合,内部由 `Config` POJO 组成。`Config` 有 3 个属性,分别是 `dataId`, `group` 以及 `refresh`
|====

View File

@ -1,17 +1,18 @@
== Spring Cloud Alibaba Nacos Discovery
该项目通过自动配置以及其他 Spring 编程模型的习惯用法为 Spring Boot 应用程序在服务注册与发现方面提供和 Nacos 的无缝集成。
通过一些简单的注解,您可以快速来注册一个服务,并使用经过双十一考验的 Nacos 组件来作为大规模分布式系统的服务注册中心。
Nacos 是一个 Alibaba 开源的、易于构建云原生应用的动态服务发现、配置管理和服务管理平台。
=== 服务注册发现: Nacos Discovery Starter
使用 Spring Cloud Alibaba Nacos Discovery可基于 Spring Cloud 的编程模型快速接入 Nacos 服务注册功能。
=== 服务注册/发现: Nacos Discovery
服务发现是微服务架构体系中最关键的组件之一。如果尝试着用手动的方式来给每一个客户端来配置所有服务提供者的服务列表是一件非常困难的事,而且也不利于
服务的动态扩缩容。Nacos Discovery Starter 可以帮助您将服务自动注册到 Nacos 服务端并且能够动态感知和刷新某个服务实例的服务列表。除此之外Nacos
Discovery Starter 也将服务实例自身的一些元数据信息-例如 hostport,健康检查URL主页等-注册到 Nacos 。Nacos 的获取和启动方式可以参考 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]。
服务的动态扩缩容。Nacos Discovery 可以帮助您将服务自动注册到 Nacos 服务端并且能够动态感知和刷新某个服务实例的服务列表。除此之外Nacos
Discovery 也将服务实例自身的一些元数据信息-例如 hostport, 健康检查URL主页等内容注册到 Nacos。Nacos 的获取和启动方式可以参考 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]。
==== 如何引入 Nacos Discovery Starter
=== 如何引入 Nacos Discovery 进行服务注册/发现
如果要在您的项目中使用 Nacos 来实现服务发现,使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alibaba-nacos-discovery` 的 starter。
如果要在您的项目中使用 Nacos 来实现服务注册/发现,使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alibaba-nacos-discovery` 的 starter。
[source,xml,indent=0]
----
@ -21,12 +22,27 @@ Discovery Starter 也将服务实例自身的一些元数据信息-例如 host
</dependency>
----
==== 启动一个 Provider 应用
=== 一个使用 Nacos Discovery 进行服务注册/发现并调用的例子
Nacos Discovery 适配了 Netflix Ribbon可以使用 RestTemplate 或 OpenFeign 进行服务的调用。
==== Nacos Server 启动
具体启动方式参考 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]。
Nacos Server 启动后,进入 http://ip:8848 查看控制台(默认账号名/密码为 nacos/nacos):
.Nacos Dashboard
image::https://img.alicdn.com/tfs/TB1dyWJbQL0gK0jSZFtXXXQCXXa-2788-1086.png[]
关于更多的 Nacos Server 版本,可以从 https://github.com/alibaba/nacos/releases[release 页面] 下载最新的版本。
==== Provider 应用
以下步骤向您展示了如何将一个服务注册到 Nacos。
1. pom.xml的配置。一个完整的 pom.xml 配置如下所示:
[source, xml]
* pom.xml的配置。一个完整的 pom.xml 配置如下所示:
[source,xml,indent=0]
----
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
@ -98,9 +114,9 @@ Discovery Starter 也将服务实例自身的一些元数据信息-例如 host
</project>
----
2. application.properties 配置。一些关于 Nacos 基本的配置也必须在 application.properties(也可以是application.yaml)配置,如下所示:
* application.properties 配置。一些关于 Nacos 基本的配置也必须在 application.properties(也可以是application.yaml)配置,如下所示:
application.properties
[source,properties]
[source,properties,indent=0]
----
server.port=8081
spring.application.name=nacos-producer
@ -111,7 +127,7 @@ management.endpoints.web.exposure.include=*
NOTE: 如果不想使用 Nacos 作为您的服务注册与发现,可以将 `spring.cloud.nacos.discovery` 设置为 `false`。
3. 启动 Provider 示例。如下所示:
* 启动 Provider 示例。如下所示:
[source,java,indent=0]
----
@SpringBootApplication
@ -134,19 +150,79 @@ public class NacosProviderDemoApplication {
这个时候你就可以在 Nacos的控制台上看到注册上来的服务信息了。
NOTE: 再启动 Provider 应用之前 请先将 Nacos 服务启动。具体启动方式可参考 https://nacos.io/zh-cn/docs/quick-start.html[Naco 官网]。
==== Consumer 应用
=== 服务的 EndPoint
Consumer 应用可能还没像启动一个 Provider 应用那么简单。因为在 Consumer 端需要去调用 Provider 端提供的REST 服务。例子中我们使用最原始的一种方式,
即显示的使用 LoadBalanceClient 和 RestTemplate 结合的方式来访问。
pom.xml 和 application.properties 的配置可以参考 1.2 小结。启动一个 Consumer应用的示例代码如下所示
spring-cloud-starter-alibaba-nacos-discovery 在实现的时候提供了一个EndPoint,EndPoint的访问地址为 `http://ip:port/actuator/nacos-discovery`。
EndPoint 的信息主要提供了两类:
NOTE: 通过带有负载均衡的RestTemplate 和 FeignClient 也是可以访问的。
1、subscribe: 显示了当前有哪些服务订阅者
2、NacosDiscoveryProperties: 显示了当前服务实例关于 Nacos 的基础配置
[source,java,indent=0]
----
@SpringBootApplication
@EnableDiscoveryClient
public class NacosConsumerApp {
一个服务实例访问 EndPoint 的信息如下所示:
@RestController
public class NacosController{
[source, json]
@Autowired
private LoadBalancerClient loadBalancerClient;
@Autowired
private RestTemplate restTemplate;
@Value("${spring.application.name}")
private String appName;
@GetMapping("/echo/app-name")
public String echoAppName(){
//使用 LoadBalanceClient 和 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);
}
}
//实例化 RestTemplate 实例
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApp.class,args);
}
}
----
这个例子中我们注入了一个 LoadBalancerClient 的实例,并且手动的实例化一个 RestTemplate同时将 `spring.application.name` 的配置值 注入到应用中来,
目的是调用 Provider 提供的服务时,希望将当前配置的应用名给显示出来。
NOTE: 在启动 Consumer 应用之前请先将 Nacos 服务启动好。具体启动方式可参考 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]。
启动后,访问 Consumer 提供出来的 `http://ip:port/echo/app-name` 接口。我这里测试启动的 port是 8082。访问结果如下所示
访问地址http://127.0.0.1:8082/echo/app-name
访问结果Hello Nacos Discovery nacos-consumer
=== Nacos Discovery 对外暴露的 Endpoint
Nacos Discovery 内部提供了一个 Endpoint, 对应的 endpoint id 为 `nacos-discovery`。
Endpoint 暴露的 json 中包含了两种属性:
1. subscribe: 显示了当前服务有哪些服务订阅者
2. NacosDiscoveryProperties: 当前应用 Nacos 的基础配置信息
这是 Endpoint 暴露的 json 示例:
[source,json,indent=0]
----
{
"subscribe": [
@ -211,86 +287,27 @@ EndPoint 的信息主要提供了两类:
}
----
=== 启动一个 Consumer 应用
=== 关于 Nacos Discovery Starter 更多的配置项信息
Consumer 的应用可能还没像启动一个 Provider 应用那么简单。因为在 Consumer 端需要去调用 Provider 端提供的REST 服务。例子中我们使用最原始的一种方式,
即显示的使用 LoadBalanceClient 和 RestTemolate 结合的方式来访问。
pom.xml 和 application.properties 的配置可以参考 1.2 小结。启动一个 Consumer应用的示例代码如下所示
NOTE: 通过带有负载均衡的RestTemplate 和 FeignClient 也是可以访问的。
[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(){
//使用 LoadBalanceClient 和 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);
}
}
//实例化 RestTemplate 实例
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(NacosConsumerApp.class,args);
}
}
----
这个例子中我们注入了一个 LoadBalancerClient 的实例,并且手动的实例化一个 RestTemplate同时将 `spring.application.name` 的配置值 注入到应用中来,
目的是调用 Provider 提供的服务时,希望将当前配置的应用名给显示出来。
NOTE: 在启动 Consumer 应用之前请先将 Nacos 服务启动好。具体启动方式可参考 https://nacos.io/zh-cn/docs/quick-start.html[Nacos 官网]。
启动后,访问 Consumer 提供出来的 `http://ip:port/echo/app-name` 接口。我这里测试启动的 port是 8082。访问结果如下所示
访问地址http://127.0.0.1:8082/echo/app-name
访问结果Hello Nacos Discovery nacos-consumer
=== 关于 Nacos Starter 更多的配置项信息
更多关于 spring-cloud-starter-alibaba-nacos-discovery 的 starter 配置项如下所示:
更多关于 Nacos Discovery Starter 的配置项如下所示:
:frame: topbot
[width="60%",options="header"]
|====
^|配置项 ^|Key ^|默认值 ^|说明
|`服务端地址`|`spring.cloud.nacos.discovery.server-addr`|`无`| `Nacos Server 启动监听的ip地址和端口`
|`服务名`|`spring.cloud.nacos.discovery.service`|`${spring.application.name}`|`给当前的服务命名`
|`权重`|`spring.cloud.nacos.discovery.weight`|`1`|`取值范围 1 到 100数值越大权重越大`
|`网卡名`|`spring.cloud.nacos.discovery.network-interface`|`无`|`当IP未配置时注册的IP为此网卡所对应的IP地址如果此项也未配置则默认取第一块网卡的地址`
|`注册的IP地址`|`spring.cloud.nacos.discovery.ip`|`无`|`优先级最高`
|`注册的端口`|`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.enpoint`|`UTF-8`|`地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址`
|`是否集成Ribbon`|`ribbon.nacos.enabled`|`true`|`一般都设置成true即可`
|服务端地址|`spring.cloud.nacos.discovery.server-addr`|| Nacos Server 启动监听的ip地址和端口
|服务名|`spring.cloud.nacos.discovery.service`|`${spring.application.name}`|注册的服务名
|权重|`spring.cloud.nacos.discovery.weight`|`1`|取值范围 1 到 100数值越大权重越大
|网卡名|`spring.cloud.nacos.discovery.network-interface`||当IP未配置时注册的IP为此网卡所对应的IP地址如果此项也未配置则默认取第一块网卡的地址
|注册的IP地址|`spring.cloud.nacos.discovery.ip`||优先级最高
|注册的端口|`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`||地域的某个服务的入口域名,通过此域名可以动态地拿到服务端地址
|是否集成Ribbon|`ribbon.nacos.enabled`|`true`|一般都设置成true即可
|是否开启Nacos Watch|`spring.cloud.nacos.discovery.watch.enabled`|`true`|可以设置成false来关闭 watch
|====

View File

@ -1,10 +1,10 @@
== Spring Cloud Alibaba Cloud OSS
== Spring Cloud AliCloud OSS
OSSObject Storage Service是阿里云的一款对象存储服务产品 Spring Cloud AliCloud OSS 提供了Spring Cloud规范下商业版的对象存储服务提供简单易用的API并且支持与 Spring 框架中 Resource 的整合。
=== 如何引入 Spring Cloud AliCloud OSS
如果要在您的项目中引入 OSS使用 group ID 为 `com.alibaba.cloud` 和 artifact ID 为 `spring-cloud-starter-alicloud-oss` 的 starter。
如果要在您的项目中引入 OSS使用 group ID 为 `org.springframework.cloud` 和 artifact ID 为 `spring-cloud-starter-alicloud-oss` 的 starter。
[source,xml]
----

View File

@ -137,6 +137,11 @@ messageChannel.send(MessageBuilder.withPayload("simple msg").build());
### Spring Cloud Alibaba RocketMQ Binder 实现
这是 Spring Cloud Stream RocketMQ Binder 的实现架构:
.SCS RocketMQ Binder
image::https://img.alicdn.com/tfs/TB1v8rcbUY1gK0jSZFCXXcwqXXa-1236-773.png[]
RocketMQ Binder 的实现依赖于 https://github.com/apache/rocketmq-spring[RocketMQ-Spring] 框架。
RocketMQ-Spring 框架是 RocketMQ 与 Spring Boot 的整合RocketMQ Spring 主要提供了 3 个特性:
@ -166,12 +171,66 @@ Message message = builder.build();
output().send(message);
```
### MessageSource 支持
SCS RocketMQ Binder 支持 `MessageSource`,可以进行消息的拉取,例子如下:
```java
@SpringBootApplication
@EnableBinding(MQApplication.PolledProcessor.class)
public class MQApplication {
private final Logger logger =
LoggerFactory.getLogger(MQApplication.class);
public static void main(String[] args) {
SpringApplication.run(MQApplication.class, args);
}
@Bean
public ApplicationRunner runner(PollableMessageSource source,
MessageChannel dest) {
return args -> {
while (true) {
boolean result = source.poll(m -> {
String payload = (String) m.getPayload();
logger.info("Received: " + payload);
dest.send(MessageBuilder.withPayload(payload.toUpperCase())
.copyHeaders(m.getHeaders())
.build());
}, new ParameterizedTypeReference<String>() { });
if (result) {
logger.info("Processed a message");
}
else {
logger.info("Nothing to do");
}
Thread.sleep(5_000);
}
};
}
public static interface PolledProcessor {
@Input
PollableMessageSource source();
@Output
MessageChannel dest();
}
}
```
### 配置选项
#### RocketMQ Binder Properties
spring.cloud.stream.rocketmq.binder.name-server::
RocketMQ NameServer 地址。
RocketMQ NameServer 地址(老版本使用 namesrv-addr 配置项)
+
Default: `127.0.0.1:9876`.
spring.cloud.stream.rocketmq.binder.access-key::
@ -276,3 +335,20 @@ retryNextServer::
消息发送失败的情况下是否重试其它的 broker。
+
默认值: `false`.
### 阿里云 MQ 服务
使用阿里云 MQ 服务需要配置 AccessKey、SecretKey 以及云上的 NameServer 地址。
NOTE: 0.1.2 & 0.2.2 & 0.9.0 才支持该功能
```properties
spring.cloud.stream.rocketmq.binder.access-key=YourAccessKey
spring.cloud.stream.rocketmq.binder.secret-key=YourSecretKey
spring.cloud.stream.rocketmq.binder.name-server=NameServerInMQ
```
NOTE: topic 和 group 请以 实例id% 为前缀进行配置。比如 topic 为 "test",需要配置成 "实例id%test"
.NameServer 的获取(配置中请去掉 http:// 前缀)
image::https://spring-cloud-alibaba.oss-cn-beijing.aliyuncs.com/MQ.png[]

View File

@ -1,4 +1,4 @@
== Spring Cloud Alibaba Cloud SchedulerX
== Spring Cloud AliCloud SchedulerX
SchedulerX分布式任务调度 是隶属于阿里云EDAS产品的组件 Spring Cloud AliCloud SchedulerX 提供了在Spring Cloud的配置规范下分布式任务调度的功能支持。SchedulerX可提供秒级、精准、高可靠、高可用的定时任务调度服务并支持多种类型的任务调度如简单单机任务、简单多机任务、脚本任务以及网格任务。
@ -75,7 +75,7 @@ public class SimpleTask implements ScxSimpleJobProcessor {
[source,text]
----
Job分组测试——***-*-*-****
Job处理接口SimpleTask
Job处理接口org.springframework.cloud.alibaba.cloud.examples.SimpleTask
类型简单Job单机版
定时表达式默认选项——0 * * * * ?
Job描述
@ -111,4 +111,4 @@ NOTE: group-id必须创建在namespace当中。
access-key以及secret-key为阿里云账号的AK/SK信息如果应用在EDAS上部署则不需要填写这两项信息否则请前往 https://usercenter.console.aliyun.com/#/manage/ak[安全信息管理]获取。
domain-name并不是必须的具体请参考 https://help.aliyun.com/document_detail/35359.html[SchedulerX官方文档]。
domain-name并不是必须的具体请参考 https://help.aliyun.com/document_detail/35359.html[SchedulerX官方文档]。

View File

@ -6,7 +6,6 @@
https://github.com/alibaba/Sentinel[Sentinel] 具有以下特征:
* *丰富的应用场景* Sentinel 承接了阿里巴巴近 10 年的双十一大促流量的核心场景,例如秒杀(即突发流量控制在系统容量可以承受的范围)、消息削峰填谷、实时熔断下游不可用应用等。
* *完备的实时监控* Sentinel 同时提供实时的监控功能。您可以在控制台中看到接入应用的单台机器秒级数据,甚至 500 台以下规模的集群的汇总运行情况。
* *广泛的开源生态* Sentinel 提供开箱即用的与其它开源框架/库的整合模块,例如与 Spring Cloud、Dubbo、gRPC 的整合。您只需要引入相应的依赖并进行简单的配置即可快速地接入 Sentinel。
@ -51,6 +50,31 @@ public class TestController {
@SentinelResource 还提供了其它额外的属性如 `blockHandler``blockHandlerClass``fallback` 用于表示限流或降级的操作,更多内容可以参考 https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81[Sentinel注解支持]。
以上例子都是在 WebServlet 环境下使用的Sentinel 目前已经支持 WebFlux需要配合 `spring-boot-starter-webflux` 依赖触发 sentinel-starter 中 WebFlux 相关的自动化配置。
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
@RestController
public class TestController {
@GetMapping("/mono")
@SentinelResource("hello")
public Mono<String> mono() {
return Mono.just("simple string")
.transform(new SentinelReactorTransformer<>("otherResourceName"));
}
}
```
##### Sentinel 控制台
Sentinel 控制台提供一个轻量级的控制台,它提供机器发现、单机资源实时监控、集群资源汇总,以及规则管理的功能。您只需要对应用进行简单的配置,就可以使用这些功能。
@ -98,12 +122,12 @@ spring:
更多 Sentinel 控制台的使用及问题参考: https://github.com/alibaba/Sentinel/wiki/%E6%8E%A7%E5%88%B6%E5%8F%B0[Sentinel控制台]
### Feign 支持
### OpenFeign 支持
Sentinel 适配了 https://github.com/OpenFeign/feign[Feign] 组件。如果想使用,除了引入 `sentinel-starter` 的依赖外还需要 2 个步骤:
Sentinel 适配了 https://github.com/OpenFeign/feign[OpenFeign] 组件。如果想使用,除了引入 `sentinel-starter` 的依赖外还需要 2 个步骤:
* 配置文件打开 sentinel 对 feign 的支持:`feign.sentinel.enabled=true`
* 加入 `feign starter` 依赖触发 `sentinel starter` 的配置类生效:
* 加入 `openfeign starter` 依赖使 `sentinel starter` 中的自动化配置类生效:
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
@ -175,11 +199,11 @@ NOTE: 应用启动的时候会检查 `@SentinelRestTemplate` 注解对应的限
Sentinel RestTemplate 限流的资源规则提供两种粒度:
* `schema://host:port/path`:协议、主机、端口和路径
* `httpmethod:schema://host:port/path`:协议、主机、端口和路径
* `schema://host:port`:协议、主机和端口
* `httpmethod:schema://host:port`:协议、主机和端口
NOTE: 以 `https://www.taobao.com/test` 这个 url 为例。对应的资源名有两种粒度,分别是 `https://www.taobao.com` 以及 `https://www.taobao.com/test`
NOTE: 以 `https://www.taobao.com/test` 这个 url 并使用 GET 方法为例。对应的资源名有两种粒度,分别是 `GET:https://www.taobao.com` 以及 `GET:https://www.taobao.com/test`
### 动态数据源支持
@ -193,12 +217,12 @@ 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.converter-class=org.springframework.cloud.alibaba.cloud.examples.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
@ -209,7 +233,7 @@ 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.ds5.apollo.rule-type=param-flow
spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow
```
@ -219,16 +243,9 @@ NOTE: d1, ds2, ds3, ds4 是 `ReadableDataSource` 的名字,可随意编写。
每种数据源都有两个共同的配置项: `data-type`、 `converter-class` 以及 `rule-type`。
`data-type` 配置项表示 `Converter` 类型Spring Cloud Alibaba Sentinel 默认提供两种内置的值,分别是 `json` 和 `xml` (不填默认是json)。 如果不想使用内置的 `json` 或 `xml` 这两种 `Converter`,可以填写 `custom` 表示自定义 `Converter`,然后再配置 `converter-class` 配置项,该配置项需要写类的全路径名(比如 `spring.cloud.sentinel.datasource.ds1.file.converter-class=JsonFlowRuleListConverter`)。
`data-type` 配置项表示 `Converter` 类型Spring Cloud Alibaba Sentinel 默认提供两种内置的值,分别是 `json` 和 `xml` (不填默认是json)。 如果不想使用内置的 `json` 或 `xml` 这两种 `Converter`,可以填写 `custom` 表示自定义 `Converter`,然后再配置 `converter-class` 配置项,该配置项需要写类的全路径名(比如 `spring.cloud.sentinel.datasource.ds1.file.converter-class=org.springframework.cloud.alibaba.cloud.examples.JsonFlowRuleListConverter`)。
`rule-type` 配置表示该数据源中的规则属于哪种类型的规则(`flow``degrade``authority``system`, `param-flow`)。
如果数据源生效并且规则成功加载,控制台会打印类似如下信息:
```
[Sentinel Starter] DataSource ds1-sentinel-file-datasource load 3 DegradeRule
[Sentinel Starter] DataSource ds2-sentinel-nacos-datasource load 2 FlowRule
```
`rule-type` 配置表示该数据源中的规则属于哪种类型的规则(`flow``degrade``authority``system`, `param-flow`, `gw-flow`, `gw-api-group`)。
NOTE: 当某个数据源规则信息加载失败的情况下,不会影响应用的启动,会在日志中打印出错误信息。
@ -236,18 +253,159 @@ NOTE: 默认情况下xml 格式是不支持的。需要添加 `jackson-datafo
关于 Sentinel 动态数据源的实现原理,参考: https://github.com/alibaba/Sentinel/wiki/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%99%E6%89%A9%E5%B1%95[动态规则扩展]
### Endpoint 支持
### Zuul 支持
在使用 Endpoint 特性之前需要在 Maven 中添加 `spring-boot-starter-actuator` 依赖,并在配置中允许 Endpoints 的访问。
https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流]
* Spring Boot 1.x 中添加配置 `management.security.enabled=false`。暴露的 endpoint 路径为 `/sentinel`
* Spring Boot 2.x 中添加配置 `management.endpoints.web.exposure.include=*`。暴露的 endpoint 路径为 `/actuator/sentinel`
若想跟 Sentinel Starter 配合使用,需要加上 `spring-cloud-alibaba-sentinel-gateway` 依赖,同时需要添加 `spring-cloud-starter-netflix-zuul` 依赖来让 `spring-cloud-alibaba-sentinel-gateway` 模块里的 Zuul 自动化配置类生效:
Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有规则信息、日志目录、当前实例的 IPSentinel Dashboard 地址Block Page应用与 Sentinel Dashboard 的心跳频率等等信息。
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
### More
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-sentinel-gateway</artifactId>
</dependency>
下表显示当应用的 `ApplicationContext` 中存在对应的Bean的类型时会进行的一些操作
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
```
### Spring Cloud Gateway 支持
https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流]
若想跟 Sentinel Starter 配合使用,需要加上 `spring-cloud-alibaba-sentinel-gateway` 依赖,同时需要添加 `spring-cloud-starter-gateway` 依赖来让 `spring-cloud-alibaba-sentinel-gateway` 模块里的 Spring Cloud Gateway 自动化配置类生效:
```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-gateway</artifactId>
</dependency>
```
### Sentinel 对外暴露的 Endpoint
Sentinel 内部提供了一个 Endpoint, 对应的 endpoint id 为 `sentinel`。
Endpoint 暴露的 json 中包含了多种属性:
1. appName: 应用名
2. logDir: 日志所在目录
3. logUsePid: 日志文件名是否带上进程id
4. blockPage: 限流 block 之后跳转的页面
5. metricsFileSize: metrics 文件的大小
6. metricsFileCharset: metrics 文件对应的字符集
7. totalMetricsFileCount: metrics 最多保留的文件数
8. consoleServer: sentinel dashboard 地址
9. clientIp: 客户端 ip
10. heartbeatIntervalMs: 客户端跟 dashboard 的心跳间隔时间
11. clientPort: 客户端需要暴露的端口跟 dashboard 进行交互
12. coldFactor: 冷启动因子
13. filter: CommonFilter 相关的属性, 比如 order, urlPatterns 以及 enable
14. datasource: 客户端配置的数据源信息
15. rules: 客户端生效的规则,内部含有 flowRules, degradeRules, systemRules, authorityRule, paramFlowRule
这是 Endpoint 暴露的 json 示例:
[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
}
----
### 关于 Sentinel Starter 更多的配置项信息
下表显示当应用的 `ApplicationContext` 中存在对应的Bean的类型时会进行自动化设置
:frame: topbot
[width="60%",options="header"]
@ -258,18 +416,20 @@ Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有
|`RequestOriginParser`|`WebCallbackManager.setRequestOriginParser(requestOriginParser)`|设置来源信息
|====
下表显示 Spring Cloud Alibaba Sentinel 的所有配置信息:
Spring Cloud Alibaba Sentinel 提供了这些配置选项
:frame: topbot
[width="60%",options="header"]
|====
^|配置项 ^|含义 ^|默认值
|`spring.application.name` or `project.name`|Sentinel项目名|
|`spring.cloud.sentinel.enabled`|Sentinel自动化配置是否生效|true
|`spring.cloud.sentinel.eager`|取消Sentinel控制台懒加载|false
|`spring.cloud.sentinel.eager`|是否提前触发 Sentinel 初始化|false
|`spring.cloud.sentinel.transport.port`|应用与Sentinel控制台交互的端口应用本地会起一个该端口占用的HttpServer|8719
|`spring.cloud.sentinel.transport.dashboard`|Sentinel 控制台地址|
|`spring.cloud.sentinel.transport.heartbeat-interval-ms`|应用与Sentinel控制台的心跳间隔时间|
|`spring.cloud.sentinel.transport.client-ip`|客户端IP|
|`spring.cloud.sentinel.transport.client-ip`|此配置的客户端IP将被注册到 Sentinel Server 端|
|`spring.cloud.sentinel.filter.order`|Servlet Filter的加载顺序。Starter内部会构造这个filter|Integer.MIN_VALUE
|`spring.cloud.sentinel.filter.url-patterns`|数据类型是数组。表示Servlet Filter的url pattern集合|/*
|`spring.cloud.sentinel.filter.enabled`|Enable to instance CommonFilter|true
@ -279,7 +439,16 @@ Sentinel Endpoint 里暴露的信息非常有用。包括当前应用的所有
|`spring.cloud.sentinel.log.dir`|Sentinel 日志文件所在的目录|
|`spring.cloud.sentinel.log.switch-pid`|Sentinel 日志文件名是否需要带上pid|false
|`spring.cloud.sentinel.servlet.block-page`| 自定义的跳转 URL当请求被限流时会自动跳转至设定好的 URL |
|`spring.cloud.sentinel.flow.cold-factor`| 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.cold-factor`| 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.zuul.order.pre`| SentinelZuulPreFilter 的 order | 10000
|`spring.cloud.sentinel.zuul.order.post`| SentinelZuulPostFilter 的 order | 1000
|`spring.cloud.sentinel.zuul.order.error`| SentinelZuulErrorFilter 的 order | -1
|`spring.cloud.sentinel.scg.fallback.mode`| Spring Cloud Gateway 熔断后的响应模式(选择 `redirect` or `response`) |
|`spring.cloud.sentinel.scg.fallback.redirect`| Spring Cloud Gateway 响应模式为 'redirect' 模式对应的重定向 URL |
|`spring.cloud.sentinel.scg.fallback.response-body`| Spring Cloud Gateway 响应模式为 'response' 模式对应的响应内容 |
|`spring.cloud.sentinel.scg.fallback.response-status`| Spring Cloud Gateway 响应模式为 'response' 模式对应的响应码 | 429
|`spring.cloud.sentinel.scg.fallback.content-type`| Spring Cloud Gateway 响应模式为 'response' 模式对应的 content-type | application/json
|====
NOTE: 请注意。这些配置只有在 Servlet 环境下才会生效RestTemplate 和 Feign 针对这些配置都无法生效

View File

@ -1,4 +1,4 @@
== Spring Cloud Alibaba Cloud SMS
== Spring Cloud AliCloud SMS
短信服务Short Message Service是阿里云为用户提供的一种通信服务的能力。 Spring Cloud AliCloud SMS 实现了与 SMS 的简单集成,提供更为简单易用的 API可以基于 Spring Cloud Alibaba SMS 来快速的接入阿里云的 SMS 服务。
@ -31,7 +31,7 @@ access-key 和 secret-key 是阿里云账号的 AK/SK需要首先注册阿里
==== 引入 SMS API
Spring Cloud Alicloud SMS 中的 SMS API 基于阿里云官方 SMS SDK 提供具备单个短信发送、多个短信批量发送、短信查询、短信消息(短信回执消息 和 上行短信消息) 类行操作API。
Spring Cloud Alicloud SMS 中的 SMS API 基于阿里云官方 SMS SDK ,提供具备单个短信发送、多个短信批量发送、短信查询、短信消息(`短信回执消息` 和 `上行短信消息`) 类型操作API。
一个简单的使用 SMS API 发送短信的应用如下。
@ -43,7 +43,13 @@ public class SmsApplication {
@Autowired
private ISmsService smsService;
/**
* 短信发送 Example
* @param code
* @return
*/
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
@ -69,6 +75,7 @@ public class SmsApplication {
}
public static void main(String[] args) throws URISyntaxException {
SpringApplication.run(SmsApplication.class, args);
}
@ -88,10 +95,15 @@ Spring Cloud Alicloud SMS 封装的 API 接口为了降低学习的成本,尽
* 批量短信发送
参考以下的 Example ,来快速开发一个具有批量短信发送的功能。在 Controller 中或者新建一个 Controller 新增如下代码:
参考以下的 Example ,来快速开发一个具有批量短信发送的功能。在 Controller 中或者新建一个 Controler 新增如下代码:
[source,java]
----
/**
* 批量短信发送 Example
* @param code
* @return
*/
@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
@RequestParam(name = "code") String code) {
@ -129,10 +141,16 @@ NOTE: 这里设置请求的 MethodType 为 GET和官网给出的例子还有
* 短信查询
参考以下的 Example ,可以快速开发根据某个指定的号码查询短信历史发送状态。在 Controller 中或者新建一个 Controller 新增如下代码:
参考以下的 Example ,可以快速开发根据某个指定的号码查询短信历史发送状态。在 Controller 中或者新建一个 Controler 新增如下代码:
[source,java]
----
/**
*
* 短信查询 Example
* @param telephone
* @return
*/
@RequestMapping("/query.do")
public QuerySendDetailsResponse querySendDetailsResponse(
@RequestParam(name = "tel") String telephone) {
@ -181,7 +199,7 @@ spring.cloud.alicloud.sms.report-queue-name=Alicom-Queue-********-SmsReport
*/
@Component
public class SmsReportMessageListener
implements SmsReportMessageListener {
implements org.springframework.cloud.alicloud.sms.SmsReportMessageListener {
@Override
public boolean dealMessage(Message message) {
@ -199,7 +217,7 @@ public class SmsReportMessageListener
* 上行短信消息
通过订阅 SmsUp 上行短信消息,可以获知终端用户回复短信的内容。这些工作也已经被 Spring Cloud AliCloud SMS 封装好了。你只需要完成以下两步即可。
通过订阅SmsUp上行短信消息可以获知终端用户回复短信的内容。这些工作也已经被 Spring Cloud AliCloud SMS 封装好了。你只需要完成以下两步即可。
1、 在 `application.properties` 配置文件中(也可以是 application.yaml)配置 SmsReport 的队列名称。
@ -217,7 +235,7 @@ spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp
*/
@Component
public class SmsUpMessageListener
implements SmsUpMessageListener {
implements org.springframework.cloud.alicloud.sms.SmsUpMessageListener {
@Override
public boolean dealMessage(Message message) {
@ -231,4 +249,4 @@ public class SmsUpMessageListener
}
----
更多关于 Message 的消息体格式可 https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[参考这里]。
更多关于 Message 的消息体格式可 https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[参考这里]。

View File

@ -1,17 +1,13 @@
[[spring-cloud-alibaba-reference]]
= Spring Cloud Alibaba 参考文档
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:
== 介绍
Spring Cloud Alibaba 致力于提供微服务开发的一站式解决方案。此项目包含开发分布式应用服务的必需组件,方便开发者通过 Spring Cloud 编程模型轻松使用这些组件来开发分布式应用服务。
依托 Spring Cloud Alibaba您只需要添加一些注解和少量配置就可以将 Spring Cloud 应用接入阿里分布式应用解决方案,通过阿里中间件来迅速搭建分布式应用系统。
include::introduction.adoc[]
include::dependency-management.adoc[]
@ -21,6 +17,8 @@ include::nacos-config.adoc[]
include::sentinel.adoc[]
include::dubbo.adoc[]
include::rocketmq.adoc[]
include::ans.adoc[]
@ -33,4 +31,3 @@ include::schedulerx.adoc[]
include::sms.adoc[]

View File

@ -1,12 +1,14 @@
== 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
If you want to use ACM in your project, please use the starter with the group ID as `org.springframework.cloud` and the artifact ID as `spring-cloud-starter-alicloud-acm`.
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]
----
@ -162,12 +164,12 @@ 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.alicloud.acm.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}`

View File

@ -2,9 +2,11 @@
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
If you want to use ANS in your project, please use the starter with the group ID as `org.springframework.cloud` and the artifact ID as `spring-cloud-starter-alicloud-ans`.
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]
----
@ -91,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.

View File

@ -1,7 +1,5 @@
== Dependency Management
### Spring Cloud Alibaba Bill of Materials (BOM)
If youre 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.
```xml
@ -10,7 +8,7 @@ If youre a Maven Central user, add our BOM to your pom.xml <dependencyManagem
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<version>1.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
@ -18,21 +16,4 @@ If youre a Maven Central user, add our BOM to your pom.xml <dependencyManagem
</dependencyManagement>
```
### Spring Snapshots Maven Repository
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:
```xml
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring SnapShots</name>
<url>https://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
```
For example, the 0.2.0.BUILD-SNAPSHOT is available from this repository.
In the following sections, it will be assumed you are using the Spring Cloud Alibaba BOM and the dependency snippets will not contain versions.

View File

@ -0,0 +1,47 @@
== Spring Cloud Alibaba Dubbo
=== Introduction
Dubbo Spring Cloud is based on Dubbo Spring Boot 2.7.3[1] and Spring Cloud 2.x development, whether the developer is a Dubbo user or a Spring Cloud user.
Easily navigate and move apps up at a cost close to “zero” costs. Dubbo Spring Cloud is designed to simplify Cloud Native development costs, improve R&D performance, and improve application performance.
=== Features
Since Dubbo Spring Cloud is built on top of the native Spring Cloud, its service governance capabilities are considered Spring Cloud Plus.
Not only does it fully cover the Spring Cloud native features [5], but it also provides a more stable and mature implementation, as shown in the following table:
:frame: topbot
[width="60%",options="header"]
|====
^|Feature ^|Spring Cloud ^|Dubbo Spring Cloud
| Distributed configuration | Git、Zookeeper、Consul、JDBC | Spring Cloud Distributed Configuration + Dubbo Configuration Center[6]
| Service registration and discovery | Eureka、Zookeeper、Consul | Spring Cloud Native Registration Center[7] + Dubbo Native Registration Center[8]
| Load balancing | RibbonRandom, RoundRobin | Dubbo built-in implementation (random, polling, etc. + weights, etc.)
| Circuit Breakers | Spring Cloud Hystrix | Spring Cloud Hystrix + Alibaba Sentinel[9] etc.
| Service-to-service calls | Open Feign、`RestTemplate` | Spring Cloud service call + Dubbo `@Reference`.
| Tracing | Spring Cloud Sleuth[10] + Zipkin[11] | Zipkin、opentracing, etc.
|====
=== Reference
[1]: Starting with 2.7.0, Dubbo Spring Boot and Dubbo are consistent in version
[2]: Preview releases of Spring Cloud Alibaba are available: 0.9.0, 0.2.2, and 0.1.2 - https://spring.io/blog/2011/04/11/preview-releases-of-spring-cloud-alibaba-are-available-0-9-0-0-2-2-and-0-1-2
[3]: The current version of the Spring Cloud "F" is: `Finchley.SR2` - https://cloud.spring.io/spring-cloud-static/Finchley.SR2/single/spring-cloud.html
[4]: The current Spring Cloud "G" version is `Greenwich.RELEASE`
[5]: Spring Cloud feature list - https://cloud.spring.io/spring-cloud-static/Greenwich.RELEASE/single/spring-cloud.html#_features
[6]: Dubbo 2.7 starts supporting the configuration center and can be customized - http://dubbo.apache.org/en-us/docs/user/configuration/config-center.html
[7]: Spring Cloud native registry, in addition to Eureka, Zookeeper, and Consul, includes Nacos in Spring Cloud Alibaba
[8]: Dubbo Native Registration Center - http://dubbo.apache.org/en-us/docs/user/references/registry/introduction.html
[9]: Alibaba Sentinel: Sentinel uses traffic as an entry point to protect service stability from multiple dimensions such as flow control, blowdown, and system load protection - https://github.com/alibaba/Sentinel/wiki/%E4%BB%8B %E7%BB%8D, currently Sentinel has been accepted as a candidate for Circuit Breaker by the Spring Cloud project - https://spring.io/blog/2011/04/8/introducing-spring-cloud-circuit-breaker
[10]:Spring Cloud Sleuth - https://spring.io/projects/spring-cloud-sleuth
[11]: Zipkin - https://github.com/apache/incubator-zipkin

View File

@ -0,0 +1,19 @@
## 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. **Rpc Service**extend Spring Cloud client RestTemplate and OpenFeign to support calling Dubbo RPC services.
5. **Event-driven**support for building highly scalable event-driven microservices connected with shared messaging systems.
6. **Distributed Transaction**support for distributed transaction solution with high performance and ease of use.
7. **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.
8. **Alibaba Cloud SchedulerX**accurate, highly reliable, and highly available scheduled job scheduling services with response time within seconds.
9. **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].

View File

@ -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,7 +43,7 @@ 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
@ -43,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);
@ -59,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
----
@ -71,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]
@ -89,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"]
----
@ -100,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");
@ -153,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]
----
@ -162,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"]
----
@ -180,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");
@ -210,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"]
----
@ -318,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 Listbuild up by `Config` POJO. `Config` has 3 attributes, `dataId`, `group` and `refresh`
|====

View File

@ -1,15 +1,16 @@
== 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
please use the starter with the group ID as `com.alibaba.cloud` and the artifact ID as `spring-cloud-starter-alibaba-nacos-discovery`.
@ -21,11 +22,26 @@ please use the starter with the group ID as `com.alibaba.cloud` and the artifact
</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
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"? >
@ -98,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]
----
@ -111,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
@ -136,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
Addresshttp://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]
----
@ -211,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 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
Addresshttp://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
|====

View File

@ -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.
@ -136,6 +136,11 @@ Alternatively, you can also use the Spring Cloud Stream RocketMQ Starter:
### How Spring Cloud Alibaba RocketMQ Binder Works
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 implementation of RocketMQ Binder depend on the https://github.com/apache/rocketmq-spring[RocketMQ-Spring] framework.
RocketMQ Spring framework is an integration of RocketMQ and Spring Boot. It provides three main features:
@ -165,12 +170,64 @@ Message message = builder.build();
output().send(message);
```
### Support MessageSource
SCS RocketMQ Binder support `MessageSource`which can receive messages by pull mode
```java
@SpringBootApplication
@EnableBinding(MQApplication.PolledProcessor.class)
public class MQApplication {
private final Logger logger =
LoggerFactory.getLogger(MQApplication.class);
public static void main(String[] args) {
SpringApplication.run(MQApplication.class, args);
}
@Bean
public ApplicationRunner runner(PollableMessageSource source,
MessageChannel dest) {
return args -> {
while (true) {
boolean result = source.poll(m -> {
String payload = (String) m.getPayload();
logger.info("Received: " + payload);
dest.send(MessageBuilder.withPayload(payload.toUpperCase())
.copyHeaders(m.getHeaders())
.build());
}, new ParameterizedTypeReference<String>() { });
if (result) {
logger.info("Processed a message");
}
else {
logger.info("Nothing to do");
}
Thread.sleep(5_000);
}
};
}
public static interface PolledProcessor {
@Input
PollableMessageSource source();
@Output
MessageChannel dest();
}
}
```
### Configuration Options
#### RocketMQ Binder Properties
spring.cloud.stream.rocketmq.binder.name-server::
The name server of RocketMQ 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::

View File

@ -111,4 +111,4 @@ NOTE: Group-id must be created within a namespace.
Access-key and secret-key are the AK/SK of your Alibaba Cloud account. If you deploy you applications on EDAS, then you do not need to fill in this information. Otherwise please go to https://usercenter.console.aliyun.com/#/manage/ak[Security Information] to get your AccessKeys.
Domain-name is not mandatory. You can refer to https://help.aliyun.com/document_detail/35359.html[SchedulerX Documentation] for details.
Domain-name is not mandatory. You can refer to https://help.aliyun.com/document_detail/35359.html[SchedulerX Documentation] for details.

View File

@ -51,6 +51,31 @@ The @SentinelResource annotation is used to identify if a resource is rate limit
@SentinelResource also provides attributes such as `blockHandler`, `blockHandlerClass`, and `fallback` to identify rate limiting or degradation operations. For more details, refer to https://github.com/alibaba/Sentinel/wiki/%E6%B3%A8%E8%A7%A3%E6%94%AF%E6%8C%81[Sentinel Annotation Support].
The above examples are all used in the WebServlet environment. Sentinel currently supports WebFlux and needs to cooperate with the `spring-boot-starter-webflux` dependency to trigger the WebFlux-related automation configuration in sentinel starter.
```java
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(ServiceApplication.class, args);
}
}
@RestController
public class TestController {
@GetMapping("/mono")
@SentinelResource("hello")
public Mono<String> mono() {
return Mono.just("simple string")
.transform(new SentinelReactorTransformer<>("otherResourceName"));
}
}
```
##### Sentinel Dashboard
Sentinel dashboard is a lightweight console that provides functions such as machine discovery, single-server resource monitoring, overview of cluster resource data, as well as rule management. To use these features, you only need to complete a few steps.
@ -98,12 +123,12 @@ 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 2 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>
@ -177,11 +202,11 @@ It will return `RestTemplate request block by sentinel` when you using `RestTemp
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
@ -199,8 +224,8 @@ spring.cloud.sentinel.datasource.ds1.file.rule-type=flow
#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
@ -211,7 +236,7 @@ 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.ds5.apollo.rule-type=param-flow
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`.
@ -222,29 +247,162 @@ Every data source has 3 common configuration items: `data-type`, `converter-clas
`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.
`rule-type` refers to the rule type in datasource(`flow`, `degrade`, `authority`, `system`, `param-flow`).
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:
The information exposed in Sentinel Endpoint is very useful. It includes all the rules of the current application, the log directory, the IP of the current instance, the Sentinel Dashboard address, the Block Page, the heartbeat frequency of the application and the Sentinel Dashboard, and so on.
```xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
### More
<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>
```
### Support Spring Cloud Gateway
https://github.com/alibaba/Sentinel/wiki/%E7%BD%91%E5%85%B3%E9%99%90%E6%B5%81[参考 Sentinel 网关限流]
If you want to use Sentinel Starter with Spring Cloud Gateway, you need to add the `spring-cloud-alibaba-sentinel-gateway` dependency and add the `spring-cloud-starter-gateway` dependency to let Spring Cloud Gateway AutoConfiguration class in the module takes effect:
```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-gateway</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:
@ -263,12 +421,13 @@ 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.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`|Client IP|
|`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.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
@ -279,6 +438,15 @@ The following table shows all the configurations of Spring Cloud Alibaba Sentine
|`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[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
|`spring.cloud.sentinel.scg.fallback.mode`| Response mode after Spring Cloud Gateway circuit break (select `redirect` or `response`) |
|`spring.cloud.sentinel.scg.fallback.redirect`| Spring Cloud Gateway response mode is the redirect URL corresponding to 'redirect' mode |
|`spring.cloud.sentinel.scg.fallback.response-body`| Spring Cloud Gateway response mode is response content corresponding to 'response' mode |
|`spring.cloud.sentinel.scg.fallback.response-status`| Spring Cloud Gateway response mode is the response code corresponding to 'response' mode | 429
|`spring.cloud.sentinel.scg.fallback.content-type`| The Spring Cloud Gateway response mode is the content-type corresponding to the 'response' mode. | application/json
|====
NOTE: These configurations will only take effect in servlet environment. RestTemplate and Feign will not take effect for these configurations.

View File

@ -2,9 +2,9 @@
SMSShort Message Serviceis 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 AliCloud SMS provide an easier-to-use API for quick access to Alibaba Cloud's SMS service based on Spring Cloud Alibaba SMS.
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.
=== 如何引入 Spring Cloud AliCloud 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`.
@ -195,7 +195,7 @@ spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp
----
@Component
public class SmsUpMessageListener
implements SmsUpMessageListener {
implements org.springframework.cloud.alicloud.sms.SmsUpMessageListener {
@Override
public boolean dealMessage(Message message) {
@ -206,4 +206,4 @@ public class SmsUpMessageListener
}
----
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].
More message body format for Message can be https://help.aliyun.com/document_detail/55496.html?spm=a2c4g.11186623.6.570.7f792c78rOiWXO[reference here].

View File

@ -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[]
@ -21,6 +17,8 @@ include::nacos-config.adoc[]
include::sentinel.adoc[]
include::dubbo.adoc[]
include::rocketmq.adoc[]
include::ans.adoc[]
@ -30,3 +28,5 @@ include::acm.adoc[]
include::oss.adoc[]
include::schedulerx.adoc[]
include::sms.adoc[]