Spring cloud gateway自定义filter以及负载均衡
自定义全局filter
package com.example.demo; import java.nio.charset.StandardCharsets; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange; import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono; /**
* @author woniu
* @date 2019/10/11 16:07
*/
@Component
public class CustomerTokenFilter implements GlobalFilter, Ordered{ private static final Log log = LogFactory.getLog(GatewayFilter.class); private static final String REQUEST_TIME_BEGIN = "requestTimeBegin";
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
exchange.getAttributes().put(REQUEST_TIME_BEGIN, System.currentTimeMillis());
log.info("contain token " + exchange.getRequest().getHeaders().containsKey("token"));
log.info("token is " + exchange.getRequest().getHeaders().get("token"));
if (exchange.getRequest().getPath().value().contains("success") || exchange.getRequest().getPath().value()
.contains("rest")) {
return chain.filter(exchange).then(
Mono.fromRunnable(() -> {
Long startTime = exchange.getAttribute(REQUEST_TIME_BEGIN);
if (startTime != null) {
log.info(exchange.getRequest().getURI().getRawPath() + ": " + (System.currentTimeMillis() - startTime) + "ms");
}
})
);
} else {
byte[] bytes =
"{\"status\":429,\"msg\":\"Too Many Requests\",\"data\":{}}".getBytes(StandardCharsets.UTF_8);
DataBuffer buffer = exchange.getResponse().bufferFactory().wrap(bytes);
ServerHttpResponse serverHttpResponse = exchange.getResponse();
serverHttpResponse.setStatusCode(HttpStatus.OK);
return exchange.getResponse().writeWith(Flux.just(buffer));
} } @Override
public int getOrder() {
return 0;
}
}
自定义LoadBalanceRule
package com.example.demo; import java.util.List;
import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.Server;
/**
* @author woniu
* @date 2019/10/12 16:20
*/
public class CustomerLoadBalanceRule extends AbstractLoadBalancerRule { private static final Log log = LogFactory.getLog(CustomerLoadBalanceRule.class); @Override
public Server choose(Object key) {
log.info("key is " + key);
List<Server> servers = this.getLoadBalancer().getReachableServers();
log.info("servers " + servers);
if (servers.isEmpty()) {
return null;
}
if (servers.size() == 1) {
return servers.get(0);
}
return randomChoose(servers);
}
/**
*
* <p>随机返回一个服务实例 </p>
* @param servers 服务列表
*/
private Server randomChoose(List<Server> servers) {
int randomIndex = RandomUtils.nextInt(servers.size());
return servers.get(randomIndex);
} @Override
public void initWithNiwsConfig(IClientConfig iClientConfig) { }
}
application.properties 配置
logging.level.org.springframework.cloud.gateway: TRACE
logging.level.org.springframework.http.server.reactive: TRACE
logging.level.org.springframework.web.reactive: TRACE
logging.level.org.springframework.boot.autoconfigure.web: TRACE spring.cloud.gateway.routes[].id: 1bcd
spring.cloud.gateway.routes[].uri: lb://my-load-balanced-service
spring.cloud.gateway.routes[].predicates[].name: Path
spring.cloud.gateway.routes[].predicates[].args[]: /rest/** my-load-balanced-service.ribbon.listOfServers: http://woniu.com
my-load-balanced-service.ribbon.NFLoadBalancerRuleClassName: com.example.demo.CustomerLoadBalanceRule
pom.xml引入的dependency
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
<version>2.1..RELEASE</version>
</dependency> <dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
<version>2.1..RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.1..RELEASE</version>
</dependency>
githup地址:https://github.com/baishi6582/wns/tree/master/springgatewaydemo
Spring cloud gateway自定义filter以及负载均衡的更多相关文章
- spring cloud gateway自定义过滤器
在API网关spring cloud gateway和负载均衡框架ribbon实战文章中,主要实现网关与负载均衡等基本功能,详见代码.本节内容将继续围绕此代码展开,主要讲解spring cloud g ...
- Spring Cloud:使用Ribbon实现负载均衡详解(下)
在上一篇文章(Spring Cloud:使用Ribbon实现负载均衡详解(上))中,我对 Ribbon 做了一个介绍,Ribbon 可以实现直接通过服务名称对服务进行访问.这一篇文章我详细分析一下如何 ...
- spring cloud gateway之filter篇
转载请标明出处: https://www.fangzhipeng.com 本文出自方志朋的博客 在上一篇文章详细的介绍了Gateway的Predict,Predict决定了请求由哪一个路由处理,在路由 ...
- Spring Cloud Alibaba学习笔记(21) - Spring Cloud Gateway 自定义全局过滤器
在前文中,我们介绍了Spring Cloud Gateway内置了一系列的全局过滤器,本文介绍如何自定义全局过滤器. 自定义全局过滤需要实现GlobalFilter 接口,该接口和 GatewayFi ...
- Spring Cloud Alibaba学习笔记(19) - Spring Cloud Gateway 自定义过滤器工厂
在前文中,我们介绍了Spring Cloud Gateway内置了一系列的内置过滤器工厂,若Spring Cloud Gateway内置的过滤器工厂无法满足我们的业务需求,那么此时就需要自定义自己的过 ...
- spring cloud gateway 自定义GatewayFilterFactory
spring cloud gateway提供了很多内置的过滤器,那么因为需求的关系,需要自定义实现,并且要可配置,在一番折腾之后,总算是解决了,那么久记录下来 对于自定义的factory,我们可以选择 ...
- Spring Cloud Gateway自定义过滤器实战(观测断路器状态变化)
欢迎访问我的GitHub https://github.com/zq2599/blog_demos 内容:所有原创文章分类汇总及配套源码,涉及Java.Docker.Kubernetes.DevOPS ...
- Spring Cloud Alibaba学习笔记(17) - Spring Cloud Gateway 自定义路由谓词工厂
在前文中,我们介绍了Spring Cloud Gateway内置了一系列的路由谓词工厂,但是如果这些内置的路由谓词工厂不能满足业务需求的话,我们可以自定义路由谓词工厂来实现特定的需求. 例如有某个服务 ...
- 史上最全Spring Cloud Alibaba--Nacos教程(涵盖负载均衡、配置管理、多环境切换、配置共享/刷新、灰度、集群)
能够实现Nacos安装 基于Nacos能实现应用负载均衡 能基于Nacos实现配置管理 配置管理 负载均衡 多环境切换 配置共享 配置刷新 灰度发布 掌握Nacos集群部署 1 Nacos安装 Nac ...
随机推荐
- MySQL 中 limit 的使用
需要注意的是,在Oracle中不使用limit,Oracle 使用rownum select no,name from emp limit 5 取前5条记录, select no,name from ...
- Java开发第一次面试经验(视频面试)
坐标:山东潍坊公共实训基地 面试岗位:java开发实习生 我们班级一共6个人一起面试,1对1,其他人坐在旁边倾听,两个大牛,四个酱油,我应该是最黑的酱油啦. 面试问题: 1.请简短的做一下自我介绍: ...
- ecshop 2.7 PC 微信扫描支付配置教程
在ecshop支付过程中,有些是没有微信支付的,需要自己添加微信支付的模块,那么怎么添加呢,添加过程需要调试,本人花了很长时间才调试成功的pc微信扫描支付, 1,数据库添加微信支付方模块 2,后台设置 ...
- 0基础入门 docker 部署 各种 Prometheus 案例 - 程序员学点xx 总集篇
目录 大家好, 学点xx 系列也推出一段时间了.虽然 yann 能力有限,但还是收到了很多鼓励与赞赏.对这个系列 yann 还是很喜欢的,特别是 Prometheus 篇,在期间经历公众号 100 篇 ...
- 【推荐系统】知乎live入门4.排序
参考链接 [推荐系统]知乎live入门 目录 1. 概述 2. 排序模型建模 3. 排序总结 ===================================================== ...
- 彻底解决mysql报错:1030, 'Got error 28 from storage engine'
权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明.本文链接:https://blog.csdn.net/harry5508/article/deta ...
- idea旗舰版续命
首先鼓励大家使用正版!我一直用的是免费的社区版,但发现有一些功能被阉割了,比如weblogbic就不支持,无奈现在的项目要用到这个,只能去下载旗舰版. 旗舰版需要付费,作为程序员的我为了一个临时的项目 ...
- Rsync+inotify 实时数据同步 inotify master 端的配置
强大的,细致的,异步的文件系统事件监控机制.Linux 内科从 2.6.13 起支持 inotify Inotify 实现的几款软件:Inotify,sersync,lsyncd ※Inotify 实 ...
- 一、苹果Assets.car文件解析图片
一. https://blog.wxhbts.com/assets.html
- 记一次在mac上源码编译curl,使其支持NSS的过程
一.背景 在一次学习https原理的过程中,希望客户端指定特定的cipher suites来抓包分析SSL/TLS的握手过程,就想到了使用curl工具,而不是使用浏览器. 接下来使用man curl找 ...