目录
第一步:搭建Gateway服务,导入依赖
<dependencies>
<!--引入Eureka的客户端依赖,不需要引入spring-boot-start-web包,因为gateway有自己的启动包-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<!--引入gateway依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
第二步:创建启动类
@SpringBootApplication
// @EnableEurekaClient:是Eureka的注解,表示开启服务注册与发现
// 此注解也是表示开启服务注册与发现,但是此注解是任何注册中心都可以使用,也可以不写
//@EnableDiscoveryClient
public class GatewayApp {
public static void main(String[] args) {
SpringApplication.run(GatewayApp.class,args);
}
}
第三步:编写配置文件
server:
port: 2000
eureka:
client: # Eureka客户端配置,指向注册中心地址
serviceUrl:
defaultZone: http://localhost:1010/eureka/
instance:
prefer-ip-address: true # 开启使用IP地址进行注册
instance-id: gateway-server:2000 # 修改实例Id
spring:
application:
name: gateway-server
cloud:
gateway:
discovery:
locator:
enabled: false # 指定关闭通过服务名访问,默认就是关闭
lower-case-service-id: true # 服务名称小写
routes:
- id: application-user #指定当前路由配置的Id,需要唯一
# uri: http://127.0.0.1:8081 # 路由的目标地址 http就是固定地址
uri: lb://user-server #路由的目标地址 lb就是负载均衡,后面跟服务名称
predicates: # 路由断言,也就是判断请求是否符合路由规则的条件
- Path=/user/** # 这个是按照路径匹配,只要以/user/开头就符合要求