微服务之四:Zuul

一: 概述

  • 在之前的例子中,都是通过浏览器或者HttpClient模拟浏览器向服务发送请求
  • 在实际环境中,一个集群肯定是多个服务提供者的,如何统一起来对外使用呢?
  • 外部服务不能知道每一个服务提供者在哪, 只需要记住统一提供的出口遍可以

1.1 Zuul介绍

Zuul将外部的请求过程划分为不同的阶段,每个阶段都提供一系列过滤器,这些过滤器有以下的功能

  • 身份验证和安全性:
  • 观察和监控,
  • 动态路由:将请求动态路由到不同的服务集群
  • 负载分配:设置每种请求的处理能力,删除那些超出限制的请求
  • 静态响应处理:
  • 路由的多样化:

二:web项目中使用Zuul

2.1 依赖项(myServer)

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>1.5.4.RELEASE</version>
</dependency>

2.2 启动类(myServer)

package com.atm.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@SpringBootApplication
@RestController
public class ZuulServerApp {

    // 默认使用8080端口
    public static void main(String[] args) {
        SpringApplication.run(ZuulServerApp.class, args);
    }

    @RequestMapping(value = "/hello/{name}", method = RequestMethod.GET)
    public String hello(@PathVariable String name) {
        return "hello, " + name;
    }
}

2.3 调用端依赖(router)

<!-- Zuul -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-zuul</artifactId>
        </dependency>
        <!-- HttpClient -->
        <!-- 为什么还需要引入HttpClient?因为Zuul底层是使用httpclient来请求发送的 -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>

2.4 配置文件(router)

server:
  port: 8085
##Zuul配置转发规则
zuul:
  routes:
  ##路由名称
    myServer:
      url: http://localhost:8080

2.5 启动类(router)

package com.atm.cloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;

@SpringBootApplication
@EnableZuulProxy//打开Zuul客户端功能,开启Zuul代理
public class ZuulRouterApp {

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

2.6 测试

  • 浏览器访问http://127.0.0.1:8085/myServer/hello/aitemi
  • 实际上转发到http://127.0.0.1:8080/hello/aitemi

三: 微服务集群中使用Zuul

原来的Spring Cloud 集成结构
在这里插入图片描述
加入服务网关Zuul之后
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值