gateway整合nacos配置文件及示例代码

Posted 零

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了gateway整合nacos配置文件及示例代码相关的知识,希望对你有一定的参考价值。

1.gateway整合nacos

添加pom文件

    <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.csp</groupId>
            <artifactId>sentinel-spring-cloud-gateway-adapter</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>
  • yml文件
server:
  port: 8180
spring:
  application:
    name: gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
    nacos:
      discovery:
        server-addr: localhost:8848
management:
  endpoints:
    web:
      exposure:
        include: "*"

2.gateway限流

  • 配置文件
package cn.qf.gateway.config;

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.callback.BlockRequestHandler;
import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
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.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.PostConstruct;
import java.util.*;

@Configuration
public class GatewayConfig 

    private final List<ViewResolver> viewResolvers;
    private final ServerCodecConfigurer serverCodecConfigurer;


    public GatewayConfig(ObjectProvider<List<ViewResolver>> viewResolversProvider,
                                ServerCodecConfigurer serverCodecConfigurer) 
        this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);
        this.serverCodecConfigurer = serverCodecConfigurer;
    

    //配置限流的异常处理
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public SentinelGatewayBlockExceptionHandler sentinelGatewayBlockExceptionHandler() 
        return new SentinelGatewayBlockExceptionHandler(viewResolvers, serverCodecConfigurer);
    

    //配置初始化的限流参数
    @PostConstruct
    public void initGatewayRules()
        Set<GatewayFlowRule> rules = new HashSet<>();
        rules.add(new GatewayFlowRule("provider_route").setCount(1).setIntervalSec(1));
        GatewayRuleManager.loadRules(rules);
    

    //初始化限流过滤器
    @Bean
    @Order(Ordered.HIGHEST_PRECEDENCE)
    public GlobalFilter sentinelGatewayFilter() 
        return new SentinelGatewayFilter();
    

    //自定义限流异常页面
    @PostConstruct
    public void initBlockHandlers()
        BlockRequestHandler blockRequestHandler = new BlockRequestHandler() 
            @Override
            public Mono<ServerResponse> handleRequest(ServerWebExchange serverWebExchange, Throwable throwable) 
                Map<String, Object> map = new HashMap();
                map.put("code",0);
                map.put("msg","被限流了");
                return ServerResponse.status(HttpStatus.OK)
                        .contentType(MediaType.APPLICATION_JSON)
                        .body(BodyInserters.fromObject(map));
            
        ;
        GatewayCallbackManager.setBlockHandler(blockRequestHandler);
    

3.gateway - nacos限流

  • 修改配置类
// nacos限流
//配置初始化的限流参数
@PostConstruct
public void initGatewayRules()
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("provider_api").setCount(1).setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);


//自定义API分组
@PostConstruct
private void initCustomizedApis()
    Set<ApiDefinition> definitions = new HashSet<>();
    ApiDefinition api= new ApiDefinition("provider_api")
        .setPredicateItems(new HashSet<ApiPredicateItem>()
            add(new ApiPathPredicateItem().setPattern("/provider/provider/port"));
        );
    definitions.add(api);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);

4.nacos自定义分组限流

  • 修改config
//配置初始化的限流参数
@PostConstruct
public void initGatewayRules()
    Set<GatewayFlowRule> rules = new HashSet<>();
    rules.add(new GatewayFlowRule("provider_api").setCount(1).setIntervalSec(1));
    rules.add(new GatewayFlowRule("provider_api1").setCount(1).setIntervalSec(1));
    rules.add(new GatewayFlowRule("provider_api2").setCount(1).setIntervalSec(1));
    GatewayRuleManager.loadRules(rules);


//自定义API分组
@PostConstruct
private void initCustomizedApis() 
    Set<ApiDefinition> definitions = new HashSet<>();
    ApiDefinition api = new ApiDefinition("provider_api")
        .setPredicateItems(new HashSet<ApiPredicateItem>() 
            add(new ApiPathPredicateItem().setPattern("/provider/provider/port"));
        );
    ApiDefinition api1 = new ApiDefinition("provider_api1")
        .setPredicateItems(new HashSet<ApiPredicateItem>() 
            add(new ApiPathPredicateItem().setPattern("/provider/provider/api1/**")
                .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
        );
    ApiDefinition api2 = new ApiDefinition("provider_api2")
        .setPredicateItems(new HashSet<ApiPredicateItem>() 
            add(new ApiPathPredicateItem().setPattern("/provider/provider/api2/demo1")
                .setMatchStrategy(SentinelGatewayConstants.URL_MATCH_STRATEGY_PREFIX));
        );

    definitions.add(api);
    definitions.add(api1);
    definitions.add(api2);
    GatewayApiDefinitionManager.loadApiDefinitions(definitions);

  • provider - controller
@GetMapping("/api1/demo1")
public String demo1()
    return "demo";


@GetMapping("/api1/demo2")
public String demo2()
    return "demo";


@GetMapping("/api2/demo1")
public String demo3()
    return "demo";


@GetMapping("/api2/demo2")
public String demo4()
    return "demo";

以上是关于gateway整合nacos配置文件及示例代码的主要内容,如果未能解决你的问题,请参考以下文章

云原生一篇打通微服务架构,nacos + gateway + Redis + MySQL + docker

云原生一篇打通微服务架构,nacos + gateway + Redis + MySQL + docker

十五.SpringCloudAlibaba极简入门-Gateway网关整合Nacos

nacos+gateway服务的配置

Nacos整合Spring Cloud Gateway组件

sentinel实战:springcloud gateway整合 sentinel nacos