Sentinel部署以及Spring Cloud应用配置

429 阅读2分钟

简介

Sentinel 是面向分布式、多语言异构化服务架构的流量治理组件,主要以流量为切入点,从流量路由、流量控制、流量整形、熔断降级、系统自适应过载保护、热点流量防护等多个维度来帮助开发者保障微服务的稳定性。
Sentinel 作为 Spring Cloud Alibaba 的一员,用于分布式服务解决方案的流量控制与服务降级。
本文则主要记录在 Docker 上搭建 Sentinel 的过程,以及在 Spring Cloud 应用中如何配置。

部署 Sentinel Dashboard

通过发布JAR包部署

1.下载JAR包

GitHub Sentinel RELEASES: github.com/alibaba/Sen…

2.运行 Sentinel Dashboard

-Dserver.port,用于指定 Sentinel 控制台端口
-Dcsp.sentinel.dashboard.server,用于指定 Sentinel 控制台地址和端口

nohup java -Dserver.port=8080 \
  -Dcsp.sentinel.dashboard.server=localhost:8080 \ 
  -Dproject.name=sentinel-dashboard \
  -jar sentinel-dashboard.jar \
  > sentinel.out 2>&1 &

通过构建源码部署

1.下载 Sentinel Dashboard 工程

Github Sentinel Dashboard: github.com/alibaba/Sen…

2.运行 Sentinel Dashboard

这里是在Docker镜像容器内运行的JAR包,也可不使用容器运行

docker run -d \
  --name sentinel-dashboard \
  -v /data/sentinel/sentinel-dashboard-1.8.1.jar:/sentinel-dashboard.jar \
  -p 8086:8080 \
  openjdk:8-alpine \
  java -Dserver.port=8080 \
  -Dcsp.sentinel.dashboard.server=localhost:8080 \
  -Dproject.name=sentinel-dashboard \
  -jar sentinel-dashboard.jar

鉴权配置

从 Sentinel 1.6.0 开始,Sentinel 控制台支持简单的登录功能,默认用户名和密码都是sentinel
-Dsentinel.dashboard.auth.username用于指定控制台的登录用户名
-Dsentinel.dashboard.auth.password用于指定控制台的登录密码
这里演示了在Docker中通过环境变量指定参数的方式

docker run -d \
  --name sentinel-dashboard \
  -p 6060:6060
  -e sentinel_dashboard_auth_username=wei
  -e sentinel_dashboard_auth_password=wei001
  openjdk:8-alpine

Spring Cloud应用配置

模块及依赖管理

聚合模块的POM

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

子模块的POM

引入spring-cloud-starter-alibaba-sentinel依赖

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

应用配置

接入监控

transport模块用来与 Sentinel Dashboard 进行通信
transport.dashboard指定 Sentinel Dashboard 地址
transport.port由 Transport 启动的一个 Http Server 所占用的端口,来与 Sentinel 控制台通信

spring:
  application:
    name: order-service
  cloud:
    sentinel:
      transport:
        dashboard: 127.0.0.1:6060
        port: 8719

注解式监控资源

@SentinelResource注解用来标识资源是否被限流、降级

@RestController
public class SentinelFlowLimitController {

    @SentinelResource("testA")
    @GetMapping("/test/a")
    public String testA() {
        return "testA";
    }
}

参考

[1] Sentinel 介绍: sentinelguard.io/zh-cn/docs/…
[2] Sentinel 控制台: sentinelguard.io/zh-cn/docs/…
[3] Github Sentinel Releases: github.com/alibaba/Sen…
[4] GitHub Sentinel Dashboard: github.com/alibaba/Sen…
[5] Cloud Alibaba Sentinel Wiki: github.com/alibaba/spr…
[6] Sentinel Dashboard Wiki: github.com/alibaba/Sen…