SpringCloud 学习笔记(五)—— 设置路由gateway

1、springcloud gateway介绍

Spring Cloud Gateway是由spring官方基于Spring5.0,Spring Boot2.0,Project Reactor等技术开发的网关。

2、环境搭建

2.1 依赖引入

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

2.2 application.yml

server:
    port: 8020
eureka:
    instance:
        prefer-ip-address: true
        ip-address: 127.0.0.1
    client:
        serviceUrl:
            defaultZone: ${EUREKA_HOST:127.0.0.1}:${EUREKA_PORT:8761}/eureka
spring:
  application:
      name: metis-gateway
  cloud:
    gateway:
      locator:
        enabled: true
      routes:
      - id: consumer #需要转发的服务id
        uri: lb://consumer 
        order: 1000
        predicates:
        - Path=/api/consumer/**
        filters:
        - StripPrefix=2
        #- PrefixPath=/contextPath   如果转发的服务带有contextPath ,加上此设置

routes:具体的路由信息,是一个数组,每一个路由基本包含部分:

id:这个路由的唯一id,不定义的话为一个uuid

uri:http请求为lb://前缀 + 服务id;ws请求为lb:ws://前缀 + 服务id;表示将请求负载到哪一个服务上

predicates:表示这个路由的请求匹配规则,只有符合这个规则的请求才会走这个路由。为一个数组,每个规则为并且的关系。

filters:请求转发前的filter,为一个数组。

order:这个路由的执行order。就是执行的拦截器的顺序

以上案例的运行过程为:访问localhost: 8020/api/consumer/get -> ${consumer.HOST}:${consumer.PORT}/get。

 

2.3 gateway入口

@SpringBootApplication
@EnableEurekaClient
public class GatewayApplication {

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

PS:

进阶文档https://blog.csdn.net/lz710117239/column/info/25719

猜你喜欢

转载自blog.csdn.net/AlphonesEric/article/details/89047452