Spring Cloud Gateway 基礎使用

Spring Cloud Gateway是Spring Cloud官方推出的第二代網(wǎng)關框架捺疼,取代Zuul網(wǎng)關女揭。網(wǎng)關作為流量的,在微服務系統(tǒng)中有著非常作用溉仑,網(wǎng)關常見的功能有路由轉(zhuǎn)發(fā)、權限校驗兽愤、限流控制等作用彼念。

源碼

項目結構

項目 端口 描述
eureka-server 8761 服務的注冊與發(fā)現(xiàn)
service-one 8081 服務
gateway-client 8080 網(wǎng)關 gateway

eureka-server

eureka-server項目非常簡單 引入

<dependency>
         <groupId>org.springframework.cloud</groupId>
         <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
</dependency>

啟動類里面

@EnableEurekaServer
@SpringBootApplication
public class EurekaServerApplication {

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

配置文件

spring:
  application:
    name: eureka-server

server:
  port: 8761
eureka:
  instance:
    hostname: localhostname
  client:
    fetch-registry: false
    register-with-eureka: false
    service-url:
      defaultZone: http://localhost:8761/eureka/

service-one 項目

搭建非常簡單,添加依賴

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

啟動類里面

@EnableEurekaClient
@SpringBootApplication
public class ServiceOneApplication {

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

配置文件

spring:
  application:
    name: service-one
server:
  port: 8081

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/

創(chuàng)建類控制器 UserController浅萧,http://localhost:8081/user/who

@RequestMapping("/user")
@RestController
public class UserController {

    @RequestMapping("who")
    public String who() {
        return "my name is liangwang";
    }
}

創(chuàng)建類控制器OrderController逐沙,http://localhost:8081/order/info

@RequestMapping("/order")
@RestController
public class OrderController {

    @RequestMapping("/info")
    public String orderInfo() {
        return "order info date : " + new Date().toString();
    }
}

gateway-client項目

使用的是Finchley.SR2版本的,其中已經(jīng)包含了 spring-boot-starter-webflux
添加依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>

使用RouteLocator的Bean進行路由轉(zhuǎn)發(fā)洼畅,將請求進行處理吩案,最后轉(zhuǎn)發(fā)到目標的下游服務

@SpringBootApplication
public class GatewayClientApplication {

    @Value("${test.uri}")
    private String uri;

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                //basic proxy
                .route(r -> r.path("/order/**")
                        .uri(uri)
                ).build();
    }

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

上面的代碼里是在訪問http://localhost:8080/order/的時候,網(wǎng)關轉(zhuǎn)發(fā)到http://service-one:8081/order/帝簇,service-one服務在eureka中有注冊徘郭,最終是對應服務的ip:port

使用配置文件
application.yml

test:
  uri: lb://service-one
spring:
  application:
    name: gateway-client
  cloud:
    gateway:
      routes:
      - id: route_service_one
        uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務),后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
        predicates:
        - Path=/user/**

server:
  port: 8080

logging:
  level:
    org.springframework.cloud.gateway: TRACE
    org.springframework.http.server.reactive: DEBUG
    org.springframework.web.reactive: DEBUG
    reactor.ipc.netty: DEBUG
eureka:
  client:
    service-url:
      defaultZone: http://localhost:8761/eureka/
  instance:
    prefer-ip-address: true

其中test.uri是我自定義的屬性丧肴,uri以lb://開頭(lb代表從注冊中心獲取服務)残揉,后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱,按照上面的配置是http://localhost:8080/usr/** => http://service-one:8081/user/** 到此項目搭建完成芋浮,接下來測試了抱环,依次啟動eureka-server、service-one纸巷、gateway-client
訪問

WX20181113-180248@2x.png
WX20181113-180339@2x.png

不啟用注冊中心

即使集成了eureka-client也不想使用注冊中心服務镇草,可以關閉

eureka.client.enabled=false

StripPrefix屬性的使用

按照上面的配置,每一個路由只能對應一個控制器的轉(zhuǎn)發(fā)瘤旨,不夠靈活梯啤,假如我想讓userapi的請求都轉(zhuǎn)到service-one服務,比如:

spring:
  application:
    name: gateway-client
  cloud:
    gateway:
      routes:
      - id: route_service_one
        uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務)存哲,后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
        predicates:
        - Path=/userapi/**
        filters:
        - StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉userapi

修改完配置因宇,重啟gateway-client項目:


使用Hystrix

在gateway-client項目中引入依賴

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
        </dependency>

在spring cloud gateway中可以使用Hystrix。Hystrix是 spring cloud中一個服務熔斷降級的組件祟偷,在微服務系統(tǒng)有著十分重要的作用羽嫡。
Hystrix是 spring cloud gateway中是以filter的形式使用的,代碼如下:

@SpringBootApplication
public class GatewayClientApplication {

    @Value("${test.uri}")
    private String uri;

    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                //basic proxy
                .route(r -> r.path("/order/**")
                        .uri(uri)
                )
                .route(r -> r.path("/user/**")
                        .filters(f -> f
                                .hystrix(config -> config
                                        .setName("myserviceOne")
                                        .setFallbackUri("forward:/user/fallback")))
                        .uri(uri)).build();
    }

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

上面代碼中添加了一個路由并配置了hystrix的fallbackUri肩袍,新添加一個FallBackController控制器

@RestController
public class FallBackController {
    @RequestMapping("/user/fallback")
    public Mono<String> fallback() {
        return Mono.just("service error, jump fallback");
    }
}

重啟gateway-client項目杭棵,并關閉service-one服務,在瀏覽器訪問 http://localhost:8080/user/who

使用yml配置Hystrix

spring:
  application:
    name: gateway-client
  cloud:
    gateway:
      routes:
      - id: route_service_one
        uri: ${test.uri} # uri以lb://開頭(lb代表從注冊中心獲取服務),后面接的就是你需要轉(zhuǎn)發(fā)到的服務名稱
        predicates:
        - Path=/userapi/**
        filters:
        - StripPrefix=1 # 表示在轉(zhuǎn)發(fā)時去掉userapi

      - id: userapi2_route
        uri: ${test.uri}
        predicates:
        - Path=/userapi2/**
        filters:
        - StripPrefix=1
        - name: Hystrix
          args:
            name: myfallbackcmd
            fallbackUri: forward:/user/fallback

在配置中增加了一個新的路由userapi2_route魂爪,還配置了Hystrix先舷,當發(fā)生錯誤時會轉(zhuǎn)發(fā)到fallbackUri,測試訪問 http://localhost:8080/userapi2/order/info

reference
Hystrix wiki
Spring Cloud Gateway
Redis RateLimiter
轉(zhuǎn)載Redis RateLimiter實現(xiàn)

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末滓侍,一起剝皮案震驚了整個濱河市蒋川,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌撩笆,老刑警劉巖捺球,帶你破解...
    沈念sama閱讀 217,185評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異夕冲,居然都是意外死亡氮兵,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,652評論 3 393
  • 文/潘曉璐 我一進店門歹鱼,熙熙樓的掌柜王于貴愁眉苦臉地迎上來泣栈,“玉大人,你說我怎么就攤上這事弥姻∧掀” “怎么了?”我有些...
    開封第一講書人閱讀 163,524評論 0 353
  • 文/不壞的土叔 我叫張陵庭敦,是天一觀的道長疼进。 經(jīng)常有香客問我,道長秧廉,這世上最難降的妖魔是什么伞广? 我笑而不...
    開封第一講書人閱讀 58,339評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮定血,結果婚禮上,老公的妹妹穿的比我還像新娘诞外。我一直安慰自己澜沟,他們只是感情好,可當我...
    茶點故事閱讀 67,387評論 6 391
  • 文/花漫 我一把揭開白布峡谊。 她就那樣靜靜地躺著茫虽,像睡著了一般。 火紅的嫁衣襯著肌膚如雪既们。 梳的紋絲不亂的頭發(fā)上濒析,一...
    開封第一講書人閱讀 51,287評論 1 301
  • 那天,我揣著相機與錄音啥纸,去河邊找鬼号杏。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的盾致。 我是一名探鬼主播主经,決...
    沈念sama閱讀 40,130評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼庭惜!你這毒婦竟也來了罩驻?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,985評論 0 275
  • 序言:老撾萬榮一對情侶失蹤护赊,失蹤者是張志新(化名)和其女友劉穎惠遏,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骏啰,經(jīng)...
    沈念sama閱讀 45,420評論 1 313
  • 正文 獨居荒郊野嶺守林人離奇死亡节吮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,617評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了器一。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片课锌。...
    茶點故事閱讀 39,779評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖祈秕,靈堂內(nèi)的尸體忽然破棺而出渺贤,到底是詐尸還是另有隱情,我是刑警寧澤请毛,帶...
    沈念sama閱讀 35,477評論 5 345
  • 正文 年R本政府宣布志鞍,位于F島的核電站,受9級特大地震影響方仿,放射性物質(zhì)發(fā)生泄漏固棚。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,088評論 3 328
  • 文/蒙蒙 一仙蚜、第九天 我趴在偏房一處隱蔽的房頂上張望此洲。 院中可真熱鬧,春花似錦委粉、人聲如沸呜师。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,716評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽汁汗。三九已至,卻和暖如春栗涂,著一層夾襖步出監(jiān)牢的瞬間知牌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,857評論 1 269
  • 我被黑心中介騙來泰國打工斤程, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留角寸,地道東北人。 一個月前我還...
    沈念sama閱讀 47,876評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像袭厂,于是被迫代替她去往敵國和親墨吓。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 44,700評論 2 354

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理纹磺,服務發(fā)現(xiàn)帖烘,斷路器,智...
    卡卡羅2017閱讀 134,654評論 18 139
  • 微服務架構模式的核心在于如何識別服務的邊界橄杨,設計出合理的微服務秘症。但如果要將微服務架構運用到生產(chǎn)項目上,并且能夠發(fā)揮...
    程序員技術圈閱讀 2,783評論 10 27
  • 想對看過的spring cloud 各個項目進行一個簡單的搭建式矫,并使用docker部署乡摹,目前包含的項目有Eurek...
    會動的木頭疙瘩兒閱讀 4,107評論 1 12
  • Spring Cloud和Docker的微服務架構 ==原文地址== 本文通過以Spring Boot,Sprin...
    浮梁翁閱讀 1,629評論 0 7
  • 晴雪齋主陳東旭藝術簡介:陳東旭采转,湖南祁東人聪廉,師從方嚴、王義軍老師故慈。千竹書院成員板熊,中國書法院零八屆研究生,中國書法網(wǎng)...
    一葦書屋閱讀 845評論 0 2