SpringCloud网关(Zuul)搭建

概述

不同的微服务的端口是不一样的,一个用户对程序的端口号是不了解的,那么就无法去填写端口号,另一个即使知道端口号,每请求一次就需要填写一次,会降低用户的体验。为此可以配置网关,使用户使用统一端口就能够访问不一样微服务。

导包

在pom文件引入包的时候报了个错,Caused by: java.lang.ClassNotFoundException: com.netflix.zuul.monitoring.CounterFactory,因为项目的构建就导了个包,写了配置文件和配置了启动类,那么问题应该出现在pom文件或者配置文件中。配置文件是根据文档写的大概率是没有错的,那么顺手打开pom文件和官方文档对比了一下。找到了错误。

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 有错误的包,是不没有看出来 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-netflix-zuul</artifactId>
        </dependency>
    </dependencies>

正确的pom文件:

 <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <!-- 正确的包 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
    </dependencies>

文档地址:
https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.0.4.RELEASE/single/spring-cloud-netflix.html#_router_and_filter_zuul

在官方文档中有这样一段话:

8.1 How to Include Zuul
To include Zuul in your project, use the starter with 

注意这两句话:
a group ID of org.springframework.cloud and 
a artifact ID of spring-cloud-starter-netflix-zuul. 

See the Spring Cloud Project page for details on setting up your build system with the current Spring Cloud Release Train.

上面两句话提到了什么,对,groupId,artifactId,这表明什么,jar包地址,所以引入就好了。官方文档里没有给出具体的groupId与artifactId的具体引用方式,大概率是文档编写者不知道你的项目构建工具是什么,所以没有给出,你的项目如何导jar的根据它的提示导就好了。

我们继续

配置文件编写

解释一下为何jar包需要导入eureka,因为服务都是运行在eureka上的,具体可以参考如下这张图

在这里插入图片描述

zuul:
  routes:
    tensqu-user:
      path: /user/**
      serviceId: tensqu-user

eureka:
  client:
    service-url:
      defaultZone: http://127.0.0.1:6868/eureka/

server:
  port: 9011

spring:
  application:
    name: tensqu-manager

需要注意的一点是path指定的是拦截路径,在访问的时候记得加上controller路径

http://localhost:9011/user/tb-user/login

比如这样,user是拦截的路径,而tb-user/login才是zuul网关转发到的具体路径。

还需要注意的一点是,先启动eureka服务器项目,在启动微服务项目,比如user项目,最后启动网关

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值