SpringCloud的网关框架zuul和nginx的功能类似,除了具备服务路由、均衡负载功能之外,它还具备了权限控制等功能,为微服务架构提供了前门保护的作用,同时将权限控制这些较重的非业务逻辑内容迁移到服务路由层面,使得服务集群主体能够具备更高的可复用性和可测试性。
注册中心使用eureka,Eureka的文章如下
SpringCloud之Eureka服务注册中心,服务注册和服务发现
下面搭建zuul微服务
在pom.xml中引入依赖
springboot的版本为1.5.15
springcloud的版本为Edgware.SR4
<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-actuator</artifactId>
</dependency>
在application.yml中配置zuul,把provider的微服务,加上前缀/provider,并忽略之前的访问url,并添加整体的url前缀/lhc
eureka:
client:
serviceUrl:
defaultZone: http://localhost:7001/eureka/
server:
port: 6001
spring:
application:
name: zuul
zuul:
#url 前缀
prefix: /lhc
#忽略之前的url访问路径
ignored-services: "*"
routes:
api-a:
path: /provider/**
serviceId: provider
在启动类中@EnableZuulProxy,搭建完毕
@EnableEurekaClient
@EnableZuulProxy
@SpringBootApplication
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
}
zuul还可以添加所有微服务的过滤器,这个就可以用来使用基于JWT的安全权限认证,自定义zuulFilter如下
@Component
public class MyZuulFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);
@Override
public String filterType() {
return null;
}
@Override
public int filterOrder() {
return 0;
}
@Override
public boolean shouldFilter() {
return false;
}
@Override
public Object run() throws ZuulException {
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;
}
}