一、简介
在Springcloud中用zuul来实现网关功能,客户端的请求首先经过负载均衡Ngnix,再到达服务网关(zuul集群),然后再到具体的服务。Zuul的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如/api/server1转发到到server1服务。zuul默认和Ribbon结合实现了负载均衡的功能。
二、搭建
首先是POM文件
<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>
然后在applicaton类加上注解@EnableZuulProxy,开启zuul的功能
@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@RefreshScope
public class HfzZuulApplication {
public static void main(String[] args) {
SpringApplication.run(HfzZuulApplication.class, args);
}
}
yml配置如下
eureka:
client:
serviceUrl:
defaultZone: http://name:pass@IP/eureka/
instance:
ip-address: Ip地址
prefer-ip-address: true
server:
port: 8769
spring:
application:
name: service-zuul
sleuth:
sampler:
percentage: 1.0
cloud:
config:
discovery:
enabled: true
service-id: CONFIG-SERVER
label: master
profile: dev
name: hfz-zuul
username: name
password: pass
以上是在项目中配置的,为了使项目更加灵活,所以将路由的配置放在github上,这样可以动态读取
zuul:
routes:
api-a:
path: /api-a/**
serviceId: service-ribbon
api-b:
path: /api-b/**
serviceId: service-feign
以/api-a/ 开头的请求都转发给service-ribbon服务;以/api-b/开头的请求都转发给service-feign服务;
三、服务过滤
zuul不仅可以路由,并且还能通过过滤来拦截一些服务,可以用来做安全验证。
public class MyFilter extends ZuulFilter{
private static Logger log = LoggerFactory.getLogger(MyFilter.class);
@Override
public String filterType() {
return "pre";
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return true;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("token");
if(accessToken == null) {
log.warn("token is empty");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
try {
ctx.getResponse().getWriter().write("token is empty");
}catch (Exception e){}
return null;
}
log.info("ok");
return null;
}
}
filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
pre:路由之前
routing:路由之时
post: 路由之后
error:发送错误调用
filterOrder:过滤的顺序
shouldFilter:逻辑判断,是否要过滤
run:过滤器的具体逻辑控制
接下来就可以测试访问了。