一、环境准备
三个工程:
eureka-server
eureka-client
gateway
实验目的:通过网关访问对应的微服务:eureka-client。gateway和eureka-client注册到eureka-server上
二、eureka-server和eureka-client准备
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 #开启自动路由功能,根据服务名称自动创建routes
lower-case-service-id: true #识别小写服务名
定义一个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网关地址,可以正确请求到eureka-client的接口文章来源:https://www.toymoban.com/news/detail-695681.html
C:\Users\Administrator>curl -X GET http://localhost:8080/hello-service/gateway/hello
hello
四、总结
1、gateway通过服务发现,将请求/hello-service/gateway/hello转发到hello-service上
2、自定义一个GlobalFilter,用于去掉路径/gateway/路径
项目源码地址文章来源地址https://www.toymoban.com/news/detail-695681.html
到了这里,关于【深入解析spring cloud gateway】05 gateway请求转发实验的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!