以 Eureka 作为服务注册中心,通过 gateway 网关转发所有服务
整体项目结构如下:
模块名 | 端口 | 功能 |
demo-eureka | 8760 | 注册中心 |
demo-gateway | 8761 | 网关服务 |
demo-server | 8762 | 服务提供者 |
1 注册中心
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>
application.yml
server:
port: 8760
spring:
application:
name: demo-eurka
eureka:
instance:
hostname: localhost
client:
registerWithEureka: false
fetchRegistry: false
serviceUrl:
defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/
EurekaApplication.java
@SpringBootApplication
@EnableEurekaServer
public class EurekaApplication {
public static void main(String[] args) {
SpringApplication.run(EurekaApplication.class, args);
}
}
2 网关服务
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
application.yml
server:
port: 8761
#微服务名称
spring:
application:
name: demo-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
lowerCaseServiceId: true
routes:
#路径匹配
- id: demo-server
uri: lb://demo-server
predicates:
- Path=/api/hi/**
filters:
- RewritePath=/api/(?<segment>.*), /$\{segment}
- AddRequestHeader=X-Request-Foo, Bar
eureka:
client:
service-url:
defaultZone: http://localhost:8760/eureka/
3 服务提供者
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
application.yml
server:
port: 8762
spring:
application:
name: demo-server
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8760/eureka/
TestController.java
@RestController
public class TestController {
@Value("${server.port}")
String port;
@GetMapping("/hi")
public String home(@RequestParam(value = "name", defaultValue = "zhangsan") String name) {
return "hi " + name + " ,i am from port:" + port;
}
}
依次启动注册中心,网关,服务提供者 三个服务
先通过服务直连,访问 http://localhost:8762/hi?name=bruce
再试通过网关转发,访问 http://localhost:8761/api/hi?name=bruce2