首页 > 技术文章 > Gateway 网关 之 整合使用

Alay 2021-08-17 00:36 原文

引入 SpringCloud Gateway 依赖 Gateway 不需要 Spring-boot-web 依赖,需要移除,否则无法启动,

注意版本的兼容问题,否则会报错  NotFindClass.................

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
    <version>${gateway.version}</version>
</dependency>

主启动类:

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

@EnableDiscoveryClient: 注解是使用了 Nacos 注册中心,可以忽略

配置文件方式配置:

动态路由配置:

默认情况下,Gateway 会根据注册中心中 注册的服务列表,以注册中心上微服务名称作为路径创建  动态路由进行转发,从而实现动态路由的功能

 


配置 Gateway 的路由有三种方式:

第一种: 配置文件方式配置 (简单配置可行,但不方便管理)

server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        # 路由ID,没有固定的规则要求,但要求唯一性,建议配合服务名
        - id: netty-socket
          # 匹配后提供服务的路由地址
          # uri: http://127.0.0.1:11000
      uri: lb://behelpful-xxx
predicates: # 断言,路径相匹配的才进行路由 - Path=/socket/** # 配置第二组(实际开发中使用 数据库+缓存实现动态路由) - id: xxxxx uri: xxxx predicates: xxx

第二种:编码注入Bean 方式配置,配置多个 @Bean 即可多路由 (不推荐)

@Configuration
public class GateWayConfig {
 
    @Bean
    public RouteLocator routeLocator(RouteLocatorBuilder routeBuilder) {
        RouteLocatorBuilder.Builder routes = routeBuilder.routes();
        /*
         * 配置路由映射 https://news.baidu.com/guonei,即访问本地的 localhost:9527/guonei,
         * 将会转发到 https://news.baidu.com/guonei
         */
        routes.route("routeId", r -> r.path("/guonei").uri("http://news.baidu.com/guonei"));
 
        return routes.build();
    }
}

第三种:数据库中进行配置管理 (强烈推荐)

1、数据库中创建与 Routes  (RouteDefinition 类)对应的存储字段即可,uri 是 URI 对象类型,配置文件中可以直接写字符串进行配置,

2、Spring 配置文件支持的字符串配置有:8 中基本数据类型、包装类型、String类型、URI 类型、Class 类型、Resource 类型

3、配置通过MySQL 与 Redis 缓存

 

请前往下一篇 进行源码分析讲解

>>>>>>>>>>>>>  https://www.cnblogs.com/Alay/p/15150600.html    <<<<<<<<<<<<<<<<

 

推荐阅读