Spring Cloud
  • Introduction
  • 网站架构演变过程
    • 微服务架构
  • Spring Cloud 简介
  • 服务的注册与发现
    • 其他知识
      • Zookeeper与Eureka区别
      • DiscoveryClient 与@EnableEurekaServer
    • Zookeeper
    • Consul
    • Eureka
      • 搭建注册中心
      • 高可用注册中心
      • Eureka详解
  • 服务消费者
    • RestTemplate
    • 服务消费者(rest+ribbon)
      • 此时架构
    • 服务消费者(Feign)
  • 断路器(Hystrix)
    • 基础入门
  • API Gateway(Zuul)
    • 基础入门
  • 分布式配置中心(Config)
    • 基础入门
  • SpringCloud Bus
  • 链路跟踪(Sleuth)
  • 数据流(Stream)
  • Dubbo
    • Untitled
Powered by GitBook
On this page
  • 创建service-zuul工程
  • applicaton类
  • application.yml配置
  • 服务过滤

Was this helpful?

  1. API Gateway(Zuul)

基础入门

创建service-zuul工程

其pom.xml文件如下:

   <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-eureka</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</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>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Dalston.RC1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

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

    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

applicaton类

在其入口applicaton类加上注解@EnableZuulProxy,开启zuul的功能:

@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ServiceZuulApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServiceZuulApplication.class, args);
	}
}

application.yml配置

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
     path: /api-a/**
     service-id: service-ribbon
    api-b:
     path: /api-b/**
     service-id: service-feign

首先指定服务注册中心的地址为http://localhost:8761/eureka/,服务的端口为8769,服务名为service-zuul;以/api-a/ 开头的请求都转发给service-ribbon服务;以/api-b/开头的请求都转发给service-feign服务;

hi forezp,i am from port:8762

服务过滤

zuul不仅只是路由,并且还能过滤,做一些安全验证。继续改造工程;

@Component
public class MyFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){}

            return null;
        }
        log.info("ok");
        return null;
    }
}

filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:

  • pre:路由之前

  • routing:路由之时

  • post: 路由之后

  • error:发送错误调用

  • filterOrder:过滤的顺序

  • shouldFilter:这里可以写逻辑判断,是否要过滤,本文true,永远过滤。

  • run:过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问。

token is empty
PreviousAPI Gateway(Zuul)Next分布式配置中心(Config)

Last updated 5 years ago

Was this helpful?

依次运行这五个工程;打开浏览器访问: ;浏览器显示:

这时访问: ;网页显示:

http://localhost:8769/api-a/hi?name=forezp
http://localhost:8769/api-a/hi?name=forezp