本文主要是介绍SpringCloud之Zuul网关控制(Finchley版本),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Zuul 的主要功能是路由转发和过滤器。路由功能是微服务的一部分,比如 /api/user 转发到到 User 服务,/api/shop 转发到到 Shop 服务。Zuul 默认和 Ribbon 结合实现了负载均衡的功能。
新建Zuul项目
我们需要新建一个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"><modelVersion>4.0.0</modelVersion><parent><groupId>com.funtl</groupId><artifactId>hello-spring-cloud-dependencies</artifactId><version>1.0.0-SNAPSHOT</version><relativePath>../hello-spring-cloud-dependencies/pom.xml</relativePath></parent><artifactId>hello-spring-cloud-zuul</artifactId><packaging>jar</packaging><name>hello-spring-cloud-zuul</name><url>http://www.funtl.com</url><inceptionYear>2018-Now</inceptionYear><dependencies><!-- Spring Boot Begin --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-tomcat</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-actuator</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- Spring Boot End --><!-- Spring Cloud Begin --><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-eureka-server</artifactId></dependency><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-netflix-zuul</artifactId></dependency><!-- Spring Cloud End --></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><mainClass>com.funtl.hello.spring.cloud.zuul.ZuulApplication</mainClass></configuration></plugin></plugins></build>
</project>
主要是增加了zuul的依赖
在启动类中增加zuul注解
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class ZuulApplication {public static void main(String[] args) {SpringApplication.run(ZuulApplication.class, args);}
}
配置application.yml
spring:application:name: hello-spring-cloud-zuulserver:port: 8769eureka:client:serviceUrl:defaultZone: http://localhost:8761/eureka/zuul:routes:api-a:path: /api/a/**serviceId: hello-spring-cloud-web-admin-ribbonapi-b:path: /api/b/**serviceId: hello-spring-cloud-web-admin-feign
路由说明
以 /api/a 开头的请求都转发给 hello-spring-cloud-web-admin-ribbon 服务
以 /api/b 开头的请求都转发给 hello-spring-cloud-web-admin-feign 服务
此时在原有的服务注册中心,服务提供者,服务调用者ribbon和Feign的基础上,另外将zuul服务也启动,
此时我们会发现当访问http://localhost:8769/api/a/hi?message=HelloZuul和http://localhost:8769/api/b/hi?message=HelloZuul时在不同的ribbon和feign服务中均发生了调用
配置网关路由失败时的回调
当我们的某一个服务崩溃时,网关要负责进行回调,此时需要添加回调类
@Component
public class WebAdminFeignFallbackProvider implements FallbackProvider {@Overridepublic String getRoute() {// ServiceId,如果需要所有调用都支持回退,则 return "*" 或 return null,单个支持回调只需要加入application.name 例如 return "hello-spring-cloud-web-admin-feign"return "*";}/*** 如果请求服务失败,则返回指定的信息给调用者* @param route* @param cause* @return*/@Overridepublic ClientHttpResponse fallbackResponse(String route, Throwable cause) {return new ClientHttpResponse() {/*** 网关向 api 服务请求失败了,但是消费者客户端向网关发起的请求是成功的,* 不应该把 api 的 404,500 等问题抛给客户端* 网关和 api 服务集群对于客户端来说是黑盒* @return* @throws IOException*/@Overridepublic HttpStatus getStatusCode() throws IOException {return HttpStatus.OK;}@Overridepublic int getRawStatusCode() throws IOException {return HttpStatus.OK.value();}@Overridepublic String getStatusText() throws IOException {return HttpStatus.OK.getReasonPhrase();}@Overridepublic void close() {}@Overridepublic InputStream getBody() throws IOException {ObjectMapper objectMapper = new ObjectMapper();Map<String, Object> map = new HashMap<>();map.put("status", 200);map.put("message", "无法连接,请检查您的网络");return new ByteArrayInputStream(objectMapper.writeValueAsString(map).getBytes("UTF-8"));}@Overridepublic HttpHeaders getHeaders() {HttpHeaders headers = new HttpHeaders();// 和 getBody 中的内容编码一致headers.setContentType(MediaType.APPLICATION_JSON_UTF8);return headers;}};}
此时如果关闭ribbon服务的话,那么访问链接会显示,会出现我们预先设置好的错误信息
增加路由过滤功能
路由过滤功能需要实现ZuulFilter,我们进行如下实现
@Component
public class LoginFilter extends ZuulFilter {private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);/*** 配置过滤类型,有四种不同生命周期的过滤器类型* 1. pre:路由之前* 2. routing:路由之时* 3. post:路由之后* 4. error:发送错误调用* @return*/@Overridepublic String filterType() {return "pre";}/*** 配置过滤的顺序* @return*/@Overridepublic int filterOrder() {return 0;}/*** 配置是否需要过滤:true/需要,false/不需要* @return*/@Overridepublic boolean shouldFilter() {return true;}/*** 过滤器的具体业务代码* @return* @throws ZuulException*/@Overridepublic Object run() throws ZuulException {RequestContext context = RequestContext.getCurrentContext();HttpServletRequest request = context.getRequest();logger.info("{} >>> {}", request.getMethod(), request.getRequestURL().toString());String token = request.getParameter("token");if (token == null) {logger.warn("Token is empty");context.setSendZuulResponse(false);context.setResponseStatusCode(401);try {context.getResponse().getWriter().write("Token is empty");} catch (IOException e) {}} else {logger.info("OK");}return null;}
}
几个参数的具体含义
filterType
返回一个字符串代表过滤器的类型,在 Zuul 中定义了四种不同生命周期的过滤器类型
pre:路由之前
routing:路由之时
post: 路由之后
error:发送错误调用
filterOrder
过滤的顺序
shouldFilter
是否需要过滤,这里是 true,需要过滤
run
过滤器的具体业务代码
此时我们访问链接
http://localhost:8769/api/b/hi?message=HelloZuul&token=123显示正常信息,我们访问http://localhost:8769/api/b/hi?message=HelloZuul会出现Token is empty的错误提示
这篇关于SpringCloud之Zuul网关控制(Finchley版本)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!