Consul + zuul:api网关,提供路由转发功能之服务路由的默认配置

本文介绍了如何利用Consul动态注册服务,并在Zuul API网关中实现无需手动配置即可进行服务路由转发的功能。在Consul上注册多个服务后,Zuul可以通过其IP自动进行路由。文中详细展示了Zuul-gateway服务的配置,包括pom.xml、application.yml和Application.java文件,并提供了测试过程及遇到的一个错误的解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现功能:

每次往Consul注册新的服务,我们无需更改zuul的网关配置,就可以通过zuul服务的ip实现路由转发功能。

service service-id(instance-id) ip:port uri 通过路由的访问方式
test-config test-config 10.9.100.100:8801

/api/getCountNum

/api/hand/sites

/health

localhost:8804/test-config/api/getCountNum

localhost:8804/test-config/api/hand/sites

localhost:8804/test-config/health

test-config-service00 test-config-service00 10.9.100.100:8802

/api/getCountNum

/api/hand/sites

/health

localhost:8804/test-config-service00/api/getCountNum

localhost:8804/test-config-service00/api/hand/sites

localhost:8804/test-config-service00/health

test-config-service01 test-config-service01 10.9.100.100:8803

/api/getCountNum

/api/hand/sites

/health

localhost:8804/test-config-service01/api/getCountNum

localhost:8804/test-config-service01/api/hand/sites

localhost:8804/test-config-service01/health

路由服务

zuul-gateway-service

(在这里是

test-config-service02)

zuul-gateway-service localhost:8804 /health  

请求方式:

${ZuulServerIP}:${server.port}:/${新注册的Server}/[新服务的请求uri]

案例:

Consul上的三个服务:

Zuul-gateway服务:

注:应为是本地启动的zuul-gateway服务,名字为test-config-service02,端口号为8804 。另,Consul服务上有个红×的原因是因为我是本地电脑注册到Consul的,健康检测时获取的是我电脑PC的主机名,该主机名在Consul服务器上没有映射,故无法健康检测。但是服务不受影响。

test-config-service02服务的

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.3.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>zuul-gateway</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <name>springboot</name>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.RELEASE</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions><!-- 去掉springboot默认配置 -->
  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值