SpringCloud体系最常用网关组件为Zuul,网关Zuul通过配置文件约定的接口规则将请求转发到对应的微服务子项目去处理,这发挥的是其路由功能。除此之外,Zuul的路由功能可以处理前端的跨越问题。前端可以通过统一域名的请求,而实际的业务处理可能是在不同域名的服务下。Zuul网关还支持过滤器的处理,比如通过判断所有请求是否带临时票据token,token是否合法做权限拦截处理。
Zuul网关服务的使用需引入依赖
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
网关过滤器需继承ZuulFilter抽象类
@Component
public class PermissionFilter extends ZuulFilter{
private static Logger logger=LoggerFactory.getLogger(PermissionFilter.class);
@Override
public Object run() {
RequestContext ctx=RequestContext.getCurrentContext();
HttpServletRequest request=ctx.getRequest();
logger.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken=request.getParameter("token");
if(accessToken==null) {
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
try {
ctx.getResponse().getWriter().write("token is empty");
} catch (Exception e) {
// TODO: handle exception
}
return null;
}
return null;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public String filterType() {
return FilterConstants.PRE_TYPE;
}
}
启动类加**@EnableZuulProxy注解,通过@Bean**注册PermissionFilter
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
@Bean
public PermissionFilter registerPermissionFilter() {
return new PermissionFilter();
}
}
application.yml配置接口规则
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
server:
port: 8888
spring:
application:
name: service-gateway
zuul:
host:
socket-timeout-millis: 60000
connect-timeout-millis: 60000
routes:
api/user:
path: /api/user/**
serviceId: service-user
api/order:
path: /api/order/**
serviceId: service-order
ribbon:
ReadTimeout: 60000
ConnectTimeout: 60000
hystrix:
command:
default:
execution:
isolation:
thread:
timeoutInMilliseconds: 60000
比如/api/user开头的接口请求的是service-user的服务,api/order开头的接口请求的是service-order的服务