SpringCloud: sentinel链路限流

一、配置文件要增加

      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控制台设置链路限流规则:
SpringCloud: sentinel链路限流_第1张图片
五、启动应用,快速刷新接口/getUser1
SpringCloud: sentinel链路限流_第2张图片

你可能感兴趣的:(SpringCloud,spring,cloud,sentinel,java)