spring cloud sentinel集成

本文详细介绍了SpringCloudSentinel的使用,包括其应用场景(限流、熔断和监控),组件构成(dashboard和客户端),并展示了如何在dashboard上搭建、配置客户端限流规则以及在rest接口和服务类中应用sentinel进行流量控制。
摘要由CSDN通过智能技术生成

目录

1. sentinel使用场景

2.  sentinel组成

3. sentinel dashboard搭建

 4. sentinel客户端详细使用

4.1 引入依赖

4.2 application.properties增加dashboard注册地址

4.3 手动增加限流配置类

4.4 rest接口及service类

4.5 通过dashboard动态配置限流规则


1. sentinel使用场景

限流、熔断、监控、动态规则配置

2.  sentinel组成

由两部分组成,

第一个是dashboard监控仪表盘,单独的jar,官网下载后启动,可监控所有服务、动态发现服务、配置限流策略、熔断等;

第二个是sentinel的客户端核心包,供微服务引用,注册到dashboard仪表盘,引入相关pom及设置相关配置即可;

3. sentinel dashboard搭建

启动命令

java -Dserver.port=8400 -Dcsp.sentinel.dashboard.server=localhost:8400 -Dproject.name=hj-sentinel -Dsentinel.dashboard.auth.username=sentinel -Dsentinel.dashboard.auth.password=sentinel -jar sentinel-dashboard-1.8.6.jar

启动成功,地址栏输入localhost:8400, 如图:

 

 4. sentinel客户端详细使用

4.1 引入依赖

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

4.2 application.properties增加dashboard注册地址

spring.cloud.sentinel.transport.dashboard=localhost:8400

4.3 手动增加限流配置类

package hj.example.sampleprovider.sample.config;

import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: sentinel 限流规则配置类
 **/
@Configuration
public class SentinelRulesConfig {
    @Bean
    public void initFlowQpsRules() {
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();
        flowRule.setResource("sentinelTest");
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule.setCount(1);
        flowRule.setLimitApp("default");
        flowRule.setClusterMode(false);
        flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        rules.add(flowRule);

        FlowRule flowRule1 = new FlowRule();
        flowRule1.setResource("sayHello");
        flowRule1.setGrade(RuleConstant.FLOW_GRADE_QPS);
        flowRule1.setCount(1);
        flowRule1.setLimitApp("default");
        flowRule1.setClusterMode(false);
        flowRule1.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT);
        rules.add(flowRule1);
        FlowRuleManager.loadRules(rules);
    }
}

4.4 rest接口及service类

其中sentinelTest为rest接口限流,sayHello为方法限流

package hj.example.sampleprovider.sample.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSONObject;
import hj.example.sampleprovider.sample.HelloServiceImpl;
import hj.example.sampleprovider.sample.config.SentinelRulesConfig;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: TODO
 **/
@RestController
public class SentinelTestController {

    @Autowired
    private HelloServiceImpl helloService;

    @RequestMapping("/testClean/{id}")
    public ResponseEntity<Object> testClean(@PathVariable("id") String id) {
        String resultStr = String.format("test clean id: %s [%s]", id, DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss ssss"));
        return new ResponseEntity<>(resultStr , HttpStatus.OK);
    }

    @RequestMapping("/testSentinelDynamicDashboard")
    public ResponseEntity<Object> testSentinelDynamicDashboard() {
        String resultStr = String.format("testSentinelDynamicDashboard [%s]", DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss sss"));
        return new ResponseEntity<>(resultStr, HttpStatus.OK);
    }

    @RequestMapping("/sayHello")
    public ResponseEntity<Object> sayHelloTest() {
        String helloStr = helloService.sayHello("sayHelloTest");
        return new ResponseEntity<>(helloStr, HttpStatus.OK);
    }

    @SentinelResource(value = "sentinelTest", blockHandler = "sentinelTestHandler")
    @RequestMapping("/sentinelTest")
    public ResponseEntity<Object> sentinelTest() {
        System.out.println(" sentinelTest :" + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss sss"));
        return new ResponseEntity<>("sentinelTest ", HttpStatus.OK);
    }
    public ResponseEntity<Object>  sentinelTestHandler(BlockException e) {
        System.out.println("被限流了");
        return new ResponseEntity<>("========sentinelTestHandler 被限流了:" + JSONObject.toJSONString(e), HttpStatus.OK);
    }
}
package hj.example.sampleprovider.sample;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.fastjson.JSON;
import hj.example.sample.IHelloService;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Value;
import test.SentinelTest;

import javax.xml.bind.ValidationException;
import java.util.Date;

@DubboService
public class HelloServiceImpl implements IHelloService {

    @Value("${dubbo.application.name}")
    private String serviceName;

    @SentinelResource(value = "sayHello", blockHandler = "sayHelloBlockHandler")
    public String sayHello(String name) {
        System.out.printf("[%s]: Hello, %s%n", serviceName, name);
        return String.format("[%s]: Hello, %s", serviceName, name);
    }

    public String sayHelloBlockHandler(String name, BlockException e) throws ValidationException {
        System.out.println("sayHello 被限流了。name:" + name + ",被限流了:" + JSON.toJSONString(e));
        return "sayHello 被限流了。name:" + name + ",被限流了:" + JSON.toJSONString(e);
    }

    public void sentinelTestMethod() {
        try(Entry entry = SphU.entry("sentinelTestMethod")) {
            System.out.println("hello sentinel : " + DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss sss"));
        }catch (BlockException e) {
            e.printStackTrace();
        }
    }

    public void sentinelTestHandler(BlockException e) throws ValidationException {
        e.printStackTrace();
        throw new ValidationException(e.getMessage());
    }
}

4.5 通过dashboard动态配置限流规则

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud集成Sentinel非常简单,只需要添加SentinelSentinel Dashboard的依赖,然后在启动类上加上`@EnableCircuitBreaker`注解即可。下面我们来详细介绍一下整个过程。 1. 添加依赖 在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel-datasource-nacos</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId> </dependency> ``` 其中,`spring-cloud-starter-alibaba-sentinel`是Sentinel的依赖,`spring-cloud-alibaba-sentinel-datasource-nacos`是Sentinel使用Nacos作为数据源的依赖,`spring-cloud-alibaba-nacos-discovery`是Nacos的依赖。 2. 启用Sentinel 在启动类上添加`@EnableCircuitBreaker`注解,启用Sentinel: ```java @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 配置Sentinel 在application.yml文件中添加如下配置: ```yaml spring: application: name: service-provider cloud: sentinel: transport: dashboard: localhost:8080 datasource: ds1: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-flow-rules groupId: DEFAULT_GROUP rule-type: flow ``` 其中,`transport.dashboard`配置Sentinel Dashboard的地址,`datasource`配置Sentinel使用Nacos作为数据源,`nacos.server-addr`配置Nacos的地址,`dataId`指定流控规则的Data ID,`groupId`指定Nacos的Group ID,`rule-type`指定规则类型。 4. 配置Sentinel Dashboard 下载Sentinel Dashboard,启动Sentinel Dashboard: ```bash java -jar sentinel-dashboard-1.8.1.jar ``` 访问http://localhost:8080即可查看Sentinel Dashboard。 5. 配置流控规则 在Nacos中添加流控规则。以service-provider服务为例,添加Data ID为service-provider-flow-rules的配置项,内容为: ```json [ { "resource": "hello", "count": 3.0, "grade": 1, "limitApp": "default", "strategy": 0, "controlBehavior": 0, "clusterMode": false } ] ``` 其中,`resource`指定资源名称,`count`指定阈值,`grade`指定流控模式,`limitApp`指定流控针对的调用来源,`strategy`指定流控策略,`controlBehavior`指定流控效果,`clusterMode`指定是否为集群模式。 6. 测试 启动服务提供者和服务消费者,访问http://localhost:8081/hello,即可触发流控规则,Sentinel会阻止请求并返回限流信息。 以上就是Spring Cloud集成Sentinel的整个过程,希望对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值