SpringCloud系列之网关(Gateway)应用篇

本文涉及的产品
Redis 开源版,标准版 2GB
推荐场景:
搭建游戏排行榜
云数据库 Tair(兼容Redis),内存型 2GB
简介:

SpringCloud系列之网关(Gateway)应用篇

@

目录
前言
项目版本
网关访问
鉴权配置
限流配置
前言
由于项目采用了微服务架构,业务功能都在相应各自的模块中,每个业务模块都是以独立的项目运行着,对外提供各自的服务接口,如没有类似网关之类组件的话,相应的鉴权,限流等功能实现起来不能够进行统一的配置和管理,有了网关后一切都是如此的优雅。刚好新项目中采用了SpringCloud Gateway组件作为网关,就记录下项目中常用的配置吧。

项目版本
spring-boot-version:2.2.5.RELEASE
spring-cloud.version:Hoxton.SR3

网关访问
示例项目还是延续SpringCloud系列原先的示例代码,引入网关仅仅只需新增spring-cloud-gateway项目即可。
核心pom.xml(详细信息查看示例源码,在文章末尾)


org.springframework.cloud

<artifactId>spring-cloud-starter-gateway</artifactId>


bootstrap.yml

server:
port: 9005
spring:
application:

name: springcloud-gateway-service

cloud:

config:
  discovery:
    enabled: true
    service-id: config-server
  profile: dev
  label: master
gateway:
  enabled: true  #开启网关
  discovery:
    locator:
      enabled: true #开启自动路由,以服务id建立路由,服务id默认大写
      lower-case-service-id: true #服务id设置为小写

eureka:
client:

service-url:
  defaultZone: http://localhost:9003/eureka/

ApiGatewayApplication.java

@EnableDiscoveryClient
@SpringBootApplication
public class ApiGatewayApplication {

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

}
访问原先spring-cloud-system-server模块对外提供的接口
http://localhost:9004/web/system/getEnvName

通过网关进行访问
http://localhost:9005/system-server/web/system/getEnvName

请求能正常返回,那就说明网关组件已集成进来了,是不是很简单呢,一行配置项就搞定了,便于展现这边采用properties配置方式说明

spring.cloud.gateway.discovery.locator.enabled=true
到此网关的基础配置应用已完成,通过网关访问的请求路径格式如下
http://网关地址:网关端口/各自服务id/各自服务对外提供的URL访问

鉴权配置
这边将spring-cloud-system-server模块引入spring security安全认证组件,上代码。
pom.xml

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


application.properties

spring.security.user.name=test
spring.security.user.password=123456
服务模块调整完后,重新启动该模块,访问对外请求接口,出现认证登录界面说明配置成功。
http://localhost:9004/web/system/getEnvName

输入上述配置项中配置的用户名和密码后,接口请求返回正常。

请求网关地址,访问服务接口按下回车键时会跳转至服务项目认证页面,如下
http://localhost:9005/system-server/web/system/getEnvName

接下来对网关模块进行相应调整
bootstrap.yml

spring:
application:

name: springcloud-gateway-service

security:

user:
  name: test
  password: 123456

新增安全认证过滤类
SecurityBasicAuthorizationFilter.java

@Component
public class SecurityBasicAuthorizationFilter implements GlobalFilter, Ordered {

@Value("${spring.security.user.name}")
private String username;
@Value("${spring.security.user.password}")
private String password;

public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    String auth = username.concat(":").concat(password);
    String encodedAuth = new sun.misc.BASE64Encoder().encode(auth.getBytes(Charset.forName("US-ASCII")));
    String authHeader = "Basic " +encodedAuth;
    //headers中增加授权信息
    ServerHttpRequest serverHttpRequest = exchange.getRequest().mutate().header("Authorization", authHeader).build();
    ServerWebExchange build = exchange.mutate().request(serverHttpRequest).build();
    return chain.filter(build);
}
/**
 * 优先级
 * 数字越大优先级越低
 * @return
 */
public int getOrder() {
    return -1;
}

}
重启网关项目,重新访问服务地址,返回正常数据。这边说明下在测试时最好新开一个无痕窗口或者清理浏览器缓存后再进行测试,不然因会话缓存会导致安全认证没有生效的假象。
http://localhost:9005/system-server/web/system/getEnvName

限流配置
SpringCloud Gateway自带限流功能,但是基于redis,这边简单演示下,项目中没有使用而是使用了阿里开源的sentinel,后续将介绍下集成sentinel组件。
pom.xml

<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis-reactive</artifactId>


bootstrap.yml

spring:
cloud:

gateway:
  enabled: true  #开启网关
  discovery:
    locator:
      enabled: true #开启自动路由,以服务id建立路由,服务id默认大写
      lower-case-service-id: true #服务id设置为小写
  routes:
    - id: baidu_route
      uri: https://www.baidu.com/
      predicates:
      - Path=/baidu/**
      filters:
        - name: RequestRateLimiter
          args:
            key-resolver: "#{@apiKeyResolver}"
            redis-rate-limiter.replenishRate: 1 #允许每秒处理多少个请求
            redis-rate-limiter.burstCapacity: 5 #允许在一秒钟内完成的最大请求数

redis:

host: 192.168.28.142
pool: 6379
password: password
database: 1              

RequestRateLimiterConfig.java

@Configuration
public class RequestRateLimiterConfig {

@Bean
@Primary
public KeyResolver apiKeyResolver() {
    //URL限流,超出限流返回429状态
    return exchange -> Mono.just(exchange.getRequest().getPath().toString());
}

}
重新启动网关项目,访问如下请求地址,会请求跳转至百度首页,目前配置项配置为1s内请求数5次,超过5次就会触发限流,返回429状态码,多次刷新就会出现如下页面
http://localhost:9005/baidu/test

通过monitor命令实时查看redis信息

本次网关项目目录结构

同系列文章
1-SpringCloud系列之配置中心(Config)使用说明
2-SpringCloud系列之服务注册发现(Eureka)应用篇
示例源码

原文地址https://www.cnblogs.com/chinaWu/p/12731796.html

相关实践学习
基于Redis实现在线游戏积分排行榜
本场景将介绍如何基于Redis数据库实现在线游戏中的游戏玩家积分排行榜功能。
云数据库 Redis 版使用教程
云数据库Redis版是兼容Redis协议标准的、提供持久化的内存数据库服务,基于高可靠双机热备架构及可无缝扩展的集群架构,满足高读写性能场景及容量需弹性变配的业务需求。 产品详情:https://www.aliyun.com/product/kvstore &nbsp; &nbsp; ------------------------------------------------------------------------- 阿里云数据库体验:数据库上云实战 开发者云会免费提供一台带自建MySQL的源数据库&nbsp;ECS 实例和一台目标数据库&nbsp;RDS实例。跟着指引,您可以一步步实现将ECS自建数据库迁移到目标数据库RDS。 点击下方链接,领取免费ECS&amp;RDS资源,30分钟完成数据库上云实战!https://developer.aliyun.com/adc/scenario/51eefbd1894e42f6bb9acacadd3f9121?spm=a2c6h.13788135.J_3257954370.9.4ba85f24utseFl
相关文章
|
22天前
|
负载均衡 Java Nacos
SpringCloud基础2——Nacos配置、Feign、Gateway
nacos配置管理、Feign远程调用、Gateway服务网关
SpringCloud基础2——Nacos配置、Feign、Gateway
|
7天前
|
Java 开发者 Spring
Spring Cloud Gateway 中,过滤器的分类有哪些?
Spring Cloud Gateway 中,过滤器的分类有哪些?
15 3
|
9天前
|
负载均衡 Java 网络架构
实现微服务网关:Zuul与Spring Cloud Gateway的比较分析
实现微服务网关:Zuul与Spring Cloud Gateway的比较分析
21 5
|
1月前
|
安全 Java 开发者
强大!Spring Cloud Gateway新特性及高级开发技巧
在微服务架构日益盛行的今天,网关作为微服务架构中的关键组件,承担着路由、安全、监控、限流等多重职责。Spring Cloud Gateway作为新一代的微服务网关,凭借其基于Spring Framework 5、Project Reactor和Spring Boot 2.0的强大技术栈,正逐步成为业界的主流选择。本文将深入探讨Spring Cloud Gateway的新特性及高级开发技巧,助力开发者更好地掌握这一强大的网关工具。
112 6
|
2月前
|
安全 API
【Azure API 管理】APIM Self-Host Gateway 自建本地环境中的网关数量超过10个且它们的出口IP为同一个时出现的429错误
【Azure API 管理】APIM Self-Host Gateway 自建本地环境中的网关数量超过10个且它们的出口IP为同一个时出现的429错误
|
2月前
|
存储 容器
【Azure 事件中心】为应用程序网关(Application Gateway with WAF) 配置诊断日志,发送到事件中心
【Azure 事件中心】为应用程序网关(Application Gateway with WAF) 配置诊断日志,发送到事件中心
|
3月前
|
监控 负载均衡 Java
深入理解Spring Cloud中的服务网关
深入理解Spring Cloud中的服务网关
|
11天前
|
监控 负载均衡 安全
微服务(五)-服务网关zuul(一)
微服务(五)-服务网关zuul(一)
|
2月前
|
运维 Kubernetes 安全
利用服务网格实现全链路mTLS(一):在入口网关上提供mTLS服务
阿里云服务网格(Service Mesh,简称ASM)提供了一个全托管式的服务网格平台,兼容Istio开源服务网格,用于简化服务治理,包括流量管理和拆分、安全认证及网格可观测性,有效减轻开发运维负担。ASM支持通过mTLS提供服务,要求客户端提供证书以增强安全性。本文介绍如何在ASM入口网关上配置mTLS服务并通过授权策略实现特定用户的访问限制。首先需部署ASM实例和ACK集群,并开启sidecar自动注入。接着,在集群中部署入口网关和httpbin应用,并生成mTLS通信所需的根证书、服务器证书及客户端证书。最后,配置网关上的mTLS监听并设置授权策略,以限制特定客户端对特定路径的访问。
119 2
|
11天前
|
测试技术 微服务
微服务(八)-服务网关zuul(四)
微服务(八)-服务网关zuul(四)
下一篇
无影云桌面