- 创建gateway项目
- 连接Eureka基于服务发现自动创建路由规则
- 通过Actuator实现动态路由功能
创建项目并加入POM依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</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-gateway</artifactId>
</dependency>
<!-- 目前暂时用不上,后面进行限流时使用 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>
</dependency>
</dependencies>
创建application启动类
package com.icodingedu.springcloud;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayServerApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayServerApplication.class,args);
}
}
创建配置文件application
spring:
application:
name: gateway-server
cloud:
gateway:
discovery:
locator:
enabled: true
server:
port: 8080
eureka:
client:
serviceUrl:
defaultZone: http://localhost:10080/eureka/
management:
security:
enabled: false
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: always
启动eureka-server,启动feign-client(启动两个),gateway-server
可以通过 http://localhost:50080/actuator/gateway/routes 查看routes规则,打开后会发现根据eureka注册的两个服务节点:FEIGN-CLIENT、GATEWAY-SERVER
每个节点都有一个断言:predicate,一个过滤器:filters
现在就可以通过gateway做服务访问了:http://localhost:50080/FEIGN-CLIENT/sayhello 访问注册到eureka的服务了,并且如果该服务有多个节点就会轮询访问
注意这里的FEIGN-CLIENT目前必须时大写:如果是小写就404了,是按照eureka中的服务名进行访问的
如果网关访问不想用大写,可以修改yaml的配置支持小写访问
spring:
application:
name: gateway-server
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true #设置路由服务名可以全小写,但设置后就不支持大写了
# http://localhost:50080/feign-client/sayhello
Gateway支持创建动态路由规则
# POST 动态创建和修改路由规则
# 创建地址:http://localhost:8080/actuator/gateway/routes/myrouter
{
"predicates": [
{
"name": "Path",
"args": {
"_genkey_0": "/myrouter-path/**"
}
}
],
"filters": [
{
"name": "StripPrefix",
"args": {
"_genkey_0": "1"
}
}
],
"uri": "lb://FEIGN-CLIENT",
"order": 0
}
# 可以看下新的路由规则是否创建成功
# http://localhost:8080/actuator/gateway/routes
# 可以删除路由规则
# DELETE http://localhost:8080/actuator/gateway/routes/myrouter
# 可以访问我们创建的路由规则
# http://localhost:8080/myrouter-path/sayhello