四点要求都要满足吗?那只能配置 + 自己写代码才能实现了。
1、2两点写在配置(或者不写也可以,因为gateway会自动从服务发现组件获取微服务名称,自动转发,并且转发规则和你的需求一致。):
routes:
- id:
uri: https://user-center
predicates:
- Path=/user-center/**
filters:
# 配置成原始路径正则, 重写后的路径的正则
- RewritePath=/user-center/(?<segment>.*), /$\{segment}
- id:
uri: https://content-center
predicates:
- Path=/content-center/**
filters:
# 配置成原始路径正则, 重写后的路径的正则
- RewritePath=/user-center/(?<segment>.*), /$\{segment}
3、4两点写代码(Gateway支持使用编码方式实现转发,代码就是你平时用的Spring MVC或者Webflux。下面使用Webflux给出结果):
加依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-gateway-webflux</artifactId>
</dependency>
写代码:
@RestController
public class GatewayController {
@Autowired
private LoadBalancerClient loadBalancerClient;
@GetMapping("/user-center/users/list")
public Mono<ResponseEntity<String>> proxy(ProxyExchange<String> proxy) throws Exception {
// 判断chid=wx
// 用ribbon选出1个可用的实例,
ServiceInstance serviceInstance = loadBalancerClient.choose("user-center");
String uri = serviceInstance.getUri() + "/user/list";
System.out.println(uri);
return proxy
.uri(uri)
.get();
}
@GetMapping("/user-center/users/{id}")
public Mono<ResponseEntity<String>> proxy(ProxyExchange<String> proxy, @PathVariable Integer id) throws Exception {
// 用ribbon选出1个可用的实例,
ServiceInstance serviceInstance = loadBalancerClient.choose("user-center");
String uri = serviceInstance.getUri() + "/users/" + id;
System.out.println(uri);
return proxy
.uri(uri)
.get();
}
}
文档参考:https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.0.M2/reference/html/#_building_a_simple_gateway_using_spring_mvc_or_webflux