Spring项目集成Sentinel,自定义BlockException异常返回值

8 篇文章 0 订阅

背景

Sentinel 官网文档:introduction

springmvc项目中集成sentinel,通过sentinel提供的控制台配置限流、熔断等规则,

项目实现UrlBlockHandler,实现在catch到blockexception时进行自定义返回值处理

sentinel的官网文档非常详细的介绍了如何下载部署控制台、以及如何接入各类型的项目框架,本文以mvc项目为例,集成sentinel。

sentinel 控制台jar下载地址:Releases · alibaba/Sentinel · GitHub

启动控制台

java -Dserver.port=8080 -Dcsp.sentinel.dashboard.server=localhost:8080 -Dproject.name=sentinel-dashboard -jar sentinel-dashboard-1.8.5.jar

集成

maven配置 

项目maven依赖,sentinel-web-servlet是web项目与sentinel客户端的适配器项目,又引用了sentinel-core核心依赖,web-servlet主要提供一个filter,用来集成sentinel功能

sentinel-transport-simple-http实现与控制台通讯

		<dependency>
			<groupId>com.alibaba.csp</groupId>
			<artifactId>sentinel-web-servlet</artifactId>
			<version>1.8.5</version>
		</dependency>
		<dependency>
		    <groupId>com.alibaba.csp</groupId>
		    <artifactId>sentinel-transport-simple-http</artifactId>
		    <version>1.8.5</version>
		</dependency>

web.xml配置

通过配置web.xml 的filter开启sentinel支持

<filter>
	<filter-name>SentinelCommonFilter</filter-name>
	<filter-class>com.alibaba.csp.sentinel.adapter.servlet.CommonFilter</filter-class>
</filter>

<filter-mapping>
	<filter-name>SentinelCommonFilter</filter-name>
	<url-pattern>/*</url-pattern>
</filter-mapping>

 Sentinel配置

SentinelConfiguration配置类主要自定义一个UrlBlockHandler,用来处理异常,要确保这个配置类会被框架扫描到

import java.io.IOException;
import java.io.PrintWriter;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;

import com.alibaba.csp.sentinel.adapter.servlet.callback.UrlBlockHandler;
import com.alibaba.csp.sentinel.adapter.servlet.callback.WebCallbackManager;
import com.alibaba.csp.sentinel.adapter.servlet.config.WebServletConfig;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.csp.sentinel.util.StringUtil;

@Configuration
public class SentinelConfiguration {

	public UrlBlockHandler urlBlockHandler() {
		return new UrlBlockHandler() {

			@Override
			public void blocked(HttpServletRequest request, HttpServletResponse response, BlockException ex) throws IOException {
				if (ex instanceof FlowException) {
					// 触发接口限流
				} else if (ex instanceof DegradeException) {
					// 触发熔断降级
				} else if (ex instanceof SystemBlockException) {
					// 触发系统保护
				} else if (ex instanceof AuthorityException) {
					// 触发授权规则
				}
				String errMsg = "Blocked by Sentinel (flow limiting)!" + ex.getRule().getResource();
				StringBuffer url = request.getRequestURL();

				if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
					url.append("?").append(request.getQueryString());
				}

				if (StringUtil.isBlank(WebServletConfig.getBlockPage())) {
					response.setStatus(WebServletConfig.getBlockPageHttpStatus());
					PrintWriter out = response.getWriter();
					out.print("{\"code\":0,\"message\":\"" + errMsg + "\"}");
					out.flush();
					out.close();

				} else {
					String redirectUrl = WebServletConfig.getBlockPage() + "?http_referer=" + url.toString();
					// Redirect to the customized block page.
					response.sendRedirect(redirectUrl);
				}

			}

		};
	}

	@PostConstruct
	public void init() {
		WebCallbackManager.setUrlBlockHandler(urlBlockHandler());
	}
}

 启动

项目启动时加入 JVM 参数 -Dcsp.sentinel.dashboard.server=localhost:8080 指定控制台地址和端口

更多启动参数配置参考startup-configuration

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Cloud集成Sentinel非常简单,只需要添加SentinelSentinel Dashboard的依赖,然后在启动类上加上`@EnableCircuitBreaker`注解即可。下面我们来详细介绍一下整个过程。 1. 添加依赖 在pom.xml文件中添加如下依赖: ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-sentinel-datasource-nacos</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-nacos-discovery</artifactId> </dependency> ``` 其中,`spring-cloud-starter-alibaba-sentinel`是Sentinel的依赖,`spring-cloud-alibaba-sentinel-datasource-nacos`是Sentinel使用Nacos作为数据源的依赖,`spring-cloud-alibaba-nacos-discovery`是Nacos的依赖。 2. 启用Sentinel 在启动类上添加`@EnableCircuitBreaker`注解,启用Sentinel: ```java @SpringBootApplication @EnableDiscoveryClient @EnableCircuitBreaker public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 3. 配置Sentinel 在application.yml文件中添加如下配置: ```yaml spring: application: name: service-provider cloud: sentinel: transport: dashboard: localhost:8080 datasource: ds1: nacos: server-addr: localhost:8848 dataId: ${spring.application.name}-flow-rules groupId: DEFAULT_GROUP rule-type: flow ``` 其中,`transport.dashboard`配置Sentinel Dashboard的地址,`datasource`配置Sentinel使用Nacos作为数据源,`nacos.server-addr`配置Nacos的地址,`dataId`指定流控规则的Data ID,`groupId`指定Nacos的Group ID,`rule-type`指定规则类型。 4. 配置Sentinel Dashboard 下载Sentinel Dashboard,启动Sentinel Dashboard: ```bash java -jar sentinel-dashboard-1.8.1.jar ``` 访问http://localhost:8080即可查看Sentinel Dashboard。 5. 配置流控规则 在Nacos中添加流控规则。以service-provider服务为例,添加Data ID为service-provider-flow-rules的配置项,内容为: ```json [ { "resource": "hello", "count": 3.0, "grade": 1, "limitApp": "default", "strategy": 0, "controlBehavior": 0, "clusterMode": false } ] ``` 其中,`resource`指定资源名称,`count`指定阈值,`grade`指定流控模式,`limitApp`指定流控针对的调用来源,`strategy`指定流控策略,`controlBehavior`指定流控效果,`clusterMode`指定是否为集群模式。 6. 测试 启动服务提供者和服务消费者,访问http://localhost:8081/hello,即可触发流控规则,Sentinel会阻止请求并返回限流信息。 以上就是Spring Cloud集成Sentinel的整个过程,希望对你有所帮助。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值