Spring gateway 入门之第一个Hello World

1、简单介绍

项目地址:https://github.com/spring-cloud/spring-cloud-gateway.git

2、hello world示例源码

https://github.com/iceqing/spring-cloud-gateway-example/tree/master/spring-cloud-gateway-helloworld

添加启动类

@SpringBootApplication
public class Application {

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

添加转发逻辑

/**
 * 示例route
 */
@Slf4j
@Configuration
public class RouteConfiguration {

    /**
     * 测试房访问豆瓣电影排行250
     * 访问localhost:8080/a/top250转到https://douban.uieee.com/v2/movie/top250
     */
    @Bean
    public RouteLocator helloRoute(RouteLocatorBuilder builder) {
        log.info("helloRoute, build RouteLocator bean");

        return builder.routes()
                .route(r -> r.path("/api/**")
                        .filters(f -> f.stripPrefix(1)
                                .prefixPath("/v2/movie/")
                        )
                        .uri("https://douban.uieee.com")
                )
                .build();
    }
}

添加spring-cloud-gateway依赖

buildscript {
    ext {
        springBootVersion = '2.1.13.RELEASE'
        springCloudVersion = 'Greenwich.SR5'
    }

    repositories {
        maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
    }

    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

group 'me.ice.springboot'
version '1.0-SNAPSHOT'

apply plugin: 'java'
apply plugin: 'org.springframework.boot'
apply plugin: "io.spring.dependency-management"

repositories {
    mavenLocal()
    maven { url 'http://maven.aliyun.com/nexus/content/groups/public/' }
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    compile group: 'org.projectlombok', name: 'lombok', version: '1.18.4'
    annotationProcessor "org.projectlombok:lombok:1.18.4"

    implementation("org.springframework.cloud:spring-cloud-starter-gateway")
    testCompile("org.springframework.boot:spring-boot-starter-test")
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

测试

测试房访问豆瓣电影排行250

访问localhost:8080/a/top250转到https://douban.uieee.com/v2/movie/top250

深度截图_选择区域_20200407234500.png

注意spring-boot与spring-cloud的版本存在兼容性问题,一定要注意版本的兼容性
具体兼容性可以参考这篇博客:
spring cloud 版本命名规范与spring boot的版本兼容性

你可能感兴趣的:(Spring gateway 入门之第一个Hello World)