创建gateway子工程(配置文件方式)

介绍

本文搭建springcloud gateway,路由 ums 微服务

创建工程

在总工程下创建子工程

添加依赖

修改pom.xml文件

<dependencies>
    <!-- gateway依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
    </dependency>
    <dependency>
        <groupId>top.malaoshi</groupId>
        <artifactId>common</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!-- springboot依赖 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>

注意:不能加下面依赖,否则报错

<!-- springboot依赖,不写版本号表示继承父工程 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

创建application.yml

server:
  port: 9001

spring:
  application:
    name: gateway

  cloud:
    gateway:
      routes:    # 可以有多个
        - id: ums-getNoticeById    # 路由id必须唯一
          uri: http://localhost:8081   # 路由地址
          predicates:   # 支持多个断言
            - Path=/getNotice/**  # 断言,匹配路径才进行路由,**表示参数

        - id: ums-sendNotice
          uri: http://localhost:8081
          predicates:
            - Path=/follow/**

eureka:
  client:
    register-with-eureka: true  #将自己注册到eureka server
    fetchRegistry: true  #是否从eureka server 抓取已有的注册信息。单节点没用,集群必须设置true才能配合ribbon使用负载均衡
    service-url:
      #      defaultZone: http://localhost:7001/eureka
      defaultZone: http://192.168.0.200:7002/eureka,http://192.168.0.201:7001/eureka
  instance:
    instance-id: ${spring.cloud.client.ip-address}:${server.port}:@project.version@
    hostname: gateway-node1
#    prefer-ip-address: true

匹配断言,路由到ums的controller中

创建主启动类

package top.malaoshi;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;

@SpringBootApplication
@EnableEurekaClient
public class GatewayMain {
    public static void main(String[] args) {
        SpringApplication.run(GatewayMain.class,args);
    }
}

测试

访问 http://localhost:9001/getNotice/1 会路由到
http://localhost:8081/getNotice/1


原文出处:/show_1EF5ijQy1D8W.html