SpringCloud of Zuul Gateway Profile, filter configured to use the mapping vs

purpose:

  Zuul routing gateways Brief Introduction and basic use

  Zuul route-map configuration

  Zuul request filter configuration

 


 

Zuul Introduction and basic routing gateways use

Zuul profile:

  Zuul from the device and Netflix streaming website to all requests of the back-end application 前门. As the edge of the service application, Zuul designed to achieve dynamic routing, monitoring, resiliency and security. It may be necessary to route requests to the appropriate service a plurality of elastically contracted group.

 

Zuul official website address: https://github.com/Netflix/zuul/wiki

  Zuul use a range of different types of filters, these filters can help us to perform the following functions:

  • Authentication and Security - Authentication requires the identification of each resource and deny the request does not meet these requirements.
  • Insight and monitoring - tracking meaningful data and statistics on the edge, in order to provide an accurate view of production for us.
  • Dynamic routing - The need to dynamically route the request to a different back-end cluster.
  • Stress test - increasing traffic to measure the performance of the cluster.
  • Load Shedding - assigned capacity for each type of request and the deletion request exceeds the limit.
  • Static response process - build some response directly at the edge, instead of forwarding them to the cluster.
  • Multi-zone elasticity - area routes across AWS request, so that we use the ELB diversification, and our advantage closer to our members.

Basic use (routing configuration)

  We create a new project, microService-Zuul-3001

 

zuul eureka also registered with the service, the port 3001

We modifications Hosts, specifically for zuul put forward a local domain name mapping 

找到本机C:\Windows\System32\drivers\etc 地址下的host文件

加下:

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

在启动类:ZuulApplication_3001中加下@EnableZuulProxy注解

package com.ht.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 然后再启动下一个1004服务,以及 zuul网关服务

我们直接请求:http://localhost:1001/student/list 能获取到数据;

我们用 http://zuul.ht.com:3001/microservice-student/student/list  域名+端口+服务名称+请求地址 也能请求到数据;

我们的路由基本配置成功了


Zuul路由映射配置

 综上所述我们可以看到访问路径很容易就暴露了提供者的名字,安全性不高。

那么映射配置就是为了把唯一标识名隐藏更换,提高安全性

至于怎么配置见下:

在yml文件中添加一段zuul相关配置:

zuul:
  routes:
    studentServer.serviceId: microservice-student
    studentServer.path: /studentServer/**  #替代microservice-student项目名称
  ignored-services: "*"  #将原来的服务提供者唯一标识名禁用
  prefix: /ht   #类似于一个命名空间的前缀

 

开启Eureka,zuul网关,服务提供者fegin用来做测试:

这次访问换成配置过后修改过的域名访问,看能否成功。

配置完毕后可通过以下链接做测试

http://zuul.ht.com:3001/ht/studentServer/student/list

很明显成功了。


Zuul请求过滤配置

   由上我们晓得路由访问提高了安全性,其实zuul请求过滤也是为了提升性能和提高安全性;

  怎么说就是每个用户来访问微服务提供的接口时也是有限制的,微服务的接口不会全部开放但是路由就不一样了;

只要你访问它就会给你跳转到你想要的页面并且返回结果集,但是我们又不能给每个用户都设置一套身份验证吧,这样让代码显得很冗余还要提高复杂度;那么zuul请求过滤恰恰就解决了这个问题,将问题简单化也降低了代码的复杂度

从下图看的出来就是从API网关中实现对客户端请求的检验,只要你访问时API携带了用户相关信息那么就开放接口让你访问,若是没有携带反之关闭。

 那么下面就直接上代码:

 

 

先定义一个 AccessFilter类让它去接收上下文数据,继承zuul自带的ZuulFilter 类进行过滤

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

    /**
     * 过滤器的具体执行逻辑
     * run方法中获取了整个上下文
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();   //请求
        //接收到了一个token令牌,也就相当于接收用户信息一样,验证过滤要用的
        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,代表会再请求被路由之前执行
     * return "pre"是不能乱填的,要根据你继承的父类去选择,不单单这一种写法
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 过滤器的执行顺序
     */
    @Override
    public int filterOrder() {
        return 0;
    }

}

然后再新建一个ZuulConfig类去开启下 Filter配置:

package com.ht.microservicezuul3001.config;

import com.ht.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令牌去访问,可以看到是访问成功的

 反之,没有携带accessToken令牌去访问,访问失败。

 

 

 谢谢观看!

Guess you like

Origin www.cnblogs.com/huangting/p/11938153.html