SpringCloud学习(二)——搭建Spring Cloud Gateway


先看一下Spring官方对Spring Cloud Gateway的介绍:

  

 

 

Spring Cloud Gateway是为了提供一种简单而有效的方式来路由到 API,并为它们提供横切关注点,例如:安全性、监控/指标和弹性

Spring Cloud Gateway就好比是整个系统的大门,比如你要去坐高铁,入口的安检会根据高铁站规定和你的身份判断你是否有权限进入,进入后让你去哪儿候车,同时检测你是否带了危险品等等,而且人进入多的时候有保安拦着是否要等着一会儿进入...

下面是搭建过程(接上一篇):

1、新建module,引入spring cloud gateway和eureka-client依赖

  

 

 

2、配置application.yml文件,内容如下:

server:
  port: 80

#指定当前eureka客户端注册的服务端地址
eureka:
  client:
    service-url:
      defaultZone: http://${eureka.instance.hostname}:8000/eureka
  instance:
    hostname: localhost

spring:
  application:
    name: cn-gateway
  profiles:
    active: path-route

---         #三个横线表示再创建一个配置文件
spring:
  profiles: path-route            #配置文件名 和 spring.profiles.active 相对应
  cloud:
    #设置路由规则
    gateway:
      routes:
        - id: cn-system
          uri: lb://cn-system      #代表从注册中心获取服务,且以lb(load-balance)负载均衡方式转发
          predicates: #断言
            - Path=/system/**      #表示将以/system/**开头的请求转发到uri为lb://cn-system的地址上
        #      - After=2019-06-20T00:00:00.789-07:00[America/Denver] #表示在该时间点之后的时间,发出的请求会被路由到uri
          filters:
            - StripPrefix=1        #表示将Path的路径/system在转发前去掉,如果设置StripPrefix=2,表示将/system/*/去掉 以此类推... 同时将spring.cloud.gateway.discovery.locator.enabled改为false,如果不改的话,之前的localhost:8001/system/hello这样的请求地址也能正常访问,因为这时为每个服务创建了2个router
        - id: cn-auth
          uri: lb://cn-auth
          predicates:
            - Path=/auth/**
          filters:
            - StripPrefix=1
      discovery:
        locator:
          #表示gateway开启服务注册和发现功能,
          #并且spring cloud gateway自动根据服务发现为每一个服务创建了一个router,这个router将以服务名开头的请求路径转发到对应的服务
          enabled: true
          #表示将请求路径的服务名配置改成小写  因为服务注册的时候,向注册中心注册时将服务名转成大写的了
          lower-case-service-id: true

3、配置启动类,添加注解@EnableDiscoveryClient

package com.cning.gateway;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

@SpringBootApplication
@EnableDiscoveryClient public class CnGatewayApplication {

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

}

4、这就完成了,启动一下我们看一下结果,为了区分出转发效果,我在cn-auth的controller里做了点标记

 

 

  启动完成后浏览器访问 localhost:/system/hello?msg=你好     和    localhost:/auth/hello?msg=你好,结果如下图

  

 

 

   

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM