1、Eureka注册中心
2、spring cloud gateway网关
Eureka不解释了。
1、启动Eureka注册中心。
2、new module
然后next,选择spring web、eureka discovery client、gateway
然后next,finish。
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.5.5</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.jw</groupId>
<artifactId>demo</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>2020.0.4</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
server:
port: 5000 # 服务端口
spring:
application:
name: gateway # 服务名称
cloud:
gateway:
discovery:
locator:
enabled: true
lower-case-service-id: true
routes:
- id: ums
uri: lb://UMS #eureka注册中心存在的服务名称
predicates:
- Path=/ums/** #路径配置
# filters:
# - StripPrefix=1 #忽略Path配置的个数,此处为1代表访问/api/customer/**时,会将api忽略,真实的访问地址为lb://admin-api/customer/**,如果为2,则为lb://admin-api/**
eureka:
client:
service-url:
defaultZone: http://localhost:8080/eureka # 指定服务注册中心
启动类
@SpringBootApplication
@EnableEurekaClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
启动Eureka、gateway、ums(我的子服务的名称)
访问:localhost:5000/ums/role/hello
ums controller
@RestController
@RequestMapping("role")
public class RoleController {
@Value("${server.port}")
String port;
@GetMapping("hello")
public String hello(){
return "hello,port:"+port;
}
}
可以看到已经通过网关成功调用。