Sentinel 和SpringBoot /SpringCloud,apollo的结合

1,引入相关包

        
            org.springframework.cloud
            spring-cloud-starter-alibaba-sentinel
            0.9.0.RELEASE
        
        
            com.alibaba.csp
            sentinel-datasource-apollo
            1.6.1
        

2,定义资源

@SentinelResource(value = "XXX")
    public ResponseObject getList(@RequestHeader(value = "lang", required = false, defaultValue = "EN") Language lang) {
       。。。。。。
    }

3,从apollo获得规则

@Configuration
public class SentinelConfig {
    @Value("${sentinel.defaultCount:2000}")
    private double defaultCount;
    //并发线程数
    @Value("${sentinel.defaultGrade:0}")
    private int defaultGrade;
    //Warm Up
    @Value("${sentinel.controlBehavior:1}")
    private int controlBehavior;
    @PostConstruct
    public void loadRuleManager(){
        // Apollo 的命名空间
        String namespaceName = "application";
        // 限流规则的Key, 在Apollo中用此Key
        String flowRuleKey = "sentinel.flowRules";
        // 限流规则的默认值
        String defaultFlowRules = "[]";
        // 注册数据源
        ReadableDataSource> flowRuleDataSource = new ApolloDataSource<>(namespaceName,
                flowRuleKey, defaultFlowRules, source -> {
            JSONArray jsonArray = JSON.parseArray(source);
            JSONArray newJsonArray = jsonArray.stream().map(b -> {
                JSONObject jsonObj = (JSONObject) b;
                jsonObj.put("grade", null == jsonObj.getInteger("grade") ? defaultGrade : jsonObj.getInteger("grade"));
                jsonObj.put("count", null == jsonObj.getDouble("count") ? defaultCount : jsonObj.getDouble("count"));
                jsonObj.put("controlBehavior", null == jsonObj.getInteger("controlBehavior") ? controlBehavior : jsonObj.getInteger("controlBehavior"));
                return jsonObj;
            }).collect(Collectors.toCollection(JSONArray::new));
            List flowRuleList =  newJsonArray.toJavaList(FlowRule.class);
            return flowRuleList;
        });
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
    }
}

4,错误处理逻辑

@ControllerAdvice
@Slf4j
public class XXControllerAdvice {



  

    @ResponseBody
    @ExceptionHandler(value = UndeclaredThrowableException.class)
    @ResponseStatus(HttpStatus.OK)
    public Response errorHandler(UndeclaredThrowableException e) {
        if (e.getCause() instanceof BlockException){
            log.error("BlockException occurred:{}", ((BlockException) e.getCause()).getRule().getResource());
            return Response.error(ResponseCode.FORBIDDEN.getCode(), ResponseCode.FORBIDDEN.getMessageKey());
        }
        log.error("Exception occurred:", e);
        return Response.error(ResponseCode.INTERNAL_ERROR.getCode(), e.getMessage());

    }

}

5,控制台配置,可以放入apllo

spring.cloud.sentinel.eager= true
spring.cloud.sentinel.transport.port= 8720
spring.cloud.sentinel.transport.dashboard= 127.0.0.1:8780
spring.cloud.sentinel.transport.heartbeat-interval-ms= 500

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