spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)

单点搭建

spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)_第1张图片


spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)_第2张图片

注意:蓝色虚线代表注册;绿色虚线代表调用、红色虚线代表心跳

1.     添加依赖

创建项目tcloud-gateway-zuulserver , pom.xml内容如下

<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.0modelVersion>

 

    <groupId> com.svw.tbox.tcloud.gatewaygroupId>

    <artifactId>tcloud-gateway-zuulserverartifactId>

    <version>0.0.1-SNAPSHOTversion>

    <name>tcloud-gateway-zuulservername>

    <url>http://maven.apache.orgurl>

 

    <parent>

        <groupId>org.springframework.bootgroupId>

        <artifactId>spring-boot-starter-parentartifactId>

        <version>1.4.3.RELEASEversion>

    parent>

 

    <properties>

        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>

        1.8

    properties>

 

    <dependencies>

        <dependency>

            <groupId>org.springframework.cloudgroupId>

            <artifactId>spring-cloud-starter-eurekaartifactId>

        dependency>

        <dependency>

            <groupId>org.springframework.cloudgroupId>

            <artifactId>spring-cloud-starter-zuulartifactId>

        dependency>

    dependencies>

   

    <dependencyManagement>

        <dependencies>

            <dependency>

                <groupId>org.springframework.cloudgroupId>

                <artifactId>spring-cloud-dependenciesartifactId>

                <version>Camden.SR4version>

                <type>pomtype>

                <scope>importscope>

            dependency>

        dependencies>

    dependencyManagement>

project>

2.     启动类开启zuul

package com.svw.tbox.tcloud.gateway.zuul;

 

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

 

@SpringBootApplication

@EnableZuulProxy

publicclass ZuulApplication {

    publicstaticvoid main(String[] args) {

        SpringApplication.run(ZuulApplication.class, args);

    }

}

3.     application.yml配置端口和注册到eurekaserver

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/

  instance:

    prefer-ip-address:true

4.     效果

启动tcloud-user-eurekaserver 2个实例进程

启动tcloud-user-provider 2个实例进程

启动tcloud-user-consumer 1个实例进程

启动tcloud-gateway-zuulserver

 

访问http://localhost:8200/tcloud-user-consumer/user/hrf ,

请求会被Zuul转发到http://localhost:9000/user/hrf

spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)_第3张图片

访问http://localhost:8200/tcloud-user-provider/getUser ,

请求会被Zuul转发到http://localhost:8000/getUser


spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)_第4张图片

ü  小结

前提条件:

Eureka Server注册的微服务的serviceId 在此处简称ms_id ;

Eureka Server注册的微服务的IP 在此处简称 ms_ip ;

Eureka Server注册的微服务的端口号 在此处简称 ms_port 。

Zuul转发规则是:

http://网关IP地址:网关端口号/ms_id/**

会被转发到 =

http:// ms_ip: ms_port/**


1.     高可用

原理:

Zuul 作为 Eureka Client ,创建多个ZuulEureka Client注册到Eureka Server集群

=>将多个Zuul节点注册到eureka sever

操作:

1.tcloud-gateway-zuulserver修改依赖pom.xml改成:

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/,http://localhost:8101/eureka/

  instance:

    prefer-ip-address:true

 

复制tcloud-gateway-zuulserver 项目 ,命名tcloud-gateway-zuulserver2修改 pom.xml

server:

  port: 8201

spring:

  application:

    name: tcloud-gateway-zuulserver

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/,http://localhost:8101/eureka/

  instance:

    prefer-ip-address:true

启动两个zuul server

=》重启provider和consumer微服务 ,运行效果和单节点一样

2.     容错:Zuul回退

如果微服务下线了,针对每个微服务,都需要回复一个中文提示,而不是报异常

1.     修改zuul server

1.      针对微服务tcloud-user-consumer添加回退类

package com.svw.tbox.tcloud.gateway.zuul.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;

import java.nio.charset.Charset;

 

@Component

public class ConsumerFallbackProvider implements ZuulFallbackProvider {

  @Override

  public String getRoute() {

    // 表明是为哪个微服务提供回退

    return "tcloud-user-consumer";

  }

 

  @Override

  public ClientHttpResponse fallbackResponse() {

    return new ClientHttpResponse() {

      @Override

      public HttpStatus getStatusCode() throws IOException {

        // fallback时的状态码

        return HttpStatus.OK;

      }

 

      @Override

      public int getRawStatusCode() throws IOException {

        // 数字类型的状态码,本例返回的其实就是200,详见HttpStatus

        return this.getStatusCode().value();

      }

 

      @Override

      public String getStatusText() throws IOException {

        // 状态文本,本例返回的其实就是OK,详见HttpStatus

        return this.getStatusCode().getReasonPhrase();

      }

 

      @Override

      public void close() {

      }

 

      @Override

      public InputStream getBody() throws IOException {

        // 响应体

        return new ByteArrayInputStream("tcloud-user-consumer微服务不可用,请稍后再试。".getBytes());

      }

 

      @Override

      public HttpHeaders getHeaders() {

        // headers设定

        HttpHeaders headers = new HttpHeaders();

        MediaType mt = new MediaType("application","json", Charset.forName("UTF-8"));

        headers.setContentType(mt);

        return headers;

      }

    };

  }

}

2.     效果

按照如下顺序启动:

=> tcloud-base-eurekaserver

=>tcloud-commons-configserver

=>tcloud-gateway-zuulserver

=>tcloud-user-provider

=>tcloud-user-consumer

关闭:tcloud-user-consumer

访问http://localhost:8200/tcloud-user-consumer/log-instance 出现如下效果:


1.     动态路由

参考3.9.4配置文件动态更新,将网关作为一个config client,注册到Eureka、config server ,连接到kafka。

1.     Pom.xml添加依赖

       <dependency>

           <groupId>org.springframework.cloudgroupId>

           <artifactId>spring-cloud-starter-eurekaartifactId>

       dependency>

       <dependency>

           <groupId>org.springframework.cloudgroupId>

           <artifactId>spring-cloud-starter-configartifactId>

       dependency>

        <dependency> 

            <groupId>org.springframework.cloudgroupId> 

            <artifactId>spring-cloud-starter-bus-kafkaartifactId> 

        dependency>

       <dependency>

           <groupId>org.springframework.bootgroupId>

           <artifactId>spring-boot-configuration-processorartifactId>

           <optional>trueoptional>

       dependency>

2.     添加配置参数

eureka:

  client:

    service-url:

      defaultZone: http://localhost:8100/eureka/

  instance:

    prefer-ip-address:true

server:

  port: 8200

spring:

  application:

    name: tcloud-gateway

  cloud:

    stream:

      default-binder: kafka

      kafka:

        binder:

          zk-nodes: localhost:2181

          brokers: localhost:9092

    config:

      failFast:true

      profile: local

      label: develop

      discovery:

        enabled:true

        serviceId: tcloud-commons-config-server

3.     启动类中注册自动配置bean @RefreshScope

@SpringBootApplication

@EnableZuulProxy

@EnableFeignClients

@EnableHystrix

publicclass GatewayApplication {

    publicstaticvoid main(String[] args) {

       SpringApplication.run(GatewayApplication.class, args);

    }

   

    @RefreshScope

    @ConfigurationProperties("zuul")

    public ZuulProperties zuulProperties() {

       returnnew ZuulProperties();

    }

}

4.     配置路由参数

zuul:

  add-host-header:true

  routes:

    tcloud-security-auth: /auth/**

    tcloud-commons-config-server: /config/**

tcloud-gateway: /gateway/**

management:

  security:

    enabled:false

 

5.     效果

1.      开启基础服务

开启zookeeper、kafka

2.      写一个微服务测试controller

tcloud-security-auth ,访问地址是:http://localhost:8200/auth/mqtt/profile

@RefreshScope

@RestController

@RequestMapping("/mqtt")

publicclass MqttController {

    @Value("${profile}")

    private String profile;

   

    @RequestMapping(value = "/profile", method = RequestMethod.GET)

    public String profile() {

       returnprofile;

    }

……

3.      修改路由地址

zuul:

  add-host-header:true

  routes:

    tcloud-security-auth: /check/**

    tcloud-commons-config-server: /config/**

tcloud-gateway: /gateway/**

management:

  security:

    enabled:false

4.      请求自动刷新参数

访问: http://localhost:8300/bus/refresh

5.      再次请求

访问:http://localhost:8200/check/mqtt/profile

spring cloud : 网关Zuul(过滤:安全、监控、限流、路由)_第5张图片



你可能感兴趣的:(spring,cloud)