IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> Java知识库 -> SpringCloud之Gateway网关路由转发route、断言predicates -> 正文阅读

[Java知识库]SpringCloud之Gateway网关路由转发route、断言predicates

1、gateway-ha 提供服务

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yzm</groupId>
        <artifactId>springcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>gateway-ha</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>gateway-ha</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
@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 提供服务

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yzm</groupId>
        <artifactId>springcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>gateway-hi</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>gateway-hi</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
@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 网关服务-路由转发

在这里插入图片描述

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <parent>
        <groupId>com.yzm</groupId>
        <artifactId>springcloud</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <artifactId>gateway-route</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>gateway-route</name>
    <description>Demo project for Spring Boot</description>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
@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/hello?name=yzm
http://localhost:8023/gateway-hi/hello?name=yzm
在这里插入图片描述
这是网关的默认路由规则

访问
http://localhost:8023/gw-a/hello?name=yzm
http://localhost:8023/gw-ha/hello?name=yzm
http://localhost:8023/ha/hello?name=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/hello?name=yzm
http://localhost:8023/hi/hello?name=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<String> 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<String> 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/query?number=333
在这里插入图片描述

  Java知识库 最新文章
计算距离春节还有多长时间
系统开发系列 之WebService(spring框架+ma
springBoot+Cache(自定义有效时间配置)
SpringBoot整合mybatis实现增删改查、分页查
spring教程
SpringBoot+Vue实现美食交流网站的设计与实
虚拟机内存结构以及虚拟机中销毁和新建对象
SpringMVC---原理
小李同学: Java如何按多个字段分组
打印票据--java
上一篇文章      下一篇文章      查看所有文章
加:2022-03-24 00:21:20  更:2022-03-24 00:23:30 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 6:42:52-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码