SpringCloud之Zuul路由网关

本文详细介绍了如何配置Zuul作为微服务网关,包括整合Eureka、设置域名映射、添加过滤器功能及实现快速回退方法。通过实际项目演示,展示了如何使用Zuul进行请求路由和过滤,确保服务的稳定性和安全性。
摘要由CSDN通过智能技术生成

目录:

Zuul简介
配置Zuul网关

Zuul简介

Zuul包含了对请求的路由和过滤两个最主要的功能:
其中路由功能负责将外部请求转发到具体的微服务实例上,是实现外部访问统一入口的基础而过滤器功能则负责对请求的处理过程进行干预,是实现请求校验、服务聚合等功能的基础.
Zuul和Eureka进行整合,将Zuul自身注册为Eureka服务治理下的应用,同时从Eureka中获得其他微服务的消息,也即以后的访问微服务都是通过Zuul跳转后获得.

在这里插入图片描述

配置Zuul网关

我们这里演示隐藏接口,所以需要配置域名映射,一样的在我们系统的hosts文件加上
127.0.0.1 zuul.liuxia.com

然后我们新建一个项目microservice-zuul-3001

加上pom依赖

<?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.liuxia</groupId>
        <artifactId>t226_microservice</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>com.liuxia</groupId>
    <artifactId>microservice-zuul-3001</artifactId>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.javaxl</groupId>
            <artifactId>microservice-common</artifactId>
        </dependency>
        <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.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</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>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>
        <!--zuul网关-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>

        <!--ribbon相关依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-ribbon</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-config</artifactId>
        </dependency>

        <!--引入Feign依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-feign</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>


配置好application.yml

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.liuxia.com:2001/eureka/,http://eureka2002.liuxia.com:2002/eureka/,http://eureka2003.liuxia.com:2003/eureka/
info:
  groupId: com.liuxia.testSpringcloud
  artifactId: microservice-zuul-3001
  version: 1.0-SNAPSHOT
  userName: http://liuxia.com
  phone: 123456

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


zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**
  ignored-services: "*"
  prefix: /liuxia


然后在启动类加上注解

package com.liuxia.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);
    }

}


然后我们的3个注册中心,然后再启动一个1006查询数据

在这里插入图片描述

yml文件中添加以下配置:

zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**
  ignored-services: "*"
  prefix: /liuxia



然后添加一个filter类

AccessFilter

package com.liuxia.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;


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;
    }

}


添加配置文件ZullConfig

package com.liuxia.microservicezuul3001.config;

import com.liuxia.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();
    }
}



然后我们就必须携带accessToken才能访问我们的方法了

http://zuul.liuxia.com:3001/liuxia/studentServer/student/list?accessToken=ww

在这里插入图片描述
但是如果轮回到1005和1006端口我们用线程设置了等待时长,因为它们应该要进错误处理方法的,
所以我们想要让他进报错处理页面,也就是我们的快速回退方法,
我们有两种方法

1、配置Zuul的等待时长,这种方法是可以解决,但是它就不会进入快速回退方法了,而是会等待响应,哪怕超时响应也是响应成功

application.yml中配置


zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**
  ignored-services: "*"
  prefix: /liuxia
  host:
    connections: 500
    socket-timeout-millis: 100000
    connect-timeout-millis: 100000
  max:
    host:
      connections: 500


2、我们实现ZuulFallback接口,并把快速回退方法放入这个里面,它就能正常访问快速回退方法了

package com.liuxia.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即可。
     * <p>
     * 不过需要注意的时,这个回退只有服务掉线或者超时的情况下才会触发(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() {

            }
        };
    }
}


over…

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值