java的主流网关是SpringCloud那一套
一、zuul
二、gateway
gateway是zuul的后代版本,在zuul上做了一些附加修正,依赖包如下: spring-cloud-starter-gateway ,
项目中有个需求如下:
现公司app线上有一个论坛的功能,现在要做个"中转", 客户的需求直接发到网关, 然后网关将请求转发到真正的app后台,真正的后台是个php服务, 也就是访问路径要做如下调整: client ---> javap ---> php
我使getaway来解决了此问题,配置如下:
server:
port: 8087
spring:
application:
name: community-api
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: blog100
uri: http://192.168.1.10:8094
predicates:
- Path= /elearning/undoor/**
上面配置的含义是如果接受到的请求路径中包含/elearning/undoor 则转发到uri 中的地址,如果请求是http://xxx/elearning/undoor/getUsermsg?id=1&token=a3ff ,那么转发的路径将是http://192.168.1.19:809./elearning/undoor/getUsermsg?id=1&token=a3ff, 注意后面通配符的使用**
然后可能我们这无法满足我们的转发规则需求,比如说我们接受到的请求是/a/b,但是请求转发之后的请求得是/b才可以,那么我们可以自定义getaway过滤器来改变转发规则,代码如下
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
@Component
public class RequestPathFilter implements GlobalFilter, Ordered {
private static Logger log = LoggerFactory.getLogger(RequestPathFilter.class);
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
ServerHttpRequest request = exchange.getRequest();
String value = request.getPath().pathWithinApplication().value();
String replacePath = value.replace("/elearn", "");//此处可以配置
log.info("this is a pre filter");
ServerHttpRequest newRequest = request.mutate().path(replacePath).build();
return chain.filter(exchange.mutate().request(newRequest).build()).then(Mono.fromRunnable(() -> {
log.info("this is a post filter");
}));
}
@Override
public int getOrder() {
return 2;//注意此处的顺序,很有讲究,顺序写不对会直接报错
}
}
搭建过程当中也遇到很多坑, gateway支持基于Eureka注册中心的转发,此处locator:enabled:true代表不使用注册中心,直接用本地路径转发,getaway用的是netty,如果我们项目中用了spring-boot-starter-web会启动报错,我们可以去掉这个包,或者排除这个包,webflux与webmvc两人相见分外眼红
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</exclusion>
</exclusions>
</dependency>
当然可能你会说,我需要webmvc,我整个项目都是webmvc做的,你怎么能让我去掉,那么你可以另外建一个项目来使用spring getaway