Java教程

gateway

本文主要是介绍gateway,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

gateway

gateway描述

网关统一服务入口,主要用于身份认证、业务鉴权、防数据篡改、响应数据脱敏等

gateway实现

引入网关依赖

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

同时需要引入consul依赖以及健康检查依赖,去除web依赖

gateway路由配置,进行路由转发

  • 通过yml配置方式实现(推荐)
spring:
  application:
    name: illriver-bbs-gateway
  cloud:
    gateway:
      routes:
        - id: goods_route
          uri: http://localhost:31007
          predicates:
            - Path=/product/**

可以设置不同断言实现不同条件路由转发规则,详见官方文档:
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

  • 通过Configuration实现
@Configuration
public class RouteConfig {

    @Bean
    public RouteLocator routes(RouteLocatorBuilder builder){
        return builder.routes()
                .route("goods_route",r->r.path("/product/**").uri("http://localhost:31003"))
                .build();

    }
}
  • 开启暴露路由规则web站点(可选),开启后可以通过访问/actuator/gateway/routes查看已经定义的路由规则。
management:
  endpoints:
    web:
      exposure:
        include: "*" #暴露路由规则web站点 /actuator/gateway/routes

gateway配置服务名实现负载均衡,需要开启根据服务名动态获取路由地址。

spring:
  application:
    name: illriver-bbs-gateway
  cloud:
    gateway:
      routes:
        - id: goods_route
          uri: lb://illriver-bbs-goods
          predicates:
            - Path=/product/**
      discovery:
        locator:
          enabled: true #开启根据服务名动态获取路由地址

gateway配置filters实现请求过滤

spring:
  application:
    name: illriver-bbs-gateway
  cloud:
    gateway:
      routes:
        - id: goods_route
          uri: lb://illriver-bbs-goods
          predicates:
            - Path=/product/**
          filters:
            - AddRequestParameter=productId, 45
            - AddResponseHeader=color, blue

更多默认提供filer详见官方文档。

自定义全局filter

@Configuration
@Slf4j
public class CustomGlobalFiler implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        if (exchange.getRequest().getQueryParams().get("userName") != null){
            return chain.filter(exchange);
        }
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
这篇关于gateway的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!