Spring gateway 入門之第一個Hello World

1、簡單介紹

項(xiàng)目地址: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);
    }
}

添加轉(zhuǎn)發(fā)邏輯

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

    /**
     * 測試房訪問豆瓣電影排行250
     * 訪問localhost:8080/a/top250轉(zhuǎn)到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轉(zhuǎn)到https://douban.uieee.com/v2/movie/top250

深度截圖_選擇區(qū)域_20200407234500.png

注意spring-boot與spring-cloud的版本存在兼容性問題,一定要注意版本的兼容性
具體兼容性可以參考這篇博客:
spring cloud 版本命名規(guī)范與spring boot的版本兼容性

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容