SpringCloud 2020版本教程2:使用spring cloud gateway作为服务网关

x33g5p2x  于2021-11-19 转载在 Spring  
字(2.2k)|赞(0)|评价(0)|浏览(373)

Spring Cloud Gateway是Spring Cloud官方推出的第二代网关框架,取代Zuul网关。网关作为流量的,在微服务系统中有着非常作用,网关常见的功能有路由转发、权限校验、限流控制等作用。

在上一节的案例中,我们讲述了如何使用nacos作为服务注册中心和配置中心,使用feign和sc loadbalancer作为服务调用。本小节将讲述如何使用spring cloud gateway作为服务网关。

工程构建

新建一个gateway的工程,工程目录如下:

gateway需要注册到nacos中去,需要引入以下的依赖:

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

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

在配置文件application.pom文件:

server:
  port: 5000

spring:
  application:
    name: gateway
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    gateway:
      discovery:
        locator:
          enabled: false
          lowerCaseServiceId: true
      routes:
        - id: provider
          uri: lb://provider
          predicates:
            - Path=/provider/**
          filters:
            - StripPrefix=1
        - id: consumer
          uri: lb://consumer
          predicates:
            - Path=/consumer/**
          filters:
            - StripPrefix=1

配置的解释请阅读文末的相关教程,在这里不再重复。

在工程的启动文件加上相关注解:

@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

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

}

依次启动gateway\consumer\provider三个工程,在nacos中已经成功注册:

在浏览器上输入http://localhost:5000/consumer/hi-feign,浏览器返回响应:

hello feign, i'm provider ,my port:8762

gateway还有其他很多强大的功能在这里就不再讲述。

相关教程

  • Spring Cloud Gateway 初体验:https://www.fangzhipeng.com/springcloud/2018/11/06/sc-f-gateway1.html
  • Spring Cloud Gateway 之Predict篇:https://www.fangzhipeng.com/springcloud/2018/12/05/sc-f-gateway2.html
  • spring cloud gateway之filter篇:https://www.fangzhipeng.com/springcloud/2018/12/21/sc-f-gatway3.html
  • spring cloud gateway 之限流篇:https://www.fangzhipeng.com/springcloud/2018/12/22/sc-f-gatway4.html
  • spring cloud gateway之服务注册与发现:https://www.fangzhipeng.com/springcloud/2018/12/23/sc-f-gateway5.html

源码下载

https://github.com/forezp/SpringCloudLearning/tree/master/sc-2020-chapter2

相关文章

微信公众号

最新文章

更多