API网关Zuul——2 (使用Zuul构建API网关)


1.创建一个普通的SpringBoot项目,然后添加相关依赖 zuul 和 eureka

在这里插入图片描述

<!-- netflix开发 整合进spring cloud zuul 网关 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>

        <!-- eureka-client注册中心客户端 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>

2.在入口类添加 @EnableZuulProxy注解,开启Zuul的API网关服务功能

@SpringBootApplication

//开启Zuul的API网关服务功能
@EnableZuulProxy
public class Application {

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

}

3.在yml文件中配置路由规则

# 内置Tomcat端口
server:
  port: 8088

spring:
  application:
    name: 06-springcloud-api-gateway

#配置API网关到注册中心上。API网关也将作为一个服务注册到eureka-server上
eureka:
  client:
    service-url.defaultZone: http://eureka8083:8083/eureka/,http://eureka8084:8084/eureka/

# 配置路由规则 是我们自定义的api-wjm 在这个路径后匹配
# 可以随便定义 但是 1.一定是一样的 2.并且成对的
zuul:
  #prefix: /api   # 添加路由前缀
  routes:
    api-wjm:     # 路由的 id
      path: /api-wjm/**  #映射路径
      # 映射路径对应的实际的url地址
      #  访问路径规则 添加 映射路径的规则
      service-id: 05-SPRINGCLOUD-SERVICE-FEIGN  # 指定服务端的名称

以上配置,我们的路由规则就是匹配所有符合/api-wjm/**的请求,只要路径中带有/api-wjm/都将被转发到05-springcloud-service-feign服务上,至于05-springcloud-service-feign服务的地址到底是什么则由eureka-server注册中心去分析,我们只需要写上服务名即可。
以我们目前搭建的项目为例,请求http://localhost:8088/api-wjm/web/hello接口则相当于请求http://localhost:8087/web/hello

(05-springcloud-service-feign 服务的地址为http://localhost:8087/web/hello),路由规则中配置的 api-wjm是路由的名字,可以任意定义,但是一组path和serviceld 映射关系的路由名要相同。

如果以上测试成功,则表示们的API网关服务已经构建成功了,我们发送的符合路由规则的请求将自动被转发到相应的服务上去处理。

4.测试

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一只小小狗

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值