介绍
api网关常见的两个用法如下
1.请求路由,方便运维人员
2.请求过滤,原来在各个服务中的鉴权逻辑可以统一放在网关
github地址:https://github.com/erlieStar/spring-cloud-learning
请求路由
示例项目:zuul-service(spring-cloud-zuul)
1.项目配置如下
pom.xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>
application.yaml
server:
port: 10001
spring:
application:
name: zuul-service
eureka:
client:
service-url:
defaultZone: http://localhost:7001/eureka
zuul:
routes:
api-ribbon:
path: /api-ribbon/**
serviceId: consumer-ribbon
api-feign:
path: /api-feign/**
serviceId: consumer-feign
2.启动类加上注解@EnableZuulProxy
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ZuulService {
public static void main(String[] args) {
SpringApplication.run(ZuulService.class);
}
}
启动eureka-service(spring-cloud-eureka)
启动producer-simple(spring-cloud-ribbon)
启动consumer-ribbon-hystrix(spring-cloud-hystrix)
启动consumer-feign-hystrix(spring-cloud-hystrix)
启动zuul-service(spring-cloud-zuul)
访问http://localhost:10001/api-ribbon/hello?name=ribbon显示
hello ribbon, I am from port: 8001
访问http://localhost:10001/api-feign/hello?name=feign显示
hello feign, I am from port: 8001
请求过滤
在zuul-service(spring-cloud-zuul)加入如下过滤器后重启
@Component
public class AccessFilter extends ZuulFilter {
public String filterType() {
return "pre";
}
public int filterOrder() {
return 0;
}
public boolean shouldFilter() {
return true;
}
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
Object accessToken = request.getParameter("accessToken");
if (accessToken == null) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
return null;
}
return null;
}
}
filterType,代表拦截器的类型,zuul中有4种类型的过滤器
类型 | 解释 |
---|---|
pre | 路由之前 |
routing | 路由时 |
post | 路由之后 |
error | 发送错误调用 |
filterOrder:过滤的顺序
shouldFilter:可以写逻辑,判断是否过滤。本文为true,永远过滤
run:过滤的具体逻辑,比如判断用户是否登陆,是否有相应的权限
访问http://localhost:10001/api-ribbon/hello?name=ribbon显示
accessToken is empty
访问http://localhost:10001/api-ribbon/hello?name=ribbon&accessToken=test显示
hello ribbon, I am from port: 8001