SpringCloud: sentinel链路限流

本文介绍了如何在SpringCloud项目中配置Sentinel进行服务限流,包括设置webContextUnify参数,使用@SentinelResource注解标记业务方法,并在sentinel控制台配置链路限流规则。示例展示了如何在Controller中调用被限流的服务方法。
摘要由CSDN通过智能技术生成

一、配置文件要增加

      spring.cloud.sentinel.webContextUnify: false

二、在要限流的业务方法上使用@SentinelResource注解

package cn.edu.tju.service;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.stereotype.Service;

@Service
public class UserService {
    @SentinelResource(value = "getUser", blockHandler = "myBlockingHandler")
    public String getUser(){
        return " a user...";
    }

    public String myBlockingHandler(BlockException ex){
        System.out.println("链路限流");
        return "链路限流啦";
    }
}

三、定义接口调用业务方法

package cn.edu.tju.controller;

import cn.edu.tju.service.UserService;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/getUser1")
    public String getUser1(){
        return userService.getUser();
    }



    @RequestMapping("/getUser2")
    public String getUser2(){
        return userService.getUser();
    }
}

四、在sentinel控制台设置链路限流规则:
在这里插入图片描述
五、启动应用,快速刷新接口/getUser1
在这里插入图片描述

Spring Cloud Alibaba是一个基于Spring Cloud的开源框架,提供了丰富的微服务开发工具包,包括服务注册与发现、配置管理、消息总线、负载均衡、熔断降级、分布式事务、流量控制、安全控制、分布式追踪等功能。 Spring Cloud Alibaba与Nacos、Dubbo、Sentinel等组件协同工作,Nacos作为注册中心和配置中心,Dubbo作为RPC框架,Sentinel作为流量控制和熔断降级组件,共同构建起完整的微服务生态体系。 使用Spring Cloud Alibaba进行服务注册和发现,可以通过注解@EnableDiscoveryClient开启服务注册与发现功能,并通过@FeignClient或@LoadBalanced注解实现服务调用和负载均衡。 使用Spring Cloud Alibaba进行服务治理,可以通过注解@EnableCircuitBreaker开启熔断降级功能,并通过@SentinelResource注解配置熔断降级规则。 使用Spring Cloud Alibaba进行熔断降级,可以通过Sentinel Dashboard进行实时监控和管理,同时通过注解@SentinelRestTemplate实现对RestTemplate的熔断降级。 使用Spring Cloud Alibaba进行服务配置管理,可以通过注解@EnableConfigNacosConfig和@Value注解实现动态配置管理。 使用Spring Cloud Alibaba进行分布式事务管理,可以通过注解@EnableDistributedTransaction开启分布式事务管理功能,并通过@GlobalTransactional注解实现分布式事务的统一管理和控制。 使用Spring Cloud Alibaba进行链路追踪,可以通过注解@EnableZipkinServer和@EnableZipkinClient开启链路追踪功能,并通过Sleuth和Zipkin实现对微服务调用链的追踪和分析。 使用Spring Cloud Alibaba进行服务限流,可以通过Sentinel进行实时流控和熔断降级,同时通过注解@SentinelResource实现对服务的限流控制。 Spring Cloud Alibaba支持微服务的服务网关管理,可以通过注解@EnableZuulProxy或@EnableGateway开启服务网关功能,并通过Zuul或Gateway实现微服务的API网关管理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值