关于Nacos的学习我们算是可以告一段落呢?在这里我们学习下springcloud Alibaba的另外一个组件Sentinel,流量的防卫兵,先来了解下什么Sentinel?
什么是Sentinel?
官方给出:Sentinel是分布式系统的流量防卫兵,主要是从系统的稳定性出发,而Sentinel主要是通过限流的方式来控制服务降级和保护我们的服务资源.
这里提到了服务降级,我们可能会想到Hystrix,关于这一块两者还是有些区别的,实现的方式不一样,详情请看官方文档:Sentinel,接下来我们先从Sentinel的限流入手,在开始前,先来启动下Sentinel Dashboard(Sentinel的控制台),我这里是使用的版本为1.6.0版本,下载地址为:https://github.com/alibaba/Sentinel/releases,昨晚下的1.6.0版本,今天一看版本升级到了1.7.0,尴尬,不过不影响,下载下来就一个jar包,通过java - jar 直接启动即可.
- 启动完毕之后,直接访问127.0.0.1:8080,会看到如下的截图:

默认的用户名和密码都是sentinel,会看到如下图:

整合sentinel
这里我还是在我之前的nacos-server的项目创建module为alibaba-nacos-sentinel,接着我们来看pom文件,代码如下:
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.2</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
- 接着来看配置文件,代码如下:
server:
port: 9007
spring:
application:
name: alibaba-nacos-sentinel
cloud:
sentinel:
transport:
dashboard: 127.0.0.1:8080
- 来看我们的启动类和接口方法
package com.alibaba.sentinel;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author cb
*/
@SpringBootApplication
@Slf4j
@RestController
public class AlibabaNacosSentinelApplication {
public static void main(String[] args) {
SpringApplication.run(AlibabaNacosSentinelApplication.class, args);
}
@GetMapping("hello")
@SentinelResource("hello")
public String hello(){
return "hello Sentinel";
}
我们启动服务访问http://127.0.0.1:9007/hello,然后我们启动Sentinel Dashboard控制台会发现我们的服务和接口被实时监控,详情如下图:

我们可以在控制台上的配置限流的规则,如图:



上述的操作,是对我们的hello接口的访问做了上限操作,我这里配置的上限为3,接着我们访问该接口超过3次时会出现如图的结果:


我们这里实现了限流的操作,这就是Sentinel的简单的操作
网友评论