org.yes.tools.handle.UrlBlockHandler Maven / Gradle / Ivy
package org.yes.tools.handle;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import java.util.HashMap;
import java.util.Map;
/**
* sentinel统一降级限流策略
*
* {@link com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.DefaultBlockExceptionHandler}
*
* @author Co.
* @date 2023/10/24 10:24
*/
@Slf4j
@RequiredArgsConstructor
public class UrlBlockHandler implements BlockExceptionHandler {
private final ObjectMapper objectMapper;
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
log.error("sentinel 降级 资源名称{}", e.getRule().getResource(), e);
response.setContentType(MediaType.APPLICATION_JSON.getType());
response.setStatus(HttpStatus.OK.value());
Map map = new HashMap();
map.put("code", HttpStatus.INTERNAL_SERVER_ERROR.value());
map.put("message", e.getMessage());
response.getWriter().print(objectMapper.writeValueAsString(map.toString()));
}
}