步骤:
- 建项目
- 给主启动类添加Eureka的注解:@EnableEurekaClient
- 添加并配置application.yml
第一步:新建gateway的项目:gateway-8205
需要用到的组件:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
第二步:给主启动类添加Eureka的注解:@EnableEurekaClient
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
@SpringBootApplication
@EnableEurekaClient
public class Gateway8205Application {
public static void main(String[] args) {
SpringApplication.run(Gateway8205Application.class, args);
}
}
第三步:添加并配置 application.yml
server:
port: 8205
spring:
application:
name: api-gateway
cloud:
# 网关配置
gateway:
# 配置路由规则
routes:
# 路由ID(一个路由配置一个ID)
- id: product-service
# 通过注册中心来查找服务(lb代表从注册中心获取服务,并且负载均衡)
uri: lb://PRODUCT-SERVICE
# 匹配到的以/product开头的路径都转发到product的服务,相当于访问 lb://PRODUCT-SERVICE/**
predicates:
- Path=/product/**
# 去掉匹配到的路径的第一段
filters:
- StripPrefix=1
# 把网关注册到注册中心(从注册中心获取服务地址)
eureka:
instance:
instance_id: gateway-${server.port}
prefer-ip-address: true
client:
service-url:
defaultZone: http://localhost:8201/eureka
启动,访问:http://localhost:8205/product/index
成功。