栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringCloud之Gateway网关路由转发route、断言predicates

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringCloud之Gateway网关路由转发route、断言predicates

官方文档:https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

1、gateway-ha 提供服务



    4.0.0

    
        com.yzm
        springcloud
        0.0.1-SNAPSHOT
        ../pom.xml
    

    gateway-ha
    0.0.1-SNAPSHOT
    jar
    gateway-ha
    Demo project for Spring Boot

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class GatewayHaApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayHaApplication.class, args);
    }

}


server:
  port: 8021

spring:
  application:
    name: gateway-ha

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

# 启动熔断降级
feign:
  hystrix:
    enabled: true

Controller

@RestController
public class HaController {

    @Resource
    private HaFeign haFeign;

    @Value("${server.port}")
    private String port;

    @GetMapping("hello")
    public String hello(@RequestParam String name) {
        return "ha," + name + " ! " + "访问端口号:" + port;
    }

    @GetMapping("ha")
    public String ha(@RequestParam String name) {
        return haFeign.callHi(name);
    }
}

Service

@FeignClient(value = "gateway-hi", fallback = HaBack.class)
public interface HaFeign {

    @GetMapping("hello")
    String callHi(@RequestParam String name);
}


@Service
public class HaBack implements HaFeign {
    @Override
    public String callHi(String name) {
        return "gateway-hi 服务挂了";
    }
}
2、gateway-hi 提供服务



    4.0.0

    
        com.yzm
        springcloud
        0.0.1-SNAPSHOT
        ../pom.xml
    

    gateway-hi
    0.0.1-SNAPSHOT
    jar
    gateway-hi
    Demo project for Spring Boot

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-openfeign
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




@EnableFeignClients
@EnableEurekaClient
@SpringBootApplication
public class GatewayHiApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayHiApplication.class, args);
    }

}


server:
  port: 8022

spring:
  application:
    name: gateway-hi

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

feign:
  hystrix:
    enabled: true

Controller

@RestController
public class HiController {

    @Resource
    private HiFeign hiFeign;

    @Value("${server.port}")
    private String port;

    @GetMapping("hello")
    public String hello(@RequestParam String name) {
        return "hi," + name + " ! " + "访问端口号:" + port;
    }

    @GetMapping("hi")
    public String hi(@RequestParam String name) {
        return hiFeign.callHa(name);
    }

}

Service

@FeignClient(value = "gateway-ha", fallback = HiBack.class)
public interface HiFeign {

    @GetMapping("hello")
    String callHa(@RequestParam String name);
}


@Service
public class HiBack implements HiFeign {
    @Override
    public String callHa(String name) {
        return "gateway-ha 服务挂了";
    }
}
3、gateway-route 网关服务-路由转发



    4.0.0

    
        com.yzm
        springcloud
        0.0.1-SNAPSHOT
        ../pom.xml
    

    gateway-route
    0.0.1-SNAPSHOT
    jar
    gateway-route
    Demo project for Spring Boot

    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            org.springframework.cloud
            spring-cloud-starter-gateway
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    




@EnableEurekaClient
@SpringBootApplication
public class GatewayRouteApplication {

    public static void main(String[] args) {
        SpringApplication.run(GatewayRouteApplication.class, args);
    }
}

application.yml

server:
  port: 8023

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

spring:
  application:
    name: gateway-route
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          # serviceId是否小写
          lowerCaseServiceId: true

通过gateway实现路由转发有两种方式:

方式一:通过代码配置类实现
@Configuration
public class RouteConfig {

    @Bean
    public RouteLocator customerRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("to_gateway_ha", r -> r
                        .path("/ha/**")
                        .filters(f -> f.
                                stripPrefix(1)
                        )
                        .uri("http://localhost:8021/")
                )
                .route(r -> r
                        .path("/gw-ha/**", "/gw-a/**")
                        .filters(f -> f.
                                stripPrefix(1)
                        )
                        .uri("lb://gateway-ha")
                )
                .build();
    }

}

to_gateway_ha:路由ID,具备全局唯一性,可以不指定,缺省值UUID。
stripPrefix(1):去掉前缀,1表示个数,如路由前请求/a/b/c/d,去掉1个前缀后请求/b/c/d再转发
uri():可以指定详细地址(不能负载),也可以指定服务ID

依次启动eureka、ha、hi和route服务

访问
http://localhost:8023/gateway-ha/helloname=yzm
http://localhost:8023/gateway-hi/helloname=yzm

这是网关的默认路由规则

访问
http://localhost:8023/gw-a/helloname=yzm
http://localhost:8023/gw-ha/helloname=yzm
http://localhost:8023/ha/helloname=yzm

这是自定义的路由规则

方式二:通过配置文件yml实现
spring:
  application:
    name: gateway-route
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lowerCaseServiceId: true
      routes:
        - id: gw_ha
          uri: http://localhost:8021/
          predicates:
            - Path=/hhha/*
          filters:
            - StripPrefix=1
        - id: to_gateway_hi
          uri: lb://gateway-hi
          predicates:
            - Path=/hi/*
          filters:
            - StripPrefix=1

重启route服务
访问
http://localhost:8023/hhha/helloname=yzm
http://localhost:8023/hi/helloname=yzm

路由转发简单实现完成!

4、predicate 断言,即路由条件 Path 路径匹配
      routes:
        - id: path_route
          uri: lb://gateway-ha
          predicates:
            - Path=/ha
Method 请求方式
	routes:
        - id: method_route
          uri: lb://gateway-ha
          predicates:
            - Method=POST
Before 某时间点之前
	routes:
        - id: time_route
          uri: lb://gateway-ha
          predicates:
            - Before=2022-03-10T16:00:22.432+08:00[Asia/Shanghai] #在该时区前发生
After 某时间点之后
	routes:
        - id: time_route
          uri: lb://gateway-ha
          predicates:
            - After=2022-03-10T15:00:22.432+08:00[Asia/Shanghai] #在该时区后发生
Between 两时间点之间
	routes:
        - id: time_route
          uri: lb://gateway-ha
          predicates:
            - Between=2022-01-10T15:00:22.432+08:00[Asia/Shanghai],2022-10-10T16:00:22.432+08:00[Asia/Shanghai] #在两个时区内发生
Header 请求头
	routes:
        - id: header_route
          uri: lb://gateway-ha
          predicates:
            - Header=id,001 #携带header信息,相当于键值对,id为key,001为value
            - Header=id,d+ #携带header信息,相当于键值对,id为key,d+为value,是一个正则表达式,表达为正数
Cookie
	routes:
        - id: cookie_route
          uri: lb://gateway-ha
          predicates:
            - Cookie=username,yzm #携带cookies信息,相当于键值对,username为key,yzm为value
            - Cookie=username,d+ #携带cookies信息,相当于键值对,username为key,d+为value
Host 域名
	routes:
        - id: host_route
          uri: lb://gateway-ha
          predicates:
            - Host=**.baidu.com,**.another.com
Query 查询条件
	routes:
        - id: query_route
          uri: lb://gateway-ha
          predicates:
            - Query=number,123 #带查询条件,第一个是查询参数名称,第二个是可选的值,有参数名为number且值=123
            - Query=number #带查询条件,有参数名为number,值无所谓
            - Query=number,d+ 
RemoteAddr 远程地址
	routes:
        - id: raddr_route
          uri: lb://gateway-ha
          predicates:
            - RemoteAddr=192.168.1.1/24

server:
  port: 8024

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8088/eureka/

spring:
  application:
    name: gateway-predicate
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lowerCaseServiceId: true
      routes:
        #Path
        - id: path_route
          uri: lb://gateway-ha
          predicates:
            - Path=/ha
        #Method
        - id: method_route
          uri: lb://gateway-ha
          predicates:
            - Method=POST
        #Header
        - id: header_route
          uri: lb://gateway-ha
          predicates:
            - Header=id,d+ #携带header信息,相当于键值对,id为key,d+为value,是一个正则表达式,表达为正数
        #Cookie
        - id: cookie_route
          uri: lb://gateway-ha
          predicates:
            - Cookie=username,d+ #携带cookies信息,相当于键值对,username为key,d+为value
        #Host
        - id: host_route
          uri: lb://gateway-ha
          predicates:
            - Host=**.baidu.com,**.another.com
        #Query
        - id: query_route
          uri: lb://gateway-ha
          predicates:
            - Query=number,d+
        #Time
#        - id: time_route
#          uri: lb://gateway-ha
#          predicates:
#            - After=2020-10-30T15:00:22.432+08:00[Asia/Shanghai] #在该时区后发生
#            - Before=2020-10-30T16:00:22.432+08:00[Asia/Shanghai] #在该时区前发生
#            - Between=2020-10-30T15:00:22.432+08:00[Asia/Shanghai],2020-10-30T16:00:22.432+08:00[Asia/Shanghai] #在两个时区内发生

在gateway-ha服务中添加接口

    @PostMapping("post")
    public String post() {
        System.out.println("post");
        return "post";
    }

    @GetMapping("time")
    public String time() {
        System.out.println("time");
        return "time";
    }

    @GetMapping("/header")
    public String header(HttpServletRequest request) {
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            System.out.println(name + " = " + request.getHeader(name));
        }
        return "header";
    }

    @GetMapping("/cookie")
    public String cookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + " = " + cookie.getValue());
        }
        return "cookie";
    }

    @GetMapping("/host")
    public String host(HttpServletRequest request) {
        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            System.out.println(name + " = " + request.getHeader(name));
        }
        return "host";
    }

    @GetMapping("/query")
    public String query(Integer number) {
        System.out.println(number);
        return "query";
    }

依次启动eureka、ha、predicates服务

使用curl访问
curl -XPOST localhost:8024/post

curl localhost:8024/header -H “id:111”

curl localhost:8024/cookie --cookie “username=222”

curl localhost:8024/host -H “host:a.another.com”

curl localhost:8024/querynumber=333

相关链接

首页
上一篇:Dashboard服务监控
下一篇:Gateway过滤器Filter

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/974130.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号