0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例

  sentinel除了让服务提供方、消费方用之外,网关也能用它来限流。我们基于上次整的网关(参见0.9.0.RELEASE版本的spring cloud alibaba nacos+gateway网关实例)来看下怎么弄。只需动其中的两板斧:

  1、pom引入sentinel适配器:

        <dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
<version>1.6.0</version>
</dependency>

  2、新增一个配置类:

import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayRuleManager;
import com.alibaba.csp.sentinel.adapter.gateway.sc.SentinelGatewayFilter;
import com.alibaba.csp.sentinel.adapter.gateway.sc.exception.SentinelGatewayBlockExceptionHandler;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver; import javax.annotation.PostConstruct;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set; @Configuration
public class GatewayConfiguration { private final List<ViewResolver> viewResolvers;
private final ServerCodecConfigurer serverCodecConfigurer; public GatewayConfiguration(ObjectProvider<List<ViewResolver>> viewResolversProvider,
ServerCodecConfigurer serverCodecConfigurer) {
this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
this.serverCodecConfigurer = serverCodecConfigurer;
} /**
* 配置SentinelGatewayBlockExceptionHandler,限流后异常处理
*
* @return
*/
@Bean
@Order(Ordered.HIGHEST_PRECEDENCE)
public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() {
return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
} @Bean
@Order(-1)
public GlobalFilter sentinelGatewayFilter() {
return new SentinelGatewayFilter();
} @PostConstruct
public void doInit() {
initGatewayRules();
} /**
* 配置限流规则
*/
private void initGatewayRules() {
Set<GatewayFlowRule> rules = new HashSet<>();
rules.add(new GatewayFlowRule("lxytrans-consumer")
.setCount(4) // 限流阈值
.setIntervalSec(1) // 统计时间窗口,单位是秒,默认是 1 秒
);
rules.add(new GatewayFlowRule("lxytrans-provider")
.setCount(3)
.setIntervalSec(1)
);
GatewayRuleManager.loadRules(rules);
}
}

  打完收功。把网关重新跑起来,我们依然基于之前的服务提供方和消费方测试,消费方并发5个限1个,提供方并发5个限2个:

0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例

0.9.0.RELEASE版本的spring cloud alibaba sentinel+gateway网关实例

上一篇:手把手教你使用spring cloud+dotnet core搭建微服务架构:服务治理(-)


下一篇:CentOS6.5 mysql 5.5安装