Spring Cloud微服务Sentinel+Apollo限流、熔断实战
    		       		warning:
    		            这篇文章距离上次修改已过424天,其中的内容可能已经有所变动。
    		        
        		                
                
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.ConfigService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
 
@RestController
public class SentinelController {
 
    private final Config config = ConfigService.getAppConfig();
 
    @GetMapping("/testSentinel")
    @SentinelResource(value = "test", blockHandler = "handleException")
    public String testSentinel(@RequestParam(value = "p", defaultValue = "0") int p) {
        if (p > 0) {
            // 模拟长时间运行的业务逻辑
        }
        return "Sentinel 限流和熔断测试";
    }
 
    public String handleException(String s, BlockException ex) {
        // 可以根据配置的Apollo值进行逻辑处理
        String fallback = config.getProperty("fallback", "fallback");
        return fallback;
    }
}这段代码展示了如何在Spring Cloud微服务中使用Sentinel进行限流和熔断,并结合Apollo进行动态配置。testSentinel方法使用了@SentinelResource注解来标记资源,并指定了异常处理方法handleException。在业务逻辑中,我们模拟了一个根据参数判断的长时间运行的操作,Sentinel会根据配置的规则进行流量控制和熔断。异常处理方法handleException会从Apollo获取配置来决定返回值。
评论已关闭