一、使用
1.准备Eureka注册中心
2.准备一个微服务工程
3.搭建Gateway网关微服务
①在maven中添加如下依赖:
<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>
<version>3.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
</dependencies>
②编写配置文件application.yaml
server:
port: 8472
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
#开启从注册中心动态创建路由功能,利用微服务名进行路由
enabled: true
lower-case-service-id: true
routes:
- id: customer #路由的ID,没有固定规则但要求唯一,建议配合服务名
# lb:// + ${目标服务的spring.application.name的值}
uri: http://127.0.0.1:10001 #匹配后提供服务的路由地址
# 映射的路径 访问符合Path值的路径,转发到响应的uri对应服务下Path
predicates:
- Path=/zhang/** # 断言,路径相匹配的进行路由
- id: provider
# lb:// + ${目标服务的spring.application.name的值}
# uri: http://127.0.0.1:10002
uri: lb://PROVIDER
# 映射的路径 访问符合Path值的路径,转发到响应的uri对应服务下Path
predicates:
- Path=/zhang/**
#eureka相关配置
eureka:
instance:
lease-renewal-interval-in-seconds: 2
lease-expiration-duration-in-seconds: 10
# instance-id: cloud-gateway
client:
service-url:
defaultZone: http://127.0.0.1:10000/eureka
register-with-eureka: true
fetch-registry: true
# 自动发现工具的本地路由规则是:
# 请求路径 - http://网关IP:网关端口/微服务的服务名/要访问的具体地址
# gateway自动解析,把请求地址中的'微服务的服务名'截取,从Eureka Client发现的服务列表中查看,如果有同名服务,则开始转发。
③主启动类:
package com.example.gateWay;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class GateWayApplication {
public static void main(String[] args) {
SpringApplication.run(GateWayApplication.class, args);
}
}
④测试
http://ip:端口/服务名/接口名