Zuul路由网关简介及基本使用
Zuul API路由网关服务简介
如上图所示,这里的API 路由网关服务 由Zuul实现,主要就是对外提供服务接口的时候,起到了请求的路由和过滤作用,也因此能够隐藏内部服务的接口细节,从来有利于保护系统的安全性;
Zuul 路由配置
我们新建一个module microservice-zuul-3001
我们修改下Hosts,专门为zuul搞个本地域名映射
hosts文件 加下:
127.0.0.1 zuul.dengrenli.com
完整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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.dengrenli</groupId>
<artifactId>t226microservice</artifactId>
<version>1.0-SNAPSHOT</version>
</parent>
<artifactId>microservice-student-provider-hystrix</artifactId>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
</dependency>
<!-- 修改后立即生效,热部署 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>springloaded</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
<dependency>
<groupId>com.dengrenli</groupId>
<artifactId>microservice-common</artifactId>
<version>1.0-SNAPSHOT</version>
<scope>compile</scope>
</dependency>
<!--添加注册中心Eureka相关配置-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<!-- actuator监控引入 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--Hystrix相关依赖-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-hystrix</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
application.yml
这里我们的zuul也要像服务提供者一样,要注册到eureka服务里,端口3001;
server:
port: 3001
context-path: /
spring:
application:
name: microservice-zuul
eureka:
instance:
instance-id: microservice-zuul:3001
prefer-ip-address: true
client:
service-url:
defaultZone: http://eureka2001.dengrenli.com:2001/eureka/,http://eureka2002.dengrenli.com:2002/eureka/,http://eureka2003.dengrenli.com:2003/eureka/
info:
groupId: com.dengrenli.testSpringcloud
artifactId: microservice-zuul-3001
version: 1.0-SNAPSHOT
userName: http://dengrenli.com
phone: 18973509876
在启动类里面加下@EnableZuulProxy注解
package com.dengrenli.microservicezuul3001;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
@EnableZuulProxy
public class MicroserviceZuul3001Application {
public static void main(String[] args) {
SpringApplication.run(MicroserviceZuul3001Application.class, args);
}
}
我们测试下:
启动一个eureka, 然后再启动下一个1006服务,以及 zuul网关服务;
然后测试输入http://eureka2001.dengrenli.com:2001/测试一下是否正常运行
然后我们直接请求:http://localhost:1006/student/list 能获取到数据;
然后我们用 http://zuul.dengrenli.com:3001/microservice-student/student/list 域名+端口+服务名称+请求地址 也能请求到数据;
服务名称指的就是服务提供者对外的名字,如图所示:
说明我们的路由基本配置OK
zuul网关服务超时时间设置
Zuul作为服务网关为了保证自己不被服务拖垮,本身已经集成了Hystrix对路由转发进行隔离。 为了方便开发人员对服务短路进行自定义处理
ZuulFallbackProvider :Zuul 提供了 ZuulFallbackProvider 接口,开发人员可以通过实现该接口来完成自定义Hystrix Fallback
FallbackProvider :Spring Cloud Zuul 提供了 FallbackProvider替代了ZuulFallbackProvider接口。
代码如下:
package com.dengrenli.microservicezuul3001.fallback;
import org.springframework.cloud.netflix.zuul.filters.route.ZuulFallbackProvider;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
@Component
public class ZuulFallBack implements ZuulFallbackProvider {
@Override
public String getRoute() {
return "*";
}
/**
* 在给zuul整合回退功能时,只要类实现ZuulFallbackProvider接口,并且注册bean即可。
*
* 不过需要注意的时,这个回退只有服务掉线或者超时的情况下才会触发(Camden.SR4版本测试是这样),
* 如果服务程序出现异常,此回退程序是不能处理的,异常会直接返回给调用者,比如页面。
*
* @return
*/
@Override
public ClientHttpResponse fallbackResponse() {
return new ClientHttpResponse() {
@Override
public HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON_UTF8);//application/json;charset=UTF-8
return headers;
}
@Override
public InputStream getBody() throws IOException {
String msg = "服务繁忙,请稍后.....";
//new ByteArrayInputStream("{\"code\":-1,\"msg\":\"服务暂不可用\"}".getBytes(StandardCharsets.UTF_8))
return new ByteArrayInputStream(msg.getBytes());
}
@Override
public String getStatusText() throws IOException {
return HttpStatus.BAD_REQUEST.getReasonPhrase();//400
}
@Override
public HttpStatus getStatusCode() throws IOException {
return HttpStatus.BAD_REQUEST;
}
@Override
public int getRawStatusCode() throws IOException {
return HttpStatus.BAD_REQUEST.value();//"Bad Request"
}
@Override
public void close() {
}
};
}
}
然后加上在yml文件里面加上我们的超时设置,如图所示:
feign:
hystrix:
enabled: true
hystrix:
command:
default:
execution:
timeout:
enabled: true
isolation:
thread:
timeoutInMilliseconds: 15000
ribbon:
ReadTimeout: 6000
ConnectTimeout: 6000
MaxAutoRetries: 0
MaxAutoRetriesNextServer: 1
eureka:
enabled: true
然后我们访问http://zuul.dengrenli.com:3001/microservice-student/student/hystrix
我们更改它的时间为16000毫秒,也就是超过我在yml文件里面定义的15000毫秒的时间即可,再来测试,结果如图所示:
Zuul路由映射配置
上面是zuul的简单使用,从接口地址很轻易的就暴露了服务提供者的唯一标识名microservice-student;有安全风险,我们需要将其隐藏;
yml文件中添加以下配置:
zuul:
routes:
studentServer.serviceId: microservice-student
studentServer.path: /studentServer/**
ignored-services: "*"
prefix: /dengrenli
ignored-services的作用是将原来的服务提供者唯一标识名禁用;
Prefix的作用是给服务加前缀
配置完毕后我们来做测试,我们用之前的例子来测试,结果如图所示:
配置了之后,我们在用以前的路径去访问,它就会报错,如图所示:
Zuul请求过滤配置
比如我们登录某个系统 需要身份验证,用户名密码啥的,我们请求服务,也可以来设置身份验证,也就是过滤非法请求;Zuul通过ZuulFilter过滤器实现,一般具体实现的话 每次经过Zuul服务网关 我们都对带来的token进行有效性验证
我们先定义一个 AccessFilter类:
package com.dengrenli.microservicezuul3001.filter;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.log4j.Logger;
import javax.servlet.http.HttpServletRequest;
/**
* @author小科比
* @site www.dengrenli.com
* @company 科比公司
* @create 2019-12-13 0:31
*/
public class AccessFilter extends ZuulFilter {
Logger logger=Logger.getLogger(AccessFilter.class);
/**
* 判断该过滤器是否要被执行
*/
@Override
public boolean shouldFilter() {
return true;
}
/**
* 过滤器的具体执行逻辑
*/
@Override
public Object run() throws ZuulException {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
String parameter = request.getParameter("accessToken");
logger.info(request.getRequestURL().toString()+" 请求访问");
if(parameter==null){
logger.error("accessToken为空!");
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(401);
ctx.setResponseBody("{\"result\":\"accessToken is empty!\"}");
return null;
}
// token判断逻辑
logger.info(request.getRequestURL().toString()+" 请求成功");
return null;
}
/**
* 过滤器的类型 这里用pre,代表会再请求被路由之前执行
*/
@Override
public String filterType() {
return "pre";
}
/**
* 过滤器的执行顺序
*/
@Override
public int filterOrder() {
return 0;
}
}
然后再开启下 Filter配置:
package com.dengrenli.microservicezuul3001.config;
import com.dengrenli.microservicezuul3001.filter.AccessFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class ZuulConfig {
@Bean
public AccessFilter accessFilter(){
return new AccessFilter();
}
}
浏览器输入地址进行测试:
我们来试一下:
http://zuul.dengrenli.com:3001/dengrenli/studentServer/student/hystrix
结果如图所示:
http://zuul.dengrenli.com:3001/dengrenli/studentServer/student/hystrix?accessToken=1
结果如图所示:
谢谢大家,多多指教!!!