gateway在微服务中起到路由网关的作用

  • 配置
    • pom引包
    • 主启动类
  • 一、路由——Route
    • 路由网关配置分两种,一种是加载bean配置;一种是yml配置
      • 方式一:yml文件配置
      • 方式二:bean配置(yml文件中nacos配置还是需要)
    • 通过注册中心配置服务名的方式配置路由网关
  • 二、断言——Predicate
    • 断言`Predicate`的几种使用:
      • 一、After Route Predicate
      • 二、2.Before Route Predicate
      • 三、Between Route Predicate
      • 四、Cookie Route Predicate
      • 五、Header Route Predicate
      • 六、Host Route Predicate
      • 七、Method Route Predicate
      • 八、Query Route Predicate
      • 九、Path Route Predicate
  • 三、过滤——Filter
    • gateway本身携带的filter
    • 自定义filter

配置

pom引包

会和spring-boot-starter-webspring-boot-starter-actuator起冲突,所以需要去掉这两个包

 <!--新增gateway--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><version>2.2.2.RELEASE</version></dependency>

pom完整内容

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.7.RELEASE</version><relativePath/></parent><groupId>com.hao.springcloud</groupId><artifactId>cloud-gateway-gateway9527</artifactId><version>1.0-SNAPSHOT</version><properties><java.version>1.8</java.version></properties><dependencies><!--新增gateway--><dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter-gateway</artifactId><version>2.2.2.RELEASE</version></dependency><!--nacos--><dependency><groupId>com.alibaba.cloud</groupId><artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId><version>2.2.1.RELEASE</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build>
</project>

主启动类

package com.hao.springcloud.cloudgatewaygateway9527;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient
public class CloudGatewayGateway9527Application {public static void main(String[] args) {SpringApplication.run(CloudGatewayGateway9527Application.class, args);}}

一、路由——Route

路由网关配置分两种,一种是加载bean配置;一种是yml配置

方式一:yml文件配置
server:port: 9527spring:application:#服务名name: cloud-gatewaycloud:#注册中心nacos:discovery:###服务注册地址server-addr: localhost:8848#网关配置gateway:routes:- id: payment_hystrix #路由的ID,没有固定规则但要求唯一,建议配合服务名uri: http://localhost:8001 #匹配后提供服务的路由地址predicates:- Path=/payment/hystrix/**   #断言,路径相匹配的进行路由。注意是Path的P是大写#可以配置多个路由指定不同的服务- id: news_baiduuri: http://news.baidu.compredicates:- Path=/**
方式二:bean配置(yml文件中nacos配置还是需要)
package com.hao.springcloud.cloudgatewaygateway9527.config;import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.PredicateSpec;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.function.Function;@Configuration
public class GateWayConfig {@Beanpublic RouteLocator customRouteLocator(RouteLocatorBuilder routeLocatorBuilder) {RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();/*lambda表达式*/routes.route("payment_hystrix",r -> r.path("/payment/hystrix/**").uri("http://localhost:8001")).build();routes.route("news_baidu", new Function<PredicateSpec, Route.AsyncBuilder>() {@Overridepublic Route.AsyncBuilder apply(PredicateSpec predicateSpec) {return predicateSpec.path("/**").uri("http://news.baidu.com");}}).build();return routes.build();}
}

效果:

通过注册中心配置服务名的方式配置路由网关

lb://serviceName是spring cloud gateway在微服务中自动为我们创建的负载均衡uri

server:port: 9527spring:application:#服务名name: cloud-gatewaycloud:#注册中心nacos:discovery:###服务注册地址server-addr: liguanghao.top:8848#网关gateway:discovery:locator:enabled: true  #开启从注册中心动态创建路由的功能,利用微服务名进行路由routes:- id: cloud-payment-service #路由的ID,没有固定规则但要求唯一,建议配合服务名#uri: http://localhost:8001  #匹配后提供服务的路由地址uri: lb://cloud-payment-service  #通过注册中心找到的8001的服务名。lb:负载均衡predicates:- Path=/payment/hystrix/** #断言,路径相匹配的进行路由

二、断言——Predicate

断言Predicate的几种使用:

一、After Route Predicate

配置从什么时间之后才可以访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service predicates:- After=2020-03-08T10:59:34.102+08:00[Asia/Shanghai]# 2020年3月8号10:59:34之后才可访问
二、2.Before Route Predicate

配置什么时间之前才可以访问,超过此时间不可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service predicates:- Before=2020-03-08T10:59:34.102+08:00[Asia/Shanghai]# 2020年3月8号10:59:34之前可以访问,超过之后禁止访问
三、Between Route Predicate

配置可访问的时间区间

routes:- id: cloud-payment-service uri: lb://cloud-payment-service predicates:- Between=2020-03-08T10:59:34.102+08:00[Asia/Shanghai] ,  2020-03-09T10:59:34.102+08:00[Asia/Shanghai]# 2020年3月8号10:59:34-2020年3月9号10:59:34之间可访问
四、Cookie Route Predicate

Cookie 中携带指定的参数和值,才可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service predicates:- Cookie=username,zzyy # Cookie中必须有username参数,并且值为zzyy

测试

不带cookie或者带username但值不对访问都失败;带cokkie且值正常才访问成功

配置多条Cookie:

routes:- id: cloud-payment-service uri: lb://cloud-payment-service  predicates:- Cookie=username,zzyy- Cookie=token,aabb
五、Header Route Predicate

请求头中携带指定的参数,值可以通过正则表达是配置。才可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service  predicates:- Header=X-Request-Id, \d+  #请求头中要有X-Request-Id属性并且值为整数的正则表达式
六、Host Route Predicate

host中携带指定的参数才可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service  predicates:- Host=**.hao.com
七、Method Route Predicate

指定方法的请求方式,符合才可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service  predicates:- Method=GET
八、Query Route Predicate

请求参数的方法中要有指定的入参和正则表达式配置的值才可访问

routes:- id: cloud-payment-service uri: lb://cloud-payment-service  predicates:- Query=userId, \d+ #要有参数名称并且值是正整数才能路由#如:localhost:9527/getUser?userId=30
九、Path Route Predicate

符合指定路径才可访问

routes:- id: cloud-payment-service #路由的ID,没有固定规则但要求唯一,建议配合服务名uri: lb://cloud-payment-service  #通过注册中心找到的8001的服务名predicates:- Path=/payment/hystrix/** #断言,路径相匹配的进行路由

三、过滤——Filter

gateway本身携带的filter


自定义filter

主要实现两个接口GlobalFilterOrdered

package com.hao.springcloud.cloudgatewaygateway9527.filter;import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.util.Date;@Component
@Slf4j
public class MyLogGateWayFilter implements GlobalFilter , Ordered{/*** 设置过滤条件* @param exchange* @param chain* @return*/@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {log.info("*********come in MyLogGateWayFilter: "+new Date());//设置参数中必须含有token参数String token = exchange.getRequest().getQueryParams().getFirst("token");if(StringUtils.isEmpty(token)){log.info("*****用户名为Null 非法用户,(┬_┬)");exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//给人家一个回应return exchange.getResponse().setComplete();}return chain.filter(exchange);}/*** 设置过滤器优先级* @return*/@Overridepublic int getOrder() {return 0;}
}

springcloud之gateway的使用相关推荐

  1. SpringCloud 网关 Gateway

    哈喽~大家好,这篇来看看SpringCloud 网关 Gateway.

  2. 解决SpringCloud的Gateway网关无法访问服务的静态资源

    解决SpringCloud的Gateway网关无法访问服务的静态资源 在重构项目的时候,配置gateway网关后,利用网关地址访问服务,发现服务的静态资源报了404 报错如下: gateway网关配置 ...

  3. SpringCloud创建Gateway模块

    1.说明 本文详细介绍Spring Cloud创建Gateway模块的方法, 基于已经创建好的Spring Cloud父工程, 请参考SpringCloud创建项目父工程, 和已经创建好的Eureka ...

  4. SpringCloud 09 - Gateway 网关

    SpringCloud 08 - Hystrix 熔断器 1. 概述简介 1.1 官网 上一代 zuul 1.x: https://github.com/Netflix/zuul/wiki 当前 ga ...

  5. springcloud整合Gateway

    简介 1.是什么 springcloud gateway使用webflux的reactor-netty响应式编程组件,底层使用了Netty通讯框架 2.能干嘛 反向代理.鉴权.流量控制.熔断.日志监控 ...

  6. SpringCloud之GateWay的基础使用

    网关简介: ​ 网关是微服务最边缘的服务(网关也是一个服务),直接暴露给用户,用来做用户和微服务的桥梁. ​ 网关作为微服务架构系统的统一入口,为微服务架构系统提供简单.有效且统一的API路由管理(提 ...

  7. SpringCloud之Gateway

    1.Gateway是什么? 1.1 为微服务提供简单有效的路由管理方式 1.2 词汇 (1)Route(路由) :构建网关的基础模块,由ID.目标URL.断言和过滤器等组成 id:路由唯一标识,区别于 ...

  8. springcloud中Gateway的限流熔断机制!

    前言 目前,Spring Cloud Gateway是仅次于Spring Cloud Netflix的第二个最受欢迎的Spring Cloud项目(就GitHub上的星级而言).它是作为Spring ...

  9. SpringCloud(Gateway网关跨域)

    网关解决跨域问题 创建配置类 @Configuration public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsC ...

  10. SpringCloud(Gateway网关使用)

    在pom.xml引入依赖 <dependencies><dependency><groupId>com.leon</groupId><artifa ...

最新文章

  1. 【Deep Learning笔记】神经网络基础
  2. python操作excel表格-Python自动化办公之操作Excel文件
  3. 构建空列表的两种法是_Python 基础3之列表
  4. Electrification
  5. 服务器端大文件如何传给客户端,客户端往服务器传文件
  6. hdu 1231 最大连续子序列 ,1003 Max Sum;
  7. pycharm检测不到python编译器_1.2 搭建python+pycharm编程开发环境
  8. 从零实现深度学习框架——优化反向传播相关代码
  9. 存储服务器格式化恢复方法
  10. huhamhire-hosts
  11. 电子设计大赛-电源类题目分析
  12. 数学建模MATLAB之分析法(一)
  13. 三维CAD/CAM软件SINOVATION 10 中文注册版
  14. H5游戏开发:游戏引擎入门推荐
  15. lol服务器维护8月7,LOL8月7日维护到几点 具体更新了什么
  16. mysql 时间段天数_ORACLE任意时间段内所有天数日期查询
  17. 东莞耳机工厂告诉你,多唛降噪是什么!
  18. 深度学习之DeepCTR
  19. 新必应(new bing)申请
  20. 卡片IOT板开发计划

热门文章

  1. ICP算法进行点云配准
  2. 苹果手机如何分享wifi密码_WiFi密码破解器 v5.1.3手机版
  3. 一键安装 kX3552 ProFX312 UFX52 程序
  4. 微软服务器版本组建nas,怎么用windows server 2012组建家用nas服务器
  5. java小程序坦克大战,小程序经典游戏,微信欢乐坦克大战攻略
  6. 微信支付服务商平台(商户平台)扫码登录后提示“登录超时,请重新登录”时该怎么处理?
  7. XtraBackUp 全量备份
  8. vue如何打开pdf文件
  9. python矩阵转置_矩阵转置python
  10. 板绘新手入门sai绘画软件有哪些技巧?