springcloud~gateway网关

有时间,我们在搭建微服务时,总希望拿一个比较单纯的,没有污染其它代码的项目来从头开始做,今天我们来建设一个最简单的,gateway项目,它被注册到nacos里,路由配置也存到nacos里,动态实现更新配置功能。

依赖配置

版本:com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-discovery:2021.0.1.0,com.alibaba.cloud:spring-cloud-starter-alibaba-nacos-config:2021.0.1.0,org.springframework.cloud:spring-cloud-starter-gateway:3.1.3

 <dependencies>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
      <!-- 解决nacos的配置文件不加载问题-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-bootstrap</artifactId>
        </dependency>
      <!-- 这个负载均衡如果不引入,在使用lb://时将出现503的错误-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-loadbalancer</artifactId>
        </dependency>
    </dependencies>

bootstrap.yml配置

spring:
  application:
    name: lind-gateway
  cloud:
    nacos:
      config:
        server-addr: 192.168.xx.xx:8848
        groupId: DEFAULT_GROUP
        namespace: public
        file-extension: yaml #对应nacos上面的配置文件扩展名
      discovery:
        server-addr: 192.168.xx.xx:8848
logging:
  level:
    root: warn
    org.springframework.cloud.gateway: debug #日志级别,方便调试
    org.alibaba.nacos: debug

nacos里的lind-gateway.yaml配置

spring:
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
      - id: micro-product
        uri: lb://micro-product
        predicates:
          - Path=/product/**
      - id: micro-account
        uri: lb://micro-account
        predicates:
          - Path=/account/**
      - id: micro-order
        uri: lb://micro-order
        predicates:
          - Path=/order/**
      default-filters:
        - StripPrefix=1 #请求地址去掉第1位,例如你请求/product/md/create时,实际转发到micro-product服务里的接口是/md/create

需要注意的地方

  • pom引用包时,需要添加spring-cloud-loadbalancer,以在gateway中实现负载协议
  • 使用nacos配置时,需要添加spring-cloud-starter-bootstrap
  • 如果是多级路径转发,加载添加StripPrefix,将可以在转发到后端时,将路径的前几位去除

测试

	@RequestMapping(path = "/stock/deduct")
	public Boolean deduct(String commodityCode, Integer count) {
		stockService.deduct(commodityCode, count);
		return true;
	}
  • 正常响应