一、環(huán)境準(zhǔn)備
三個工程:
eureka-server
eureka-client
gateway
實驗?zāi)康模和ㄟ^網(wǎng)關(guān)訪問對應(yīng)的微服務(wù):eureka-client。gateway和eureka-client注冊到eureka-server上
二、eureka-server和eureka-client準(zhǔn)備
eureka-server略
eureka-client
application.yml
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8081
spring:
application:
name: hello-service
提供一個接口
@RestController
@Slf4j
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello"
}
}
三、gateway配置
pom.xml
<dependencies>
<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>
</dependencies>
application.yml
server:
port: 8080
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka
instance:
instance-id: gateway
prefer-ip-address: true
---
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
enabled: true #開啟自動路由功能,根據(jù)服務(wù)名稱自動創(chuàng)建routes
lower-case-service-id: true #識別小寫服務(wù)名
定義一個filter用于去掉路徑中的/gateway
@Configuration(proxyBeanMethods = false)
public class FilterConfig {
@Bean public RemovePathFilter removePathFilter() {
return new RemovePathFilter(); }
}
自定義一個GlobalFilter,用于去掉路徑/gateway/
@Slf4j
public class RemovePathFilter implements GlobalFilter, Ordered {
private static final String PREFIX = "/gateway/";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
log.info("刪除api前綴");
ServerHttpRequest req = exchange.getRequest();
addOriginalRequestUrl(exchange, req.getURI());
String path = req.getURI().getRawPath();
if (path.contains(PREFIX)) {
String newPath = path.replace(PREFIX, "/");
req = req.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, req.getURI());
}
return chain.filter(exchange.mutate().request(req).build());
}
@Override
public int getOrder() {
return 0;
}
}
請求示例
通過訪問 http://localhost:8080/hello-service/gateway/hello網(wǎng)關(guān)地址,可以正確請求到eureka-client的接口文章來源:http://www.zghlxwxcb.cn/news/detail-695681.html
C:\Users\Administrator>curl -X GET http://localhost:8080/hello-service/gateway/hello
hello
四、總結(jié)
1、gateway通過服務(wù)發(fā)現(xiàn),將請求/hello-service/gateway/hello轉(zhuǎn)發(fā)到hello-service上
2、自定義一個GlobalFilter,用于去掉路徑/gateway/路徑
項目源碼地址文章來源地址http://www.zghlxwxcb.cn/news/detail-695681.html
到了這里,關(guān)于【深入解析spring cloud gateway】05 gateway請求轉(zhuǎn)發(fā)實驗的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!