update spring-cloud-alibaba to v2.1.2.RELEASE

This commit is contained in:
zlt2000
2020-04-16 11:57:27 +08:00
parent 5b1f1b55bd
commit 2d67a0aed7
6 changed files with 55 additions and 16 deletions
@@ -1,34 +1,65 @@
package com.central.sentinel.config;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.spring.webflux.callback.WebFluxCallbackManager;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.config.SentinelWebMvcConfig;
import com.central.common.model.Result;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Sentinel配置类
*
* @author zlt
* @date 2019/1/22
* <p>
* Blog: https://blog.csdn.net/zlt2000
* Github: https://github.com/zlt2000
*/
public class SentinelAutoConfigure {
public SentinelAutoConfigure() {
WebCallbackManager.setUrlBlockHandler(new CustomUrlBlockHandler());
/**
* 限流、熔断统一处理类
*/
@Configuration
@ConditionalOnClass(HttpServletRequest.class)
public static class WebmvcHandler {
public WebmvcHandler(SentinelWebMvcConfig config) {
config.setBlockExceptionHandler(webmvcBlockExceptionHandler());
}
public BlockExceptionHandler webmvcBlockExceptionHandler() {
return (request, response, e) -> {
response.setStatus(429);
Result result = Result.failed(e.getMessage());
response.getWriter().print(JSONUtil.toJsonStr(result));
};
}
}
/**
* 限流、熔断统一处理类
*/
public class CustomUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
Result result = Result.failed("flow-limiting");
httpServletResponse.getWriter().print(JSONUtil.toJsonStr(result));
@Configuration
@ConditionalOnClass(ServerResponse.class)
public static class WebfluxHandler {
public WebfluxHandler() {
WebFluxCallbackManager.setBlockHandler(webfluxBlockExceptionHandler());
}
public BlockRequestHandler webfluxBlockExceptionHandler() {
return (exchange, t) ->
ServerResponse.status(HttpStatus.TOO_MANY_REQUESTS)
.contentType(MediaType.APPLICATION_JSON)
.body(BodyInserters.fromObject(Result.failed(t.getMessage())));
}
}
}