您好,登錄后才能下訂單哦!
1.錯誤重定向: 增加組建,通用異常捕獲處理(增加sentinel異常次數-Tracer.trace(e))
(1).錯誤重定向
@Component
public class MyUrlBlockHandler implements UrlBlockHandler {
@Override
public void blocked(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws IOException {
Map<String,Object> backMap=new HashMap<>();
backMap.put("error","sentinel error");
if (e instanceof FlowException){
backMap.put("code",100);
backMap.put("msg","限流-異常");
}else if (e instanceof DegradeException){
backMap.put("code",101);
backMap.put("msg","降級-異常");
}else if (e instanceof ParamFlowException){
backMap.put("code",102);
backMap.put("msg","熱點-異常");
}else if (e instanceof SystemBlockException){
backMap.put("code",103);
backMap.put("msg","系統規則-異常");
}else if (e instanceof AuthorityException){
backMap.put("code",104);
backMap.put("msg","認證-異常");
}
// 設置返回json數據
String header= MediaType.APPLICATION_JSON_UTF8_VALUE;
httpServletResponse.setStatus(200);
httpServletResponse.setHeader("content-Type",header);
httpServletResponse.setContentType(header);
httpServletResponse.getWriter().write(JSON.toJSONString(backMap));
}
}
(2).通用異常捕獲處理(增加sentinel異常次數)
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
// 處理身份異常
@ExceptionHandler(SecurityException.class)
public ResponseEntity<ApiResult> handler(SecurityException e) {
ApiResult backResult = ApiResult.builder().code(1001).message(e.getMessage()).build();
Tracer.trace(e);
return new ResponseEntity<ApiResult>(backResult, HttpStatus.OK);
}
// 處理表單字段異常
@ExceptionHandler(FormFieldErrorException.class)
public ResponseEntity<ApiResult> handler(FormFieldErrorException e) {
ApiResult backResult = ApiResult.builder()
.code(1003)
.data(e.getFieldMessage())
.message(e.getMessage())
.build();
Tracer.trace(e);
return new ResponseEntity<ApiResult>(backResult, HttpStatus.OK);
}
}
來源處理,服務來源傳遞
思路:
(1).【Client方】,設置當前 Fegin 頭部的【source-origin】值為當前應用名稱: spring.application.name
(2).【被調用方】,配置Sentinel的Origin解析操作
(1).Fegin 服務來源傳遞
@Configuration
@Slf4j
public class MyRequestInterceptor implements RequestInterceptor {
@Value("${spring.application.name}")
String applicationName;
@Override
public void apply(RequestTemplate requestTemplate) {
requestTemplate.header("source-origin", applicationName);
}
}
(2).來源處理,增加組建
@Slf4j
@Component
public class MyRequestOriginParse implements RequestOriginParser {
@Override
public String parseOrigin(HttpServletRequest httpServletRequest) {
String origin=httpServletRequest.getHeader("source-origin");
if (StringUtils.isBlank(origin)){
origin="default";
}
// log.info("頭部名稱是: "+ JSON.toJSONString(httpServletRequest.getHeaderNames()));
// log.info("來源是: "+origin);
return origin;
}
}
(3).【sentinel控制臺】測試服務來源限制
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。