SpringCloud Gateway使用实例

官网地址:https://spring.io/projects/spring-cloud-gateway

主要功能如下:

   路由功能、熔断器的集成、与服务发现组件的集成、限流、url重写等。

下面主要演示其与Nacos服务注册中心的集成,达到所有前端的访问先通过nginx反向代理到网关,然后通过网关从注册中心获取服务列表,然后以负载均衡的方式访问具体微服务的目的。图示如下:

 具体实现如下:

1. pom文件添加依赖

<dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

    </dependencies>

2. 启动类

/**
 * @author huxin
 * 创建时间:2021/4/30
 */
@SpringBootApplication
public class GatewayApplication {

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

}

3. 配置文件

spring:
  application:
    name: getway
  cloud:
    nacos:
      discovery:
        server-addr: "192.168.105.49:8848"
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      routes:
        - id: path_route
          uri: lb://common-sys
          predicates:
            - Path=/commons/**
          filters:
            - StripPrefix=1
server:
  port: 8888
logging:
  level:
    root: debug

配置说明:

  1. 断言:表示匹配请求的url path路径以/commons作为前缀的url会放行

   predicates:

          - Path=/commons/**

  2.过滤:将上面的url路径第一部分截取

   filters:

       - StripPrefix=1

3.路由:将上述断言放行的url请求过滤之后(即截取路径前缀的第一部分,然后用剩余部分和下面的url进行拼接产生路由地址,
lb:表示是负载均衡协议 , common-sys是发布的微服务的服务名
uri: lb://common-sys



 

   

原文地址:https://www.cnblogs.com/hzhuxin/p/14736998.html