Zuul的主要功能是路由和過濾器。路由功能是微服務的一部分,zuul實現了負載均衡。
1.1
新建模塊zuul
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>spring-cloud</artifactId>
<groupId>com.feng</groupId>
<version>0.0.1</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>zuul</artifactId>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-zuul</artifactId>
</dependency>
</dependencies>
</project>
1.2
application.yml:
spring:
application:
name: zuul
server:
port: 8020
eureka:
client:
service-url:
defaultZone: http://localhost:8010/eureka/
zuul:
routes:
api-a:
path: /service-a/**
serviceId: service-a
api-b:
path: /service-b/**
serviceId: service-b
sensitive-headers: #設置忽略的頭信息,設置為空能解決會話保持問題
add-host-header: true #設為true才能保持Host頭信息處理正確
上面配置說明把/service-a/開頭的所有請求都轉發給service-a服務執行,把/service-b/開頭的所有請求都轉發給service-b服務執行
1.3
ZuulApplication,使用EnableZuulProxy注解開啟zuul功能,並且注冊了一個zuul的過濾器
/**
* @author fengzp
* @date 17/4/27
* @email fengzp@gzyitop.com
* @company 廣州易站通計算機科技有限公司
*/
@SpringCloudApplication //這個注解整合了@SpringBootApplication、@EnableDiscoveryClient、@EnableCircuitBreake
@EnableZuulProxy
public class ZuulApplication {
public static void main(String[] args) {
SpringApplication.run(ZuulApplication.class, args);
}
@Bean
public MyZuulFilter getZuulFilter(){
return new MyZuulFilter();
}
}
MyZuulFilter,過濾器加了個判斷id是否為空,空則返回401錯誤碼
public class MyZuulFilter extends ZuulFilter {
private static Logger log = LoggerFactory.getLogger(MyZuulFilter.class);
/**
* 返回過濾器類型
* @return
* pre:可以在請求被路由之前調用
* routing:在路由請求時候被調用
* post:在routing和error過濾器之后被調用
* error:處理請求時發生錯誤時被調用
*/
@Override
public String filterType() {
return "pre";
}
/**
* 通過int值來定義過濾器的執行順序
*/
@Override
public int filterOrder() {
return 0;
}
/**
* 判斷過濾器是否執行
*/
@Override
public boolean shouldFilter() {
return true;
}
/**
* 過濾器的具體邏輯
* ctx.setSendZuulResponse(false)令zuul不允許請求,
* ctx.setResponseStatusCode(401)設置了其返回的錯誤碼
* ctx.setResponseBody(body)編輯返回body內容
* @return
*/
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
log.info(String.format("%s request to %s", request.getMethod(), request.getRequestURL().toString()));
Object accessToken = request.getParameter("id");
if(accessToken == null) {
log.warn("id is null");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
return null;
}
log.info("pass!");
return null;
}
}
1.4
把之前負載的service-b的spring.application.name改為service-b, 運行項目,分別打開http://localhost:8020/service-a/hi?id=zuul和http://localhost:8020/service-b/hi?id=zuul