SpringCloudAlibaba

目录

1.介绍

2. Dependency Management

3. Spring Cloud Alibaba Nacos Discovery

3.4. Nacos Discovery Endpoint

3.5. Weight Route权重

3.6. 关于Nacos Discovery启动器配置的更多信息

4. Spring Cloud Alibaba Nacos Config

4.1. 如何引入Nacos配置进行配置

4.2. 快速启动 

4.3. 使用YAML格式的DataId添加配置

4.4. 支持动态更新配置

4.5. 支持profile文件级别的配置

4.6. 支持自定义Namespaces

4.7. 支持自定义组

4.8.支持自定义数据Id

4.9. Nacos配置端点(Nacos Config Endpoint)

4.10. 禁用Nacos Config AutoConfiguration

4.11. 关于Nacos Config启动器配置的更多信息

5. Spring Cloud Alibaba Sentinel

5.1. Sentinel的介绍

5.2. 如何使用Sentinel

Sentinel Dashboard

5.2.2. 配置Dashboard

5.3. OpenFeign支持

5.4. RestTemplate支持

5.5. 动态数据源支持

5.6. Spring Cloud Gateway支持

5.7. 断路器: Spring Cloud Circuit Breaker With Sentinel & Configuring Sentinel Circuit Breakers

5.7.1. 默认配置

5.7.2. ju断路器配置

5.8. Sentinel Endpoint

5.9. 配置

6. Spring Cloud Alibaba RocketMQ Binder

6.1. RocketMQ介绍

6.2. RocketMQ用法

6.3. Spring Cloud Stream介绍

6.4. How to use Spring Cloud Alibaba RocketMQ Binder

6.5. Spring Cloud Alibaba RocketMQ Binder如何工作

6.6.配置选项

6.6.1. RocketMQ Binder Properties

6.6.2. RocketMQ Consumer Properties

6.6.3. RocketMQ Provider Properties

7. Spring Cloud Alibaba Cloud ANS

7.1. 如何引入Spring Cloud Alibaba Cloud ANS

7.2. 使用ANS注册服务

7.3. 启动注册中心

7.3.1. 启动轻量级配置中心

7.3.2. 云端用户注册中心

8. Spring Cloud Alibaba Cloud ACM

8.1. 如何引入Spring Cloud Alibaba Cloud ACM

8.2. 使用ACM管理配置

8.2.1. 启动配置中心

8.2.2. 在配置中心中添加配置

8.2.3. 启动应用程序验证

8.3. 修改配置文件扩展名

8.4. 动态刷新配置

8.5. 配置配置文件粒度

8.6. 支持自定义ACM超时时间

8.7. 支持自定义组配置

8.7.1. 支持共享配置

8.8. Actuator Endpoint

9. Spring Cloud Alibaba Cloud OSS

9.1. 如何引入 Spring Cloud Alibaba Cloud OSS

9.2. 如何使用OSS API

9.2.1. 配置OSS

9.2.2. 介绍OSS API

9.3. 与Spring的资源规范集成

9.4. Use STS Authentication

9.5. 客户端的更多配置

10. Spring Cloud Alibaba Cloud SchedulerX

10.2. 开始SchedulerX

10.3. 编译一个简单的任务

10.4. Job Scheduling

10.5. 在生产环境中的使用

11. Spring Cloud Alibaba Cloud SMS

11.1. 如何引入 Spring Cloud Alibaba Cloud SMS

11.2. 如何使用短信API

11.2.1. 配置SMS

11.2.2. 介绍SMS API

11.3. 短信Api的高级功能


1.介绍

  阿里巴巴致力于为微服务开发提供一站式解决方案。该项目包括开发分布式应用程序和服务所需的组件,以便开发人员可以使用Spring Cloud编程模型轻松地开发分布式应用程序。

  使用Spring Cloud Alibaba,您只需要添加一些注释和配置,就可以将阿里巴巴的分布式解决方案用于您的应用程序,并使用阿里巴巴中间件构建自己的分布式系统。

Spring Cloud Alibaba的特点:

1.流量控制和服务降级:支持WebServlet、WebFlux、OpenFeign、RestTemplate、Dubbo访问的流量限制和降级功能。它可以在运行时通过控制台实时修改限制和降级流的规则,而且它还支持对限制和降级度量的监视。

2.服务注册和发现:服务可以注册,客户端可以使用spring管理的bean、自动集成Ribbon来发现实例。

3.分布式配置:支持分布式系统中的外部化配置,当配置更改时自动刷新。

4.Rpc Service:扩展SpringCloud客户端RestTemplate和OpenFeign以支持调用Dubbo Rpc服务。

5.事件驱动:支持构建与共享消息传递系统连接的高度可伸缩的事件驱动微服务。

6.分布式事务:支持高性能和易于使用的分布式事务解决方案。

7.阿里云对象存储:海量、安全、低成本、高可靠的云存储服务。支持在任何应用程序中、任何时间、任何地点存储和访问任何类型的数据。

8.Alibaba Cloud SchedulerX:精确、高可靠性、高可用性的调度作业服务,响应时间可达数秒。

9.阿里云短信:阿里云短信是一种覆盖全球的短信服务,提供方便、高效和智能的通信能力,帮助企业快速联系客户。


2. Dependency Management

  如果您是一个Maven Central用户,请将我们的BOM添加到您的pom.xml的 <dependencyManagement>部分。这将允许您忽略任何Maven依赖项的版本,而将版本管理委托给BOM。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>2021.0.4.0</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

在下面的小节中,假设您正在使用Spring Cloud Alibaba BOM,并且依赖片段不包含版本。


3. Spring Cloud Alibaba Nacos Discovery

  Nacos是一个易于使用的动态服务发现、配置和服务管理平台,用于构建云本地应用程序。

  通过Spring Cloud Alibaba Nacos Discovery,您可以基于Spring Cloud的编程模型快速访问Nacos服务注册特性。

3.1. 服务注册/发现:Nacos发现

  服务发现是微服务体系结构中的关键组件之一。在这样的体系结构中,为每个客户机手动配置服务列表可能是一项艰巨的任务,并且使动态扩展变得极为困难。Nacos Discovery帮助您自动向Nacos服务器注册服务,而Nacos服务器将跟踪服务并动态刷新服务列表。此外,Nacos Discovery将服务实例的一些元数据(如主机、端口、健康检查URL、主页)注册到Nacos。有关如何下载和启动Nacos的详细信息,请到 Nacos文档

3.2. 如何为服务注册/发现引入Nacos Discovery

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

3.3. 使用Nacos Discovery进行服务注册/发现和调用的示例

3.3.1. Nacos Server 启动

Nacos Server启动后,登录http://ip:8848查看控制台(默认帐号/密码为Nacos / Nacos):

picture

3.3.2. 启动提供者应用程序

下面的示例说明如何向Nacos注册服务。

以下是一个完整的pom.xml示例:

pom.xml

<?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"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>open.source.test</groupId>
    <artifactId>nacos-discovery-test</artifactId>
    <version>1.0-SNAPSHOT</version>
    <name>nacos-discovery-test</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>${spring.boot.version}</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring.cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring.cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties应用程序配置。Nacos的一些基本配置必须包含在应用程序中。属性(或application.yaml),如下所示:

application.properties

server.port=8081
spring.application.name=nacos-provider
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
management.endpoints.web.exposure.include=*

Note:如果不想使用Nacos进行服务注册和发现,可以将spring.cloud.nacos.discovery设置为false。

下面是启动Provider的示例:

@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosProviderDemoApplication.class, args);
    }

    @RestController
    public class EchoController {
        @GetMapping(value = "/echo/{string}")
        public String echo(@PathVariable String string) {
            return "Hello Nacos Discovery " + string;
        }
    }
}

  现在您可以在Nacos控制台中看到注册的服务。

Note:在启动提供程序应用程序之前,请先启动Nacos。

3.3.3. 启动消费者应用程序

  这可能不像启动提供者应用程序那么容易,因为使用者需要调用提供者的RESTful服务。在本例中,我们将使用最基本的方式,即显式地组合LoadBalanceClient和RestTemplate来访问RESTful服务。您可以参考1.2节了解pom.xml和应用程序。属性配置。下面是启动使用者应用程序的示例代码。

Note:您还可以通过使用带有负载均衡的RestTemplate和FeignClient来访问该服务。

@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和RestTemplate的组合访问
            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的配置值注入到应用程序中,以便在调用提供者的服务时显示当前的应用程序名称。

接下来,访问消费者提供的http://ip:port/echo/app-name接口。在这里我们开始了8082的端口。访问结果如下图所示:

Address:http://127.0.0.1:8082/echo/app-name
Access result: Hello Nacos Discovery nacos-consumer

3.4. Nacos Discovery Endpoint

Nacos Discovery在内部提供了一个端点,其对应的端点id为nacosdiscovery。

Endpoint exposed json包含两个属性:

1.subscribe:显示当前的服务订阅者

2.NacosDiscoveryProperties:显示当前服务的当前基本Nacos配置

下面展示了服务实例如何访问Endpoint:

{
  "subscribe": [
    {
      "jsonFromServer": "",
      "name": "nacos-provider",
      "clusters": "",
      "cacheMillis": 10000,
      "hosts": [
        {
          "instanceId": "30.5.124.156#8081#DEFAULT#nacos-provider",
          "ip": "30.5.124.156",
          "port": 8081,
          "weight": 1.0,
          "healthy": true,
          "enabled": true,
          "cluster": {
            "serviceName": null,
            "name": null,
            "healthChecker": {
              "type": "TCP"
            },
            "defaultPort": 80,
            "defaultCheckPort": 80,
            "useIPPort4Check": true,
            "metadata": {

            }
          },
          "service": null,
          "metadata": {

          }
        }
      ],
      "lastRefTime": 1541755293119,
      "checksum": "e5a699c9201f5328241c178e804657e11541755293119",
      "allIPs": false,
      "key": "nacos-provider",
      "valid": true
    }
  ],
  "NacosDiscoveryProperties": {
    "serverAddr": "127.0.0.1:8848",
    "endpoint": "",
    "namespace": "",
    "logName": "",
    "service": "nacos-provider",
    "weight": 1.0,
    "clusterName": "DEFAULT",
    "metadata": {

    },
    "registerEnabled": true,
    "ip": "30.5.124.201",
    "networkInterface": "",
    "port": 8082,
    "secure": false,
    "accessKey": "",
    "secretKey": ""
  }
}

3.5. Weight Route权重

3.5.1. Spring Cloud Loadbalancer

<dependencies>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-loadbalancer</artifactId>
    </dependency>
</dependencies>

application.properties

spring.cloud.loadbalancer.ribbon.enabled=false
spring.cloud.loadbalancer.nacos.enabled=true

3.6. 关于Nacos Discovery启动器配置的更多信息

下面是Nacos Discovery启动器的其他配置:

ConfigurationKeyDefault ValueDescription
Server addressspring.cloud.nacos.discovery.server-addrNacos Server监听器的IP和端口
Service namespring.cloud.nacos.discovery.service{spring.application.name}命名当前服务
Weightspring.cloud.nacos.discovery.weight1取值范围:1 ~ 100。值越大,权重越大
Network card namespring.cloud.nacos.discovery.network-interface如果不指定IP地址,则注册的IP地址为网卡的IP地址。如果也未指定此参数,则默认使用第一张网卡的IP地址。
Registered IP addressspring.cloud.nacos.discovery.ip最高优先权
Registered IP address Typespring.cloud.nacos.discovery.ip-typeIPv4可以配置IPv4和IPv6,如果同一类型的网卡有多个IP地址,并且您想指定一个特定的网段地址,可以使用spring.cloud.inetutils。首选网络配置过滤地址
Registered portspring.cloud.nacos.discovery.port-1默认情况下自动检测。不需要配置。
Namespacespring.cloud.nacos.discovery.namespace典型的场景是隔离不同环境的服务注册,例如测试和生产环境之间的资源(配置、服务等)隔离
AccessKeyspring.cloud.nacos.discovery.access-key阿里云账户accesskey
SecretKeyspring.cloud.nacos.discovery.secret-key阿里云账户秘钥
Metadataspring.cloud.nacos.discovery.metadata您可以用Map格式为服务定义一些元数据
Log file namespring.cloud.nacos.discovery.log-name
Cluster Namespring.cloud.nacos.discovery.cluster-nameDEFAULT        Nacos的集群名称
Endpointspring.cloud.nacos.discovery.endpoint指定区域内某项服务的域名。您可以使用该域名动态检索服务器地址
Integrate LoadBalancer or notspring.cloud.loadbalancer.nacos.enabledfalse
Enable Nacos WatchSpring Cloud Alibaba Reference Documentationtrue设置为false关闭监视

4. Spring Cloud Alibaba Nacos Config

Nacos是一个易于使用的动态服务发现、配置和服务管理平台,用于构建云本地应用程序。

使用Spring Cloud阿里Nacos配置,基于Spring Cloud的编程模型快速访问Nacos配置管理功能。

4.1. 如何引入Nacos配置进行配置

请使用组ID为com.alibaba.cloud和工件ID为spring-cloud-starter-alibaba-nacos-config的启动器。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

4.2. 快速启动 

Nacos Config使用DataId和GROUP来确定配置。

 下图显示DataId使用myDataid, GROUP使用DEFAULT_GROUP,并配置格式为Properties的配置项:

4.2.1. 初始化Nacos服务器

具体启动方法请参考Spring Cloud阿里Nacos发现的“Nacos服务器启动”章节。

Nacos Server启动后,添加如何配置它:

Data ID:    nacos-config.properties

Group  :    DEFAULT_GROUP

Configuration format:    Properties

Configuration content:   user.name=nacos-config-properties
            user.age=90

Note:DataId的默认文件扩展名是properties。

客户端使用

如果您想使用Nacos来管理应用程序的外部化配置,请使用组ID为com.alibaba.cloud的启动器,工件ID为spring-cloud-starter-alibaba-nacos-config。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>

现在我们可以创建一个标准的Spring Boot应用程序了。

@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] 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);
    }
}

Note:注意,当spring-cloud-alibaba的版本为' ' 2021.1时,因为nacos在 bootstrap.yml 会在application.ym之前加Spring的官方文件所提到的[bootstrap](Spring Cloud Config) 为了解决这个问题,我们建议您将以下依赖项添加到项目根pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
    <version>3.1.1</version>
</dependency>

在运行这个示例之前,我们需要在bootstrap.properties中配置Nacos服务器的地址。例如:

bootstrap.properties

# DataId默认情况下,' spring.application.name '配置与文件扩展名相结合(默认情况下,配置格式使用属性),GROUP默认情况下没有配置为使用DEFAULT_GROUP。因此,配置文件对应的Nacos Config配置有一个DataId为nacos-config.properties和DEFAULT_GROUP
spring.application.name=nacos-config
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

Note:如果使用域名访问Nacos,spring.cloud.nacos.config.server-addr的格式为域名:端口。例如,Nacos域名为 abc.com.nacos, listner端口是80,那么配置应该是  spring.cloud.nacos.config.server-addr=abc.com.nacos:80 

80端口不能省略。

运行此示例,您可以看到以下输出:

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

4.3. 使用YAML格式的DataId添加配置

Nacos Config也支持yaml格式。您只需要完成以下2个步骤。

1.在bootstrap.properties文件中,添加以下行来声明DataId的格式是yaml。如下:

bootstrap.properties

spring.cloud.nacos.config.file-extension=yaml

2、在Nacos控制台中添加yaml格式的DataId配置,如下所示:

Data ID:        nacos-config.yaml

Group  :        DEFAULT_GROUP

Configuration format:        YAML

Configuration content:        user.name: nacos-config-yaml
                              user.age: 68

完成前两个步骤后,重新启动测试程序,您将看到以下结果。

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

4.4. 支持动态更新配置

Nacos Config还支持动态配置更新。启动Spring Boot应用程序测试的代码如下:

@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.class, args);
        while(true) {
            //当配置动态刷新时,它们将在环境中更新,因此在这里我们每隔一秒从环境中检索配置。
            String userName = applicationContext.getEnvironment().getProperty("user.name");
            String userAge = applicationContext.getEnvironment().getProperty("user.age");
            System.err.println("user name :" + userName + "; age: " + userAge);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

当user.name被更改时,可以从应用程序中检索到最新的值,如下所示:

user name :nacos-config-yaml; age: 68
user name :nacos-config-yaml; age: 68
user name :nacos-config-yaml; age: 68
2018-11-02 15:04:25.069  INFO 32957 --- [-127.0.0.1:8848] o.s.boot.SpringApplication               : Started application in 0.144 seconds (JVM running for 71.752)
2018-11-02 15:04:25.070  INFO 32957 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@10c89124: startup date [Fri Nov 02 15:04:25 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@6520af7
2018-11-02 15:04:25.071  INFO 32957 --- [-127.0.0.1:8848] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@6520af7: startup date [Fri Nov 02 15:04:24 CST 2018]; root of context hierarchy
//从环境中读取更新的值
user name :nacos-config-yaml-update; age: 68
user name :nacos-config-yaml-update; age: 68

Note:你可以通过设置' spring.cloud.nacos.config.refresh.enabled=false '禁用自动刷新。

4.5. 支持profile文件级别的配置

当配置由Nacos Config加载时,基本配置使用${spring.application.name}.${file-extension:properties}的DataId。和${spring.application.name}-${profile}.${file-extension:properties}的DataId也会被加载。如果需要使用来自不同环境的不同配置,可以使用

${spring.profiles.active}配置由Spring提供。

spring.profiles.active=develop

Note:当在配置文件中指定时,${spring.profiles.active} 必须放在bootstrap.properties中。

在Nacos中添加基本配置,使用nacos-config-develop.yaml的DataId。Yaml,如下所示:

Data ID:        nacos-config-develop.yaml

Group  :        DEFAULT_GROUP

Configuration format:        YAML

Configuration content:        current.env: develop-env

运行以下Spring Boot应用程序测试代码:

@SpringBootApplication
public class NacosConfigApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(NacosConfigApplication.class, args);
        while(true) {
            String userName = applicationContext.getEnvironment().getProperty("user.name");
            String userAge = applicationContext.getEnvironment().getProperty("user.age");
            //获取当前部署环境
            String currentEnv = applicationContext.getEnvironment().getProperty("current.env");
            System.err.println("in "+currentEnv+" enviroment; "+"user name :" + userName + "; age: " + userAge);
            TimeUnit.SECONDS.sleep(1);
        }
    }
}

启动后,您可以在控制台中看到如下输出:

in develop-env enviroment; user name :nacos-config-yaml-update; age: 68
2018-11-02 15:34:25.013  INFO 33014 --- [ Thread-11] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6f1c29b7: startup date [Fri Nov 02 15:33:57 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@63355449

要切换到生产环境,您只需要更改${spring.profiles.active}的参数。如下图所示:        

spring.profiles.active=product

同时,在生产环境的Nacos中使用DataId添加基本配置。例如,你可以使用nacos-config-product.yaml的DataId添加配置在您的生产环境的Nacos:

Data ID:        nacos-config-product.yaml

Group  :        DEFAULT_GROUP

Configuration format:        YAML

Configuration content:        current.env: product-env

启动测试程序,您将看到以下结果:

in product-env enviroment; user name :nacos-config-yaml-update; age: 68
2018-11-02 15:42:14.628  INFO 33024 --- [Thread-11] ConfigServletWebServerApplicationContext : Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@6aa8e115: startup date [Fri Nov 02 15:42:03 CST 2018]; parent: org.springframework.context.annotation.AnnotationConfigApplicationContext@19bb07ed

Note:在本例中,我们使用spring.profiles.active=<profilename>在配置文件中对配置进行编码。在实际场景中,该变量需要在不同的环境中不同。可以使用-Dspring.profiles.active=<profile>参数指定配置,以便在不同的环境之间轻松切换。

4.6. 支持自定义Namespaces

有关Nacos中的名称空间的详细信息,请参见Nacos概念

Namespaces用于隔离不同租户的配置。组和数据id可以在不同的名称空间中相同。名称空间的典型场景是不同环境的配置隔离,例如,开发/测试环境和生产环境(配置和服务等)之间的隔离。

如果在${spring.cloud.nacos.config.namespace}中没有指定命名空间,则使用Nacos的" Public "命名空间。您还可以通过以下方式指定自定义名称空间:

spring.cloud.nacos.config.namespace=b3404bc0-d7dc-4855-b519-570ed34b62d7

Note:该配置必须在bootstrap.properties。spring.cloud.nacos.config.namespace的值是命名空间的id, id的值可以从Nacos控制台检索。添加配置时不能选择其他名称空间。否则无法正常检索配置。

4.7. 支持自定义组

当没有定义{spring.cloud.nacos.config.group}配置时,默认使用DEFAULT_GROUP。如果你需要定义自己的组,你可以在以下属性中定义它:

spring.cloud.nacos.config.group=DEVELOP_GROUP

Note:该配置必须在bootstrap.properties,Group的值必须与spring.cloud.nacos.config.group的值一致

4.8.支持自定义数据Id

在Spring Cloud Alibaba Nacos Config中,data id可以自定义。该部分的详细设计请参考Github issue。以下是一个完整的例子:

spring.application.name=opensource-service-provider
spring.cloud.nacos.config.server-addr=127.0.0.1:8848

# 配置外部配置
# 1. “Data Id”属于默认组“DEFAULT_GROUP”,不支持动态刷新配置。
spring.cloud.nacos.config.ext-config[0].data-id=ext-config-common01.properties

# 2. Data Id 不在默认组中,不支持动态刷新配置。
spring.cloud.nacos.config.ext-config[1].data-id=ext-config-common02.properties
spring.cloud.nacos.config.ext-config[1].group=GLOBALE_GROUP

# 3. Data Id 不在默认组中,支持动态引用配置。
spring.cloud.nacos.config.ext-config[2].data-id=ext-config-common03.properties
spring.cloud.nacos.config.ext-config[2].group=REFRESH_GROUP
spring.cloud.nacos.config.ext-config[2].refresh=true

我们可以看到:

通过配置支持多个数据id  spring.cloud.nacos.config.ext-config[n].data-id.

通过配置自定义数据id组 spring.cloud.nacos.config.ext-config[n].group。如果未指定,则使用DEFAULT_GROUP。

控制此data id在通过spring.cloud.nacos.config.ext-config[n].refresh配置更改配置时是否支持配置的动态刷新。默认情况下不支持。

Note:当同时配置多个Data id时,优先级由 spring.cloud.nacos.config.ext-config[n].data-id 中“n”的值定义。该值越大,优先级越高

Note:spring.cloud.nacos.config.ext-config[n].data-id的值必须有文件扩展名,它可以是 properties or yaml/yml。spring.cloud.nacos.config.file-extension中的设置对自定义数据Id文件扩展名没有任何影响。

我自定义Data Id的配置允许在多个应用程序之间共享配置,还支持一个应用程序的多个配置。

为了在多个应用程序之间更清晰地共享 data id,还可以使用以下方法:

spring.cloud.nacos.config.shared-dataids=bootstrap-common.properties,all-common.properties
spring.cloud.nacos.config.refreshable-dataids=bootstrap-common.properties

我们可以看到:

  • 可以使用 spring.cloud.nacos.config.shared-dataids 配置多个共享数据id,数据id之间用逗号分隔。

  • spring.cloud.nacos.config.refreshable-dataids用于控制在更新配置时动态刷新哪些data id,以及应用程序可以检索最新的配置值。数据id以逗号分隔。如果不指定,将不会动态刷新所有共享数据id。

Note:当使用 spring.cloud.nacos.config.shared-dataids 配置多个共享数据id时,我们同意共享配置之间的以下优先级:优先级是根据配置出现的顺序决定的。较晚出现的那个比最先出现的那个优先级高。

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指定支持动态刷新的数据id时,数据id的对应值也应该指定文件扩展名。

4.9. Nacos配置端点(Nacos Config Endpoint)

Nacos Config在内部提供了一个端点,其对应的端点id为nacos-config。

ndpoint exposed json包含三个属性:

1.Sources:当前应用程序配置数据信息
2.RefreshHistory:配置刷新历史
3.NacosConfigProperties:显示当前服务的当前基本Nacos配置

下面展示了服务实例如何访问Endpoint:

{
	"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"
	}]
}

4.10. 禁用Nacos Config AutoConfiguration

设置 spring.cloud.nacos.config.enabled = false 禁用Spring Cloud Nacos Config AutoConfiguration。

4.11. 关于Nacos Config启动器配置的更多信息

下面是Nacos Config启动器的其他配置:

ConfigurationKeyDefault ValueDescription

Server address

spring.cloud.nacos.config.server-addr

IP and port of the Nacos Server listener

Dataid from nacos config

spring.cloud.nacos.config.name

First take the prefix, then go to the name, and finally take spring.application.name

Dataid from nacos config

spring.cloud.nacos.config.prefix

First take the prefix, then go to the name, and finally take spring.application.name

Encode for nacos config content

spring.cloud.nacos.config.encode

Encode for nacos config content

GROUP for nacos config

spring.cloud.nacos.config.group

DEFAULT_GROUP

GROUP for nacos config

The suffix of nacos config dataId, also the file extension of config content.

spring.cloud.nacos.config.fileExtension

properties

The suffix of nacos config dataId, also the file extension of config content(now support properties or yaml(yml))

Timeout for get config from nacos

spring.cloud.nacos.config.timeout

3000

Timeout for get config from nacos

Endpoint

spring.cloud.nacos.config.endpoint

Endpoint

Namespace

spring.cloud.nacos.config.namespace

Namespace

AccessKey

spring.cloud.nacos.config.accessKey

Alibaba Cloud account accesskey

SecretKey

spring.cloud.nacos.config.secretKey

Alibaba Cloud account secretkey

The context path of Nacos Server

spring.cloud.nacos.config.contextPath

The context path of Nacos Server

Cluster name

spring.cloud.nacos.config.clusterName

Cluster name

Dataid for Shared Configuration

spring.cloud.nacos.config.sharedDataids

Dataid for Shared Configuration, split by ","

Dynamic refresh dataid for Shared Configuration

spring.cloud.nacos.config.refreshableDataids

Dynamic refresh dataid for Shared Configuration, split by ","

custom dataid

spring.cloud.nacos.config.extConfig

It’s a List,build up by Config POJO. Config has 3 attributes, dataIdgroup and refresh

5. Spring Cloud Alibaba Sentinel

5.1. Sentinel的介绍

随着微服务的普及,服务调用的稳定性变得越来越重要。Sentinel以“流量”为切入点,在流量控制、断路、负载保护等多个领域开展工作,保障业务可靠性。

Sentinel  具有下列性质:

丰富的场景:Sentinel支持阿里巴巴双十一购物节10多年的关键场景,如秒杀(即;(控制突然爆发的流量,使其处于系统容量的可接受范围内)、消息负载转移、不可靠的下游应用断路。

全面实时监控:Sentinel提供实时监控功能。您可以以秒为精度查看服务器的监视数据,甚至可以查看节点少于500个的集群的总体运行时状态。

广泛的开源生态系统:Sentinel提供开箱即用的模块,可以轻松地与其他开源框架/库集成,如Spring Cloud、Dubbo和gRPC。要使用Sentinel,您只需要引入相关的依赖项并进行一些简单的配置。

健全的SPI扩展:Sentinel提供易于使用和健全的SPI扩展接口。您可以使用SPI扩展快速地自定义逻辑,例如,您可以定义自己的规则管理,或者适应特定的数据源。

Note:

  • SPI 全称为 Service Provider Interface,是一种服务发现机制
  • 用来给第三方实现或扩展的 API,它可以用于实现框架扩展或组件替换
  • SPI 机制本质是将接口实现类的全限定名配置在文件中,并由服务加载器读取配置文件,加载文件中的实现类,这样运行时可以动态的为接口替换实现类

5.2. 如何使用Sentinel

如果您想在您的项目中使用Sentinel,请使用带有组ID为com.alibaba.cloud和工件ID为spring-cloud-starter-alibaba-sentinel的启动器。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>

下面是一个如何使用Sentinel的简单示例:

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(ServiceApplication.class, args);
    }

}

@RestController
public class TestController {

    @GetMapping(value = "/hello")
    @SentinelResource("hello")
    public String hello() {
        return "Hello Sentinel";
    }

}

@SentinelResource注解用于识别资源是否受到速率限制或降级。在上面的示例中,注释的'hello'属性引用资源名。

@SentinelResource还提供诸如blockHandler、blockHandlerClass和fallback等属性来标识速率限制或降级操作。

有关更多详细信息,请参阅Sentinel注释支持

上面的示例都在WebServlet环境中使用。Sentinel目前支持WebFlux,需要与spring-boot-starter-webflux依赖项合作,在Sentinel启动器中触发与WebFlux相关的自动化配置。

@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

哨兵仪表板是一个轻量级控制台,提供了诸如机器发现、单服务器资源监视、集群资源数据概述以及规则管理等功能。要使用这些功能,您只需要完成几个步骤。

Note:集群统计概述只支持500节点以下的集群,时延约为1 ~ 2秒。

要使用Sentinel仪表板,只需完成以下3个步骤。

获取仪表板

您可以从发布页面下载最新的仪表板JAR文件。

你也可以获得最新的源代码来构建你自己的Sentinel仪表盘:

下载Dashboard项目。
运行以下命令将代码打包到一个FatJar中:mvn clean package

启动仪表板

哨兵仪表板是一个标准的SpringBoot应用程序,您可以在SpringBoot模式下运行JAR文件。

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard.jar

如果与8080端口冲突,可以使用  -Dserver.port=new port  定义新端口。

5.2.2. 配置Dashboard

application.yml

spring:
  cloud:
    sentinel:
      transport:
        port: 8719
        dashboard: localhost:8080

在 spring.cloud.sentinel.transport.port 中指定的端口号将启动应用程序对应服务器上的HTTP Server,该服务器将与Sentinel仪表板进行交互。例如,如果在Sentinel仪表板中添加了速率限制规则,则规则数据将被推送到HTTP Server并由HTTP Server接收,而HTTP Server又将规则注册到Sentinel。

5.3. OpenFeign支持

Sentinel与OpenFeign组件兼容。要使用它,除了引入sentinel-starter依赖之外,还需要完成以下2个步骤:

在properties file中启用Sentinel对Feign的支持

feign.sentinel.enabled=true

添加openfeign启动器依赖来触发并启用sentinel starter:

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

这是FeignClient的一个简单用法:

@FeignClient(name = "service-provider", fallback = EchoServiceFallback.class, configuration = FeignConfiguration.class)
public interface EchoService {
    @GetMapping(value = "/echo/{str}")
    String echo(@PathVariable("str") String str);
}

class FeignConfiguration {
    @Bean
    public EchoServiceFallback echoServiceFallback() {
        return new EchoServiceFallback();
    }
}

class EchoServiceFallback implements EchoService {
    @Override
    public String echo(@PathVariable("str") String str) {
        return "echo fallback";
    }
}

Note:Feign对应接口的资源名策略为  httpmethod:protocol://requesturl.

Sentinel支持@FeignClient注释中的所有属性。

EchoService接口中echo方法对应的资源名为  GET:http://service-provider/echo/{str}.

5.4. RestTemplate支持

Spring Cloud Alibaba Sentinel支持使用Sentinel保护RestTemplate服务调用。为此,您需要在构造RestTemplate bean时添加@SentinelRestTemplate注释。

@Bean
@SentinelRestTemplate(blockHandler = "handleException", blockHandlerClass = ExceptionUtil.class)
public RestTemplate restTemplate() {
    return new RestTemplate();
}

@SentinelRestTemplate注释的属性支持流控制(blockHandler, blockHandlerClass)和断路(fallback, fallbackClass)。

blockHandler或fallback是blockHandlerClass或fallbackClass的静态方法。

@SentinelRestTemplate中method的参数和返回值与org.springframework.http.client相同。但是它还有一个参数BlockException来捕获Sentinel的异常。

上面ExceptionUtil中handleException的方法签名应该是这样的:

public class ExceptionUtil {
    public static ClientHttpResponse handleException(HttpRequest request, byte[] body, ClientHttpRequestExecution execution, BlockException exception) {
        ...
    }
}

Note:当应用程序启动时,它将检查@SentinelRestTemplate注释相应的流量控制或断路方法对应的是否存在,如果不存在,它将抛出异常。

@SentinelRestTemplate注释的属性是可选的。

当你使用由sentinel阻塞的RestTemplate时,它将返回由sentinel阻塞的RestTemplate请求块。你可以用你自己的逻辑来覆盖它。我们提供SentinelClientHttpResponse来处理响应。

Sentinel RestTemplate为资源速率限制提供了两个粒度:

  • httpmethod:schema://host:port/path : Protocol, host, port and path

  • httpmethod:schema://host:port : Protocol, host and port

Note:以Http GET https://www.taobao.com/test为例。对应的资源名有两个粒度级别,GET:https://www.taobao.com和GET:https://www.taobao.com/test。

5.5. 动态数据源支持

SentinelProperties提供数据源属性来配置数据源。

例如,配置4个数据源:

spring.cloud.sentinel.datasource.ds1.file.file=classpath: degraderule.json
spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

#spring.cloud.sentinel.datasource.ds1.file.file=classpath: flowrule.json
#spring.cloud.sentinel.datasource.ds1.file.data-type=custom
#spring.cloud.sentinel.datasource.ds1.file.converter-class=JsonFlowRuleListConverter
#spring.cloud.sentinel.datasource.ds1.file.rule-type=flow

spring.cloud.sentinel.datasource.ds2.nacos.server-addr=127.0.0.1:8848
spring.cloud.sentinel.datasource.ds2.nacos.data-id=sentinel
spring.cloud.sentinel.datasource.ds2.nacos.group-id=DEFAULT_GROUP
spring.cloud.sentinel.datasource.ds2.nacos.data-type=json
spring.cloud.sentinel.datasource.ds2.nacos.rule-type=degrade

spring.cloud.sentinel.datasource.ds3.zk.path = /Sentinel-Demo/SYSTEM-CODE-DEMO-FLOW
spring.cloud.sentinel.datasource.ds3.zk.server-addr = localhost:2181
spring.cloud.sentinel.datasource.ds3.zk.rule-type=authority

spring.cloud.sentinel.datasource.ds4.apollo.namespace-name = application
spring.cloud.sentinel.datasource.ds4.apollo.flow-rules-key = sentinel
spring.cloud.sentinel.datasource.ds4.apollo.default-flow-rule-value = test
spring.cloud.sentinel.datasource.ds4.apollo.rule-type=param-flow

此方法遵循 Spring Cloud Stream Binder的配置。TreeMap用于内部存储,比较器是String.CASE_INSENSITIVE_ORDER。

Note:d1, ds2, ds3, ds4是ReadableDataSource的名称,可以根据您的喜好进行编码。文件zk、nacos、apollo指的是特定的数据源。它们后面的配置分别是这些数据源的特定配置。

每个数据源有3个公共配置项:data-typeconverter-class , rule-type.

data-type指Converter。Spring Cloud Alibaba Sentinel默认提供了两个嵌入值:json和xml(如果没有指定,默认为json)。如果您不想使用嵌入的json或xml Converter,您还可以填写custom以表示您将定义自己的Converter,然后配置转换器类。您需要为这个配置指定类的完整路径。

rule-type指数据源中的规则类型(flow、degrade、authority、system、param-flow、gw-flow、gw-api-group)。

Note:默认情况下不支持XML格式。为了使其有效,您需要添加jackson-dataformat-xml依赖项。

要了解更多关于动态数据源如何在Sentinel中工作的信息,请参阅动态规则扩展

5.6. Spring Cloud Gateway支持

参考 API Gateway Flow Control

如果你想和Spring Cloud Gateway一起使用Sentinel Starter,你需要添加Spring-Cloud-alibaba-Sentinel-Gateway依赖,并添加Spring-Cloud-Starter-Gateway依赖,让模块中的Spring Cloud Gateway AutoConfiguration类生效:

<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>

5.7. 断路器: Spring Cloud Circuit Breaker With Sentinel & Configuring Sentinel Circuit Breakers

5.7.1. 默认配置

要为所有断路器提供默认配置,请创建一个Customizer bean,它被传递给SentinelCircuitBreakerFactory或ReactiveSentinelCircuitBreakerFactory。configureDefault方法可用于提供默认配置。

@Bean
public Customizer<SentinelCircuitBreakerFactory> defaultCustomizer() {
	return factory -> factory.configureDefault(id -> new SentinelConfigBuilder(id)
			.build());
}

  你可以选择通过SentinelConfigBuilder#rules(rules)提供默认的断路规则。你也可以选择以后在其他地方加载断路规则,使用Sentinel的  DegradeRuleManager.loadRules(rules)   API,或者通过Sentinel仪表板。

反应性示例:

@Bean
public Customizer<ReactiveSentinelCircuitBreakerFactory> defaultCustomizer() {
	return factory -> factory.configureDefault(id -> new SentinelConfigBuilder(id)
			.build());
}

5.7.2. ju断路器配置

与提供默认配置类似,您可以创建Customizer bean,该bean通过SentinelCircuitBreakerFactory传递

@Bean
public Customizer<SentinelCircuitBreakerFactory> slowCustomizer() {
	String slowId = "slow";
	List<DegradeRule> rules = Collections.singletonList(
		new DegradeRule(slowId).setGrade(RuleConstant.DEGRADE_GRADE_RT)
			.setCount(100)
			.setTimeWindow(10)
		);
	return factory -> factory.configure(builder -> builder.rules(rules), slowId);
}

反应性示例:

@Bean
public Customizer<ReactiveSentinelCircuitBreakerFactory> customizer() {
	List<DegradeRule> rules = Collections.singletonList(
		new DegradeRule().setGrade(RuleConstant.DEGRADE_GRADE_RT)
			.setCount(100)
			.setTimeWindow(10)
		);
	return factory -> factory.configure(builder -> builder.rules(rules), "foo", "bar");
}

5.8. Sentinel Endpoint

Sentinel在内部提供一个Endpoint,其中包含Sentinel的相应端点id。

Endpoint exposed json包含多个属性:

  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

下面展示了服务实例如何访问Endpoint:

{
	"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
}

5.9. 配置

下表显示了当ApplicationContext中有相应的bean类型时,将采取一些操作:

Existing Bean Type

Action

Function

UrlCleaner

WebCallbackManager.setUrlCleaner(urlCleaner)

Resource cleaning(resource(for example, classify all URLs of /foo/:id to the /foo/* resource))

UrlBlockHandler

WebCallbackManager.setUrlBlockHandler(urlBlockHandler)

Customize rate limiting logic

RequestOriginParser

WebCallbackManager.setRequestOriginParser(requestOriginParser)

Setting the origin

下表是Spring Cloud Sentinel的所有配置:

Configuration

Description

Default Value

spring.application.name or project.name

Project Name Of Sentinel

spring.cloud.sentinel.enabled

Sentinel自动配置是否生效

true

spring.cloud.sentinel.eager

是否提前触发Sentinel初始化

false

spring.cloud.sentinel.transport.port

应用程序与Sentinel仪表板交互的端口。使用此端口的HTTP Server将在应用程序中启动

8719

spring.cloud.sentinel.transport.dashboard

哨兵仪表板地址

spring.cloud.sentinel.transport.heartbeatIntervalMs

应用程序和Sentinel仪表板之间的心跳间隔

spring.cloud.sentinel.transport.client-ip

此配置的客户端IP将注册到Sentinel Server端。

spring.cloud.sentinel.filter.order

Servlet过滤器的加载顺序。过滤器将在启动器中构造

Integer.MIN_VALUE

spring.cloud.sentinel.filter.url-patterns

数据类型为数组。指Servlet过滤器ULR模式的集合

/*

spring.cloud.sentinel.filter.enabled

启用CommonFilter实例

true

spring.cloud.sentinel.metric.charset

metric file character set

UTF-8

spring.cloud.sentinel.metric.fileSingleSize

Sentinel metric single file size

spring.cloud.sentinel.metric.fileTotalCount

Sentinel metric total file number

spring.cloud.sentinel.log.dir

Directory of Sentinel log files

spring.cloud.sentinel.log.switch-pid

If PID is required for Sentinel log file names

false

spring.cloud.sentinel.servlet.blockPage

自定义重定向URL。当速率限制时,请求将被重定向到预定义的URL

spring.cloud.sentinel.flow.coldFactor

ColdFactor

3

spring.cloud.sentinel.scg.fallback.mode

Spring Cloud GateWay断路后的响应模式(选择重定向或响应)

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’模式对应的内容类型。

application/json

Note:这些配置只在servlet环境中生效。RestTemplate和Feign对这些配置不生效。

6. Spring Cloud Alibaba RocketMQ Binder

6.1. RocketMQ介绍

RocketMQ是一个开源的分布式消息系统。它基于高可用的分布式集群技术,提供低延迟、高稳定性的消息发布和订阅服务。RocketMQ广泛应用于各种行业,如异步通信解耦、企业解决方案、金融结算、电信、电子商务、物流、营销、社交媒体、即时消息、移动应用程序、移动游戏、视频、物联网和车联网。

它具有以下特点:

  • 严格的信息发送和消费秩序

  • 丰富的消息提取模式

  • 消费者的横向可扩展性

  • 实时消息订阅

  • 十亿级的消息积累能力

6.2. RocketMQ用法

下载RocketMQ


下载RocketMQ最新二进制文件并解压。

解压后的目录如下:

apache-rocketmq
├── LICENSE
├── NOTICE
├── README.md
├── benchmark
├── bin
├── conf
└── lib
  • 开启 NameServer

nohup sh bin/mqnamesrv &
tail -f ~/logs/rocketmqlogs/namesrv.log
  • 开启 Broker

nohup sh bin/mqbroker -n localhost:9876 &
tail -f ~/logs/rocketmqlogs/broker.log
  • 发送和接收消息

发送消息

sh bin/tools.sh org.apache.rocketmq.example.quickstart.Producer

消息成功发送时的输出: SendResult [sendStatus=SEND_OK, msgId= …​

接收消息

sh bin/tools.sh org.apache.rocketmq.example.quickstart.Consumer

成功接收消息时的输出: ConsumeMessageThread_%d Receive New Messages: [MessageExt…​

  • 关闭 Server

sh bin/mqshutdown broker
sh bin/mqshutdown namesrv

6.3. Spring Cloud Stream介绍

Spring Cloud Stream是一个用于构建基于消息的架构的微服务框架。它帮助您创建基于SpringBoot的可生产的单服务器Spring应用程序,并使用Spring Integration与Broker连接。

Spring Cloud Stream提供了消息中间件配置的统一抽象,并提出了发布-订阅、消费者组和分区等概念。

Spring Cloud Stream中有两个概念:Binder和Binding

  • Binder: 用于与外部消息中间件集成的组件,并用于创建binding。不同的消息中间件产品有自己的绑定器实现。

例如,Kafka使用KafkaMessageChannelBinder, RabbitMQ使用RabbitMessageChannelBinder,而RocketMQ使用RocketMQMessageChannelBinder。

  • Binding: 包括输入绑定和输出绑定。

Binding充当消息中间件与应用程序的提供者和使用者之间的桥梁。开发人员只需要使用提供者或使用者来生成或使用数据,而不需要担心与消息中间件的交互。

 现在让我们使用Spring Cloud Stream来编写一个发送和接收消息的简单代码:

MessageChannel messageChannel = new DirectChannel();

// Message 订阅
((SubscribableChannel) messageChannel).subscribe(new MessageHandler() {
    @Override
    public void handleMessage(Message<? > message) throws MessagingException {
        System.out.println("receive msg: " + message.getPayload());
    }
});

// Message 发送
messageChannel.send(MessageBuilder.withPayload("simple msg").build());

此代码中的所有消息类型都由 spring-messaging module提供。它屏蔽了消息中间件的底层实现。如果希望更改消息中间件,只需要在配置文件中配置相关的消息中间件信息并修改绑定器依赖项。

Spring Cloud Stream的底层还基于前面的代码实现了各种代码抽象。

6.4. How to use Spring Cloud Alibaba RocketMQ Binder

要使用Spring Cloud Alibaba RocketMQ Binder,你只需要将它添加到Spring Cloud Stream应用程序中,使用以下Maven坐标:

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-stream-binder-rocketmq</artifactId>
</dependency>

或者,你也可以使用 Spring Cloud Stream RocketMQ Starter:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-stream-rocketmq</artifactId>
</dependency>

6.5. Spring Cloud Alibaba RocketMQ Binder如何工作

这是Spring Cloud Stream RocketMQ Binder的实现架构:

RocketMQ Binder的实现依赖于RocketMQ- spring框架。

RocketMQ Spring框架是RocketMQ和Spring Boot的集成。它提供了三个主要功能:

  1. RocketMQTemplate: 发送消息,包括同步消息、异步消息和事务性消息。

  2. @RocketMQTransactionListener: 监听并检查事务消息。

  3. @RocketMQMessageListener: 消费messages.

RocketMQMessageChannelBinder 是Binder的标准实现,它将在内部构建RocketMQInboundChannelAdapter 和 RocketMQMessageHandler。

RocketMQMessageHandler将基于绑定配置构造RocketMQTemplate。RocketMQTemplate将spring-messaging模块的org.springframework.messaging.Message消息类转换为RocketMQ消息类org.apache.rocketmq.common .message.Message,然后发送出去。

RocketMQInboundChannelAdapter 也会建构  RocketMQListenerBindingContainer基于绑定配置,RocketMQListenerBindingContainer将启动RocketMQ Consumer来接收消息。

Note: RocketMQ绑定应用程序”也可用于配置RocketMQ.**触发RocketMQ Spring相关的自动配置

目前Binder支持在Header中设置相关的键来设置RocketMQ消息的属性。

例如,TAGS、DELAY、TRANSACTIONAL_ARG、KEYS、WAIT_STORE_MSG_OK、FLAG表示与RocketMQ消息对应的标签。

MessageBuilder builder = MessageBuilder.withPayload(msg)
    .setHeader(RocketMQHeaders.TAGS, "binder")
    .setHeader(RocketMQHeaders.KEYS, "my-key")
    .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "1");
Message message = builder.build();
output().send(message);

或者使用StreamBridge

MessageBuilder builder = MessageBuilder.withPayload(msg)
    .setHeader(RocketMQHeaders.TAGS, "binder")
    .setHeader(RocketMQHeaders.KEYS, "my-key")
    .setHeader(MessageConst.PROPERTY_DELAY_TIME_LEVEL, "1");
Message message = builder.build();
streamBridge.send("producer-out-0", message);

Note:更多示例:RocketMQ示例

6.6.配置选项

6.6.1. RocketMQ Binder Properties

spring.cloud.stream.rocketmq.binder.name-server

   RocketMQ server的名称服务器(旧版本使用namesrv-addr配置项)。

   Default: 127.0.0.1:9876.

spring.cloud.stream.rocketmq.binder.access-key

   阿里巴巴云账户的AccessKey。

   Default: null.

spring.cloud.stream.rocketmq.binder.secret-key

   阿里巴巴云账户的秘钥。

   Default: null.

spring.cloud.stream.rocketmq.binder.enable-msg-trace

   为所有生产者和使用者启用消息跟踪功能。

   Default: true.

spring.cloud.stream.rocketmq.binder.customized-trace-topic   

   消息跟踪的跟踪主题。

   Default: RMQ_SYS_TRACE_TOPIC.

spring.cloud.stream.rocketmq.binder.access-channel

   rocketmq消息轨迹主题的商业版本为adaptive,取值为CLOUD

   Default: null.

6.6.2. RocketMQ Consumer Properties

以下属性仅对RocketMQ生产者可用,必须使用前缀

spring.cloud.stream.rocketmq.bindings.<channelName>.consumer..

enable

启用消费者绑定。

Default: true.

tags

消费者订阅标签表达式,标签以 ||  分隔。

Default: empty.

sql

消费者订阅sql表达式。

Default: empty.

broadcasting

控制消息模式,如果想让所有订阅者都收到消息,广播是一个不错的选择。

Default: false.

orderly

同时或有序地接收信息。

Default: false.

delayLevelWhenNextConsume

用于并发使用的消息使用重试策略:

  • -1,没有重试,直接放入DLQ(死信队列)

  • 0,broker 控制重试频率

  • >0,client 控制重试频率

    Default: 0.

suspendCurrentQueueTimeMillis

有序使用的消息使用重试的时间间隔。

Default: 1000.

6.6.3. RocketMQ Provider Properties

以下属性仅对RocketMQ生产者可用,必须使用前缀

spring.cloud.stream.rocketmq.bindings.<channelName>.producer..

enable

启用生产者绑定。

Default: true.

group

生产者组名称。

Default: empty.

maxMessageSize

允许的最大消息大小(以字节为单位)。

Default: 8249344.

transactional

发送事务消息

Default: false.

sync

以同步方式发送消息。

Default: false.

vipChannelEnabled

用vip通道发送消息。

Default: true.

sendMessageTimeout

发送消息超时时间。

Default: 3000.

compressMessageBodyThreshold

压缩消息体阈值,即缺省情况下,大于4k的消息体将被压缩。

Default: 4096.

retryTimesWhenSendFailed

在同步模式下声称发送失败之前在内部执行的最大重试次数。

Default: 2.

retryTimesWhenSendAsyncFailed

在异步模式下声称发送失败之前在内部执行的最大重试次数。

Default: 2.

retryNextServer

指示在内部发送失败时是否重试另一个代理。

Default: false.

7. Spring Cloud Alibaba Cloud ANS

ANS(应用程序命名服务)是EDAS的一个组件。Spring Cloud Alibaba Cloud ANS提供了符合Spring Cloud规范的服务注册和发现的商业版本,这样您就可以在本地开发您的应用程序并在云中运行它们。

Note:EDAS目前支持直接部署Nacos Discovery应用程序

7.1. 如何引入Spring Cloud Alibaba Cloud ANS

如果您想在您的项目中使用ANS,请使用带有组ID为com.alibaba.cloud和工件ID为spring-cloud-starter-alicloud-ans的启动器。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-ans</artifactId>
</dependency>

7.2. 使用ANS注册服务

当客户端引入Spring Cloud AliCloud ANS Starter时,服务的元数据(IP、端口号、权限等)会自动注册到注册中心。客户机将维护与服务器的心跳,以证明它能够正确地提供服务。

下面是一个简单的例子。

@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class ProviderApplication {

    @RequestMapping("/")
    public String home() {
        return "Hello world";
    }

    public static void main(String[] args) {
        SpringApplication.run(ProviderApplication.class, args);
    }

}

由于服务将注册到注册中心,因此我们需要配置注册中心的地址。我们还需要在application.properties中添加以下地址。

# 应用程序名称将用作服务名称,因此它是必选的。
spring.application.name=ans-provider
server.port=18081
# 以下为注册中心的IP地址和端口号。
spring.cloud.alicloud.ans.server-list=127.0.0.1
spring.cloud.alicloud.ans.server-port=8080

Note:到目前为止,注册中心还没有启动,因此如果启动了应用程序,您将收到一条错误消息。因此,在启动应用程序之前,请先启动注册中心。

7.3. 启动注册中心

ANS使用两种类型的注册中心。一个是免费的轻量级配置中心,另一个是通过EDAS提供的云端注册中心。通常,您可以使用轻量级版本进行应用程序开发和本地测试,而使用EDAS进行canary部署或生产。

7.3.1. 启动轻量级配置中心

关于如何下载和安装轻量级配置中心,请参见配置轻量级配置中心

No只需执行步骤1(下载轻量级配置中心)和步骤2(启动轻量级配置中心)。如果同时使用ANS,则不需要执行步骤3(配置主机)。

在启动轻量级配置中心之后,直接启动ProviderApplication,您将能够向配置中心注册您的服务。轻量级配置中心的默认端口为8080,因此您可以打开http://127.0.0.1:8080,单击左侧的“Services”,查看已注册的服务。

7.3.2. 云端用户注册中心

使用云上的注册中心可以省去服务器维护的繁琐工作,同时提供更好的稳定性。使用云上的注册中心和轻量级配置中心在代码级别上没有区别,但在配置上有一些区别。

下面是在云中使用注册中心的简单示例。

# 应用程序名称将用作服务名称,因此是必选的。
spring.application.name=ans-provider
# 配置自己的端口号
server.port=18081
# 以下为配置中心的IP地址和端口号。默认值为127.0.0.1和8080,因此可以省略以下行。
spring.cloud.alicloud.ans.server-mode=EDAS
spring.cloud.alicloud.access-key=Your Alibaba Cloud AK
spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK
spring.cloud.alicloud.edas.namespace=cn-xxxxx

服务器模式的默认值为LOCAL。如果要使用云上的注册中心,需要将其更改为EDAS。

接入密钥和密钥是您的阿里云账户的AK/SK。先注册一个阿里云账号,登录云控制台 Alibaba Cloud AK/SK复制您的AccessKey ID和AccessKey Secret。如果你还没有创建一个,点击“创建AccessKey”按钮。

命名空间是EDAS中的一个概念,用于隔离环境,如测试环境和生产环境。要找到您的名称空间,请先单击“注册EDAS”。在现收现付模式下,您不会被收费。然后登录到EDAS控制台,您将能够看到您的名称空间,例如cn-hangzhou。

Note:

EDAS提供应用程序托管服务,并为托管的应用程序自动填写所有配置。

8. Spring Cloud Alibaba Cloud ACM

Spring Cloud AliCloud ACM是Spring Cloud的商用产品ACM (Application Configuration Management)在客户端的实现,是免费的。关于ACM更多信息

使用Spring Cloud AliCloud ACM基于Spring Cloud的编程模型,快速访问ACM配置管理功能。

Note:目前EDAS已经支持直接部署Nacos Config应用程序。

8.1. 如何引入Spring Cloud Alibaba Cloud ACM

如果您想在您的项目中使用ACM,请使用组ID为com.alibaba.cloud和工件ID为spring-cloud-starter-alicloud-acm的启动器。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-acm</artifactId>
</dependency>

8.2. 使用ACM管理配置

当Spring Cloud Alibaba Cloud ACM Starter引入客户端时,应用程序启动时会自动从配置管理服务器获取配置信息,并将配置注入到Spring Environment中。

下面是一个简单的例子。

@SpringBootApplication
public class ProviderApplication {

    public static void main(String[] args) {
        ConfigurableApplicationContext applicationContext = SpringApplication.run(ProviderApplication.class, args);
        String userName = applicationContext.getEnvironment().getProperty("user.name");
        String userAge = applicationContext.getEnvironment().getProperty("user.age");
        System.err.println("user name :" +userName+"; age: "+userAge);
    }
}

由于我们需要从配置服务器获取配置信息,因此我们需要配置服务器的地址。我们还需要在bootstrap.properties中添加以下信息。

# 必需的。 应用程序名称将被用作关键字的一部分,以便从服务器获取配置密钥。
spring.application.name=acm-config
server.port=18081
# 以下为配置服务器的IP地址和端口号。
spring.cloud.alicloud.acm.server-list=127.0.0.1
spring.cloud.alicloud.acm.server-port=8080

Note:到目前为止,配置中心还没有启动,因此如果启动了应用程序,您将得到一条错误消息。因此,在启动应用程序之前,请先启动配置中心。

8.2.1. 启动配置中心

ACM使用两种配置中心。一个是轻量级配置中心,另一个是在阿里云上使用的ACM。通常,您可以使用轻量级版本进行应用程序开发和本地测试,而使用ACM进行canary部署或生产。

使用轻量级配置中心

关于如何下载和安装轻量级配置中心,请参见配置轻量级配置中心

Note:只需执行步骤1(下载轻量级配置中心)和步骤2(启动轻量级配置中心)。

请在阿里云上使用ACM

在云平台上使用ACM,可以省去服务器维护的繁琐工作,同时提供更好的稳定性。在云上使用ACM和在轻量级配置中心上使用ACM在代码级别上没有区别,但在配置上有一些区别。

下面是一个使用ACM的简单示例。您可以通过ACM控制台查看配置详情

# 应用程序名称将被用作关键字的一部分,用于从服务器获取配置密钥,并且是必选的
spring.application.name=acm-config
# 配置自己的端口号
server.port=18081
# 以下为配置中心的IP地址和端口号
spring.cloud.alicloud.acm.server-mode=EDAS
spring.cloud.alicloud.access-key=Your Alibaba Cloud AK
spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK
spring.cloud.alicloud.acm.endpoint=acm.aliyun.com
spring.cloud.alicloud.acm.namespace=Your ACM namespace(You can find the namespace on the ACM console)

Note:EDAS提供应用程序托管服务,并为托管的应用程序自动填写有关ACM的所有配置。

8.2.2. 在配置中心中添加配置

  1. 启动轻量级配置中心后,在控制台上添加以下配置。

Group:      DEFAULT_GROOUP

DataId:     acm-config.properties

Content:    user.name=james
            user.age=18

Note:dataId格式为{prefix}. {file-extension}   

“prefix”默认从spring.application.name获取,“file-extension”默认值为“properties”。

8.2.3. 启动应用程序验证

开始下面的示例,您可以看到打印在控制台上的值就是我们在轻量级配置中心中配置的值。

user name :james; age: 18

8.3. 修改配置文件扩展名

spring-cloud-starter-alcloudloud-acm中dataId默认的文件扩展名是properties。除了properties之外,还支持yaml。你可以使用spring.cloud.alicloud.acm.file-extension来设置文件扩展名。只需将其设置为yaml或yaml格式的' yml '。

Note:修改文件扩展名后,需要在配置中心的DataID和内容中进行相应的格式更改。

8.4. 动态刷新配置

spring-cloud-starter-alicloud-acm支持动态配置更新。当您在配置中心更新配置时,在Spring中发布RefreshEvent。所有带有@RefreshScope和@ConfigurationProperties注释的类将自动刷新。

Note:你可以通过以下设置禁用自动刷新:spring.cloud.alicloud.acm.refresh.enabled=false

8.5. 配置配置文件粒度

使用spring-cloud-starter-alicloud-acm加载配置时,使用DataId  {spring.application.name}. {file-extension}进行配置将被首先加载。如果有内容在  spring.profiles.active,spring.profile的内容,和配置的dataid格式为  {spring.application.name}-{profile}.{file-extension}  也将依次加载,后者具有更高的优先级。

spring.profiles.active 是配置元数据,并且也应该在bootstrap.properties或bootstrap.yaml。例如,您可以在bootstrap.properties中添加以下内容。

spring.profiles.active={profile-name}

Note:还可以通过JVM参数配置粒度,例如   -Dspring.profiles.active=develop 或者 有更高的优先级的--spring.profiles.active=develop。只要遵循Spring Boot的规范就可以了。

8.6. 支持自定义ACM超时时间

ACM client  从服务器获取配置的默认超时时间为3000ms。如果需要定义超时时间,请设置配置spring.cloud.alicloud.acm.timeout,单位为毫秒。

8.7. 支持自定义组配置

当没有定义{spring.cloud.alicloud.acm.group}配置时,默认使用DEFAULT_GROUP。如果您需要定义自己的分组,可以使用以下方法:

spring.cloud.alicloud.acm.group=DEVELOP_GROUP

Note:此配置必须放在bootstrap.properties中。Group的值必须与spring.cloud.alicloud.acm.group的值保持一致。

8.7.1. 支持共享配置

ACM提供了跨多个应用程序共享相同配置的解决方案。您可以通过在Bootstrap中添加spring.application.group配置来做到这一点。

spring.application.group=company.department.team

然后,应用程序将依次从以下DataId检索配置,然后再检索自己的配置:company:application。属性:company.department: application.properties,company.department.team:application.properties.

之后,它还从{spring.application.group}: {spring.application.name}. {file-extension}中检索配置。顺序越晚,优先级越高,应用程序本身的唯一配置具有最高优先级。

Note:DataId的默认后缀是properties,您可以使用spring.cloud.alicloud.acm.file-extension来更改它。{spring.application.group}: {spring.application.name}. {file-extension} .

Note:如果配置了spring.profiles.active,则DataId格式为  {spring.application.group}: {spring.application.name}-{spring.profiles.active}. {file-extension} 也支持,并且优先级高于

{spring.application.group}: {spring.application.name}. {file-extension}

8.8. Actuator Endpoint

ACM的执行器端点为 /acm,

config表示ACM元数据配置信息、

runtime.sources对应从ACM服务器获取的配置信息和最近一次刷新时间,

runtime.refreshHistory对应动态刷新历史。

9. Spring Cloud Alibaba Cloud OSS

对象存储服务(OSS)是阿里云上的一款存储产品。Spring Cloud Alibaba Cloud OSS提供符合Spring Cloud规范的商业化存储服务。我们提供易于使用的api,并支持在Spring框架中集成Resource。

9.1. 如何引入 Spring Cloud Alibaba Cloud OSS

我们发布了Spring Cloud Alibaba 0.2.1版本。您首先需要添加依赖管理POM。

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-alibaba-dependencies</artifactId>
            <version>0.2.2.BUILD-SNAPSHOT</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

接下来我们需要介绍Spring Cloud Alibaba Cloud OSS Starter。

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-oss</artifactId>
</dependency>

9.2. 如何使用OSS API

9.2.1. 配置OSS

在您开始使用 Spring Cloud Alibaba Cloud OSS之前,请在application.properties中添加以下配置。

spring.cloud.alicloud.access-key=Your Alibaba Cloud AK
spring.cloud.alicloud.secret-key=Your Alibaba Cloud SK
spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com

access-key和secret-key是您的阿里云账户的AK/SK。如果您没有,请先注册一个帐号,然后登录阿里云AK/SK管理,获取您的AccessKey ID和AccessKey Secret。如果你还没有创建AccessKey,点击“create AccessKey”创建一个。

关于端点信息,请参考OSS文档并获取您所在区域的端点。

9.2.2. 介绍OSS API

Spring Cloud Alibaba Cloud OSS 的OSS API是基于官方的OSS SDK,包含上传、下载、查看文件的API。

下面是一个使用OSS API的简单应用程序。

@SpringBootApplication
public class OssApplication {

    @Autowired
    private OSS ossClient;

    @RequestMapping("/")
    public String home() {
        ossClient.putObject("bucketName", "fileName", new FileInputStream("/your/local/file/path"));
        return "upload success";
    }

    public static void main(String[] args) throws URISyntaxException {
        SpringApplication.run(OssApplication.class, args);
    }

}

上传文件前,请先注册阿里云账号。如果你已经有一个,请注册OSS
登录网管控制台,单击“创建新桶”,根据界面提示创建桶。用新的桶名替换前面代码“bucketname”中的桶名。"fileName "可以是你喜欢的任何名称,"/your/local/file/path "可以是任何本地文件路径。接下来,您可以运行' curl http://127.0.0.1:port number/上传您的文件,您将在OSS控制台上看到您的文件。
关于OSS api的更多说明,请参考OSS SDK文档

9.3. 与Spring的资源规范集成

Spring Cloud Alibaba Cloud OSS 集成了Spring框架的Resource,可以让您轻松使用OSS资源。

下面是如何使用Resource的一个简单示例。

@SpringBootApplication
public class OssApplication {

    @Value("oss://bucketName/fileName")
    private Resource file;

    @GetMapping("/file")
    public String fileResource() {
        try {
            return "get file resource success. content: " + StreamUtils.copyToString(
                file.getInputStream(), Charset.forName(CharEncoding.UTF_8));
        } catch (Exception e) {
            return "get resource fail: " + e.getMessage();
        }
    }

    public static void main(String[] args) throws URISyntaxException {
        SpringApplication.run(OssApplication.class, args);
    }

}

Note:上述示例的一个先决条件是,您需要在OSS上有一个名为“bucketName”的桶,并且在这个桶中有一个名为“fileName”的文件。

9.4. Use STS Authentication

除了AccessKeys外,Spring Cloud阿里云OSS还支持STS认证。STS是一种带有临时安全令牌的身份验证方法,通常用于第三方临时访问其资源。

对于临时访问资源的第三方,只需要完成以下配置即可。

spring.cloud.alicloud.oss.authorization-mode=STS
spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com
spring.cloud.alicloud.oss.sts.access-key=Your authenticated AK
spring.cloud.alicloud.oss.sts.secret-key=Your authenticated SK
spring.cloud.alicloud.oss.sts.security-token=Your authenticated ST

其中,spring.cloud.alicloud.oss.authorization-mode是枚举类型。此处填写STS表示使用STS身份验证。关于端点信息,请参考OSS文档并为您的区域填写端点。

Access-key、secret-key和安全令牌需要由认证方颁发。有关STS的更多信息,请参考STS文档

9.5. 客户端的更多配置

除了基本配置,Spring Cloud Alibaba Cloud OSS还支持许多其他配置,这些配置也包含在application.properties。

下面是一些例子。

spring.cloud.alicloud.oss.authorization-mode=STS
spring.cloud.alicloud.oss.endpoint=***.aliyuncs.com
spring.cloud.alicloud.oss.sts.access-key=Your authenticated AK
spring.cloud.alicloud.oss.sts.secret-key=Your authenticated SK
spring.cloud.alicloud.oss.sts.security-token=Your authenticated ST

spring.cloud.alicloud.oss.config.connection-timeout=3000
spring.cloud.alicloud.oss.config.max-connections=1000

更多配置请参考OSSClient configurations底部的表格。

Note:在大多数情况下,对于OSSClient Configurations表中的参数,您需要用“-”连接参数名,并且所有字母都应该是小写的。例如,ConnectionTimeout应该更改为connection-timeout。

10. Spring Cloud Alibaba Cloud SchedulerX

SchedulerX(分布式作业调度)是Alibaba Cloud产品EDAS的一个组件。Alibaba Cloud Alibaba SchedulerX提供了符合Spring Cloud规范的分布式作业调度。SchedulerX提供秒级高精度、高稳定性、高可用性的定时作业调度服务,支持简单的单机作业、简单的多主机作业、脚本作业、网格作业等多种作业类型。

10.1. 如何引入Spring Cloud Alibaba Cloud SchedulerX

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-schedulerX</artifactId>
</dependency>

10.2. 开始SchedulerX

在Spring Cloud Alibaba Cloud SchedulerX Starter被引入到客户端之后,您只需要完成一些简单的配置,就可以自动初始化SchedulerX服务。

下面是一个简单的例子。

@SpringBootApplication
public class ScxApplication {

    public static void main(String[] args) {
        SpringApplication.run(ScxApplication.class, args);
    }

}

在application.properties中添加以下配置

server.port=18033
# cn-test is the test region of SchedulerX
spring.cloud.alicloud.scx.group-id=***
spring.cloud.alicloud.edas.namespace=cn-test

在获得group-id之前,请先注册阿里巴巴云账号,然后再注册EDASschedulex

Note:当您创建一个组时,请选择“test”区域。

10.3. 编译一个简单的任务

简单的工作是最常用的工作类型。您只需要实现ScxSimpleJobProcessor接口。
下面是一个简单的单服务器作业示例。

public class SimpleTask implements ScxSimpleJobProcessor {

	@Override
	public ProcessResult process(ScxSimpleJobContext context) {
		System.out.println("-----------Hello world---------------");
		ProcessResult processResult = new ProcessResult(true);
		return processResult;
	}

}

10.4. Job Scheduling

转到SchedulerX Jobs页面,选择“Test”区域,并单击右上角的“Create Job”创建一个作业,如下所示。

Job Group: Test——***-*-*-****
Job process interface:SimpleTask
Type: Simple Single-Server Job
Quartz Cron Expression: Default Option——0 * * * * ?
Job Description: Empty
Custom Parameters: Empty

上面的作业是一个“Simple Single-Server Job”,并指定了一个Cron表达式“0 * * * * ?”这意味着该作业每分钟只执行一次。

10.5. 在生产环境中的使用

前面的示例展示了如何在“Test”区域中使用SchedulerX,该区域主要用于本地测试。

在生产级别,除了上面提到的组id和名称空间外,还需要完成一些其他配置。参见下面的例子:

server.port=18033
# cn-test是SchedulerX的测试区域
spring.cloud.alicloud.scx.group-id=***
spring.cloud.alicloud.edas.namespace=***
# 如果应用程序运行在EDAS上,则不需要配置以下内容。
spring.cloud.alicloud.access-key=***
spring.cloud.alicloud.secret-key=***
#以下配置不是必须的。您可以参考SchedulerX文档了解详细信息。

spring.cloud.alicloud.scx.domain-name=***

获取 group-id 的方法与前面示例中描述的相同,您可以通过单击EDAS控制台左侧导航窗格中的“Namespaces”来获取名称空间。

Note:Group-id必须在命名空间内创建。

接入密钥和密钥是您的阿里云账户的AK/SK。如果将应用程序部署在EDAS上,则不需要填写此信息。否则请到安全信息获取您的AccessKeys。

11. Spring Cloud Alibaba Cloud SMS

SMS(短消息服务)是一种覆盖全球的消息服务,Alibaba SMS提供方便、高效和智能的通信能力,帮助企业快速联系他们的客户。

阿里云短信提供了一个更容易使用的API,可以快速访问基于Spring Cloud Alibaba SMS的阿里云短信服务。

11.1. 如何引入 Spring Cloud Alibaba Cloud SMS

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alicloud-sms</artifactId>
</dependency>

11.2. 如何使用短信API

11.2.1. 配置SMS

在您开始使用Spring Cloud Alibaba Clou SMS之前,请在application.properties中添加以下配置。

spring.cloud.alicloud.access-key=AK
spring.cloud.alicloud.secret-key=SK

access-key和secret-key是您的阿里云账户的AK/SK。如果您没有,请先注册一个帐号,然后登录 Alibaba Cloud AK/SK Management,获取您的AccessKey ID和AccessKey Secret。如果你还没有创建AccessKey,点击“create AccessKey”创建一个。

11.2.2. 介绍SMS API

Spring Cloud Alicloud SMS的短信API是基于 Alibaba Cloud SMS SDK的。它具有单个短信发送、多个短信批量发送、短信查询、短信(短信接收消息和上游短信)类操作API。

以下是如何使用SMS api发送短消息的简单示例:

@SpringBootApplication
public class SmsApplication {

    @Autowired
    private ISmsService smsService;

    @RequestMapping("/batch-sms-send.do")
    public SendBatchSmsResponse batchsendCheckCode(
            @RequestParam(name = "code") String code) {

        SendSmsRequest request = new SendSmsRequest();
        // 必填:手机号码
        request.setPhoneNumbers("152******");
        // 必填:SMS-SignName-could 在短信控制台中找到
        request.setSignName("******");
        // 必填:Template-could 在短信控制台中找到
        request.setTemplateCode("******");
        // 必填:短信模板参数。例如,如果模板是“你好,你的验证码是${code}”。参数应该像下面的值一样
        request.setTemplateParam("{\"code\":\"" + code + "\"}");
        SendSmsResponse sendSmsResponse ;
        try {
            sendSmsResponse = smsService.sendSmsRequest(request);
        }
        catch (ClientException e) {
            e.printStackTrace();
            sendSmsResponse = new SendSmsResponse();
        }
        return sendSmsResponse ;
    }

    public static void main(String[] args) throws URISyntaxException {
        SpringApplication.run(SmsApplication.class, args);
    }

}

在您发送信息之前,请先注册一个阿里云账号。如果您已经有短信服务,请打开短信服务

关于SMS的更多信息,请参考SMS官方SMS (SendSms)—JAVA]文档。

Note:由于早期SMS sdk版本的一个问题,如果文本消息无法发送,请删除包含显式MethodType为POST的代码行。如果您还有问题,请尽快与我们联系。

11.3. 短信Api的高级功能

为了降低学习成本,Spring Cloud Alicloud SMS包的API接口与官网提供的API和Example保持一致。

  • 批量发送短信

参考下面的示例,快速开发具有批量短信发送功能的功能。在控制器中添加以下代码或创建一个新的控制器:

@RequestMapping("/batch-sms-send.do")
public SendBatchSmsResponse batchsendCheckCode(
        @RequestParam(name = "code") String code) {
    SendBatchSmsRequest request = new SendBatchSmsRequest();
    request.setMethod(MethodType.GET);
    request.setPhoneNumberJson("[\"177********\",\"130********\"]");
    request.setSignNameJson("[\"*******\",\"*******\"]");
    request.setTemplateCode("******");
    request.setTemplateParamJson(
            "[{\"code\":\"" + code + "\"},{\"code\":\"" + code + "\"}]");
    SendBatchSmsResponse sendSmsResponse ;
    try {
        sendSmsResponse = smsService
                .sendSmsBatchRequest(request);
        return sendSmsResponse;
    }
    catch (ClientException e) {
        e.printStackTrace();
        sendSmsResponse =  new SendBatchSmsResponse();
    }
    return sendSmsResponse ;
}

Note:请求的MethodType设置为GET,与官网给出的示例有些不同。这是因为依赖的阿里云POP API版本不一致导致不兼容问题,设置为GET。

更多参数说明可在此参考

  • 短信查询 

        参考以下示例,可快速建立基于指定号码的短信发送历史记录。在控制器中添加以下代码或创建一个新的控制器:

@RequestMapping("/query.do")
public QuerySendDetailsResponse querySendDetailsResponse(
        @RequestParam(name = "tel") String telephone) {
    QuerySendDetailsRequest request = new QuerySendDetailsRequest();
    request.setPhoneNumber(telephone);
    request.setSendDate("20190103");
    request.setPageSize(10L);
    request.setCurrentPage(1L);
    try {
        QuerySendDetailsResponse response = smsService.querySendDetails(request);
        return response;
    }
    catch (ClientException e) {
        e.printStackTrace();
    }

    return new QuerySendDetailsResponse();
}

更多的参数描述可以在参考这里找到

  • SMS receipt message

通过订阅SmsReport短信状态报表,您可以了解每条短信的状态,以及是否了解终端用户的状态和相关信息。这些努力已经被Spring Cloud AliCloud SMS内部封装。您只需要完成以下两个步骤。

1、在应用中配置SmsReport的队列名称。application.properties(也可以是application.yaml)。

application.properties

spring.cloud.alicloud.sms.report-queue-name=Alicom-Queue-********-SmsReport

2、实现SmsReportMessageListener接口并初始化Spring Bean。

@Component
public class SmsReportMessageListener
		implements SmsReportMessageListener {

	@Override
	public boolean dealMessage(Message message) {
	    //do something
		System.err.println(this.getClass().getName() + "; " + message.toString());
		return true;
	}
}

更多message的消息体格式可在此参考

  • 上游短信

通过订阅SmsUp上游短信,您可以了解最终用户回复短信的内容。这些努力也被春云阿里云短信打包了。您只需要完成以下两个步骤。

1、在应用中配置SmsReport的队列名称。application.properties(也可以是application.yaml)。

application.properties

spring.cloud.alicloud.sms.up-queue-name=Alicom-Queue-********-SmsUp

2、实现SmsUpMessageListener接口并初始化Spring Bean。

@Component
public class SmsUpMessageListener
		implements org.springframework.cloud.alicloud.sms.SmsUpMessageListener {

	@Override
	public boolean dealMessage(Message message) {
    	//do something
		System.err.println(this.getClass().getName() + "; " + message.toString());
		return true;
	}
}

更多message的消息体格式可在此参考

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值