Spring Cloud Alibaba之网关组件Gateway

时间:2024-07-05 07:06:02

实例演示1:在微服务体系中引入GateWay组件

  • 创建一个ServiceForGateway的SpringBoot项目,通过在控制类编写方法对外提供服务
@RestController
public class Controller {
    @RequestMapping("/getAccount/{id}")
    public String getAccount(@PathVariable String id){
        return "Account Info, id is:"+id;
     }
}
  • 创建GatewayDemo项目,添加依赖到pom文件
 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
 </dependencies>

ps:本次实验演练仅用到Gateway组件,所以在pom文件里面,就不需要通过dependencyManagement引入spring-cloud-alibaba-dependencies,在引入了gateway的依赖后也不需要再引入spring-boot-starter-web了。

  • 配置application.yml文件相关参数,实现简单路由转发
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        # 路由id,可随便命名,但要确保唯一
        - id: account_route
          # 匹配后的地址
          uri: http://localhost:8090/getAccount/{id}
          #断言
          predicates:
            # 包含/getAccount即需转发
            - Path=/getAccount/{id}
  • 修改application.yml文件,实现网关过滤
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        - id: StripPrefix_route
          # 匹配后的地址
          uri: http://localhost:8090
          predicates:
            - Path=/needRemoved/**
          filters:
            - StripPrefix=1
        - id: PrefixPath_route
          # 匹配后的地址
          uri: http://localhost:8090
          predicates:
            - Method=GET
          filters:
            - PrefixPath=/getAccount
  • 自定义全局过滤器,设置过滤器动作:
//自定义的全局性过滤器
public class MyGlobalFilter implements GlobalFilter, Ordered {
    //处理请求
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String urlPath = exchange.getRequest().getURI().getPath();
        System.out.println(urlPath);
        if(urlPath.indexOf("hacker") == -1){
            return chain.filter(exchange);
        }
        else{
            ServerHttpResponse res = exchange.getResponse();
            String msg = "fail for hacker";
            byte[] bits = msg.getBytes();
            DataBuffer buf = res.bufferFactory().wrap(bits);
            res.setStatusCode(HttpStatus.BAD_REQUEST);
            res.getHeaders().add("Content-Type", "text/plain");
            return res.writeWith(Mono.just(buf));
        }
    }
    @Override
    public int getOrder() {
        //Order值越小,优先级越高
        return 0;
    }
}
  • 编写代码配置过滤器:
@Configuration
public class ConfigMyGlobalFilter {
    @Bean
    public GlobalFilter configFilter() {
        return new MyGlobalFilter();
    }
}

实例演示2:GateWay整合Nacos,实现负载均衡

  • 创建 GateWithNacos项目,添加pom依赖,引入nacos和GateWay依赖包
<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
</dependencies>
  • 编写启动类,添加注解,说明项目与nacos组件交互
@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }

}
  • 配置application.yml文件,实现GateWay整合Nacos效果
server:
  port: 8080
spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      routes:
        - id: loadbalance_route
          uri: lb://ServiceProvider/
          predicates:
            - Path=/callServiceByRibbon

实例演示3:通过GateWay实现灰度发布

  • 创建GrayRelease项目,添加pom依赖,启动类同上一致
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>
  • 配置application.yml文件,实现灰度发布效果
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        - id: oldVersion_Route
          uri: http://localhost:3333/getAccount/{id}
          predicates:
            - Path=/getAccount/{id}
            - Weight=accountGroup, 9
        - id: newVersion_Route
          uri: http://localhost:5555/getAccount/{id}
          predicates:
            - Path=/getAccount/{id}
            - Weight=accountGroup, 1