Spring Cloud Alibaba之网关组件Gateway

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

  • 创建一个ServiceForGateway的SpringBoot项目,通过在控制类编写方法对外提供服务
java 复制代码
@RestController
public class Controller {
    @RequestMapping("/getAccount/{id}")
    public String getAccount(@PathVariable String id){
        return "Account Info, id is:"+id;
     }
}
  • 创建GatewayDemo项目,添加依赖到pom文件
XML 复制代码
 <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文件相关参数,实现简单路由转发
XML 复制代码
server:
  port: 8080
spring:
  cloud:
    gateway:
      routes:
        # 路由id,可随便命名,但要确保唯一
        - id: account_route
          # 匹配后的地址
          uri: http://localhost:8090/getAccount/{id}
          #断言
          predicates:
            # 包含/getAccount即需转发
            - Path=/getAccount/{id}
  • 修改application.yml文件,实现网关过滤
XML 复制代码
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
  • 自定义全局过滤器,设置过滤器动作:
java 复制代码
//自定义的全局性过滤器
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;
    }
}
  • 编写代码配置过滤器:
java 复制代码
@Configuration
public class ConfigMyGlobalFilter {
    @Bean
    public GlobalFilter configFilter() {
        return new MyGlobalFilter();
    }
}

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

  • 创建 GateWithNacos项目,添加pom依赖,引入nacos和GateWay依赖包
XML 复制代码
<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组件交互
java 复制代码
@EnableDiscoveryClient
@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args);
    }

}
  • 配置application.yml文件,实现GateWay整合Nacos效果
java 复制代码
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依赖,启动类同上一致
XML 复制代码
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>
  • 配置application.yml文件,实现灰度发布效果
XML 复制代码
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
相关推荐
我是一只代码狗8 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好21 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui26 分钟前
Centos项目部署之运行SpringBoot打包后的jar文件
linux·spring boot
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
zyxzyx6661 小时前
Flyway 介绍以及与 Spring Boot 集成指南
spring boot·笔记
一头生产的驴3 小时前
java整合itext pdf实现自定义PDF文件格式导出
java·spring boot·pdf·itextpdf
程序员张35 小时前
SpringBoot计时一次请求耗时
java·spring boot·后端
麦兜*12 小时前
Spring Boot启动优化7板斧(延迟初始化、组件扫描精准打击、JVM参数调优):砍掉70%启动时间的魔鬼实践
java·jvm·spring boot·后端·spring·spring cloud·系统架构
KK溜了溜了12 小时前
JAVA-springboot 整合Redis
java·spring boot·redis
大只鹅12 小时前
解决 Spring Boot 对 Elasticsearch 字段没有小驼峰映射的问题
spring boot·后端·elasticsearch