ITPub博客

首页 > IT职业 > IT生活 > SpringCloud Gateway入门

SpringCloud Gateway入门

IT生活 作者:d0e1f 时间:2021-09-09 09:47:45 0 删除 编辑

本文是介绍一下SpringCloud Gateway简单路由转发使用。

SpringCloud Gateway简介

SpringCloud是基于Spring Framework 5,Project Reactor和Spring Boot 2.0构建,目标是用于替代zuul。

官方文档

在官方文档上是这样介绍Spring Cloud Gateway的:

该项目提供了一个用于在Spring MVC之上构建API网关的库。Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到API,并为他们提供横切关注点。)

入门案例

接下来,介绍一下简单使用SpringCloud Gateway路由功能(本文使用SpringBoot2.0.0.RELEASE和SpringCloud Finchley.RC1版本)。

创建项目

新建一个项目,项目种加入SpringCloud Gateway依赖,完整pom如下:

4.0.0com.dalaoyangspringcloud_gateway0.0.1-SNAPSHOTjarspringcloud_gatewayspringcloud_gatewayorg.springframework.bootspring-boot-starter-parent2.0.0.RELEASE<!-- lookup parent from repository -->UTF-8UTF-81.8Finchley.RC1org.springframework.cloudspring-cloud-starter-gatewayorg.springframework.bootspring-boot-devtoolsruntimeorg.springframework.bootspring-boot-starter-testtestorg.springframework.cloudspring-cloud-dependencies${spring-cloud.version}pomimportorg.springframework.bootspring-boot-maven-plugin

SpringBoot主程序

在类中配置路由

主程序中加入了一种配置路由的方法,利用@Bean的方式自定义RouteLocator。

package com.dalaoyang;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;


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



    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/jianshu")
                        .uri("http://www.jianshu.com/u/128b6effde53")
                ).build();
    }

}

在配置文件中配置:

server:
  port: 8888

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
      - id: dalaoyang
        uri: http://www.dalaoyang.cn/
        predicates:
          - Path=/dalaoyang/**
      - id: juejin
        uri: https://juejin.im/user/5aa50b96f265da23866f836e
        predicates:
          - Path=/juejin/**

运行测试

到这里其实就配置完成了

源码下载:大老杨源码

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/4019/viewspace-2812499/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-10-17

  • 博文量
    75
  • 访问量
    552