Zuul网关使用步骤

Zuul网关使用步骤

1.在父项目中导入依赖SpringCloud管理

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

2.在网关微服务中导入Zuul以及Eureka。

说明:注册中心使用Eureka,若使用其他注册中心,则导入对应的注册中心依赖。

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
</dependencies>

3.在SpringBoot启动类中添加@EnableZuulProxy

4.在ymp文件中配置路由信息

以服务名称为goods示例:

zuul:
  routes:
    goods:
      path: /goods/**
      sensitiveHeaders: Authorization
      url: http://localhost:8081
  prefix: /api
  addProxyHeaders: false

更多配置请阅读官网文档:https://docs.spring.io/spring-cloud-netflix/docs/2.2.9.RELEASE/reference/html/#router-and-filter-zuul

5.在goods微服务添加/hello方法

@RestController
public class GoodsController {
    @GetMapping("/hello")
    public String hello() throws Exception{
        return "hello world";
    }
}

6.直接调用网关服务

http://网关IP:网关端口/api/hello

网关过滤器使用步骤

1.新建类继承ZuulFilter并实现对应方法。

@Component //必须放入Spring容器
public class AuthorizationFilter extends ZuulFilter {
    @Override
    public String filterType() {
        //过滤器类型,取值:pre、route、post、error
        return "pre";
    }
    @Override
    public int filterOrder() {
        //过滤器执行顺序,越小越优先执行
        return 0;
    }
    @Override
    public boolean shouldFilter() {
        //过滤器执行条件
        return true;
    }
    @Override
    public Object run() throws ZuulException {
        //过滤器执行逻辑
        return "test";
    }
}

2.在SpringBoot启动类加入注解@EnableZuulProxy

深入可阅读:Zuul网关源码解析

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值