创建spring Cloud Gateway
一、准备pom.xml依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
<!-- spring cloud 结合 eureka 进行使用,所以要加入 eureka client 的依赖 -->
<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-contract-stub-runner</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-web</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
二、创建bootstrap.yml文件
spring:
application:
name: my-gateway
################################################################################
# 配置管理中心相关配
# 这里的值配置在环境变量中
# 如果项目没有使用统一的配置管理中心则不需要此段配置
################################################################################
cloud:
config:
profile: ${LZX_SPRING_PROFILE}
label: ${SPRING_LABEL}
uri: ${lzx_CONFIG_URL}
三、准备application.yml文件
###################################
#服务启动端口的配置
###################################
server:
port: ${server-port}
###############################################################
# eureka 的相关配置
# 如果不需要 结合eureka 使用,可以不要这一段配置
###############################################################
eureka:
client:
fetch-registry: true
register-with-eureka: ${register-with-eureka} # 是否注册到eureka
service-url:
defaultZone: ${service-url-defaultZone}
instance:
prefer-ip-address: false
hostname: ${instance-hostname}
spring:
cloud:
#################################
# gateway相关配置
#################################
gateway:
# 路由定义
routes:
- id: baidu
uri: https://www.baidu.com
predicates:
- Path=/baidu/**
filters:
- StripPrefix=1
- id: eureka-manage
uri: lb://eureka-manage
predicates:
- Path=/eureka-manage/**
filters:
- StripPrefix=1
四、修改启动类
package com.lzx.gateway.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
/**
* @SpringBootApplication springboot启动类注解
* @EnableEurekaClient 启用eureka客服端
*/
@SpringBootApplication
@EnableEurekaClient
public class MyGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(MyGatewayApplication.class, args);
}
}