当前位置: 首页 > news >正文

荆州做网站公司太原推广团队

荆州做网站公司,太原推广团队,企业网站建设后期维护费用,哪些企业会考虑做网站文章目录 前言一、内置路由断言1. 案例(Weight)2. 更多断言 二、自定义路由断言1. 黑名单断言2. 全局异常处理3. 应用配置4. 单元测试 总结 前言 Spring Cloud Gateway可以让我们根据请求内容精确匹配到对应路由服务,官方已经内置了很多路由断言,我们也…

文章目录

  • 前言
  • 一、内置路由断言
    • 1. 案例(Weight)
    • 2. 更多断言
  • 二、自定义路由断言
    • 1. 黑名单断言
    • 2. 全局异常处理
    • 3. 应用配置
    • 4. 单元测试
  • 总结


前言

Spring Cloud Gateway可以让我们根据请求内容精确匹配到对应路由服务,官方已经内置了很多路由断言,我们也可以根据需求自己定义,RemoteAddrRoutePredicateFactory就像是根据IP去匹配的白名单,接下来我们根据它来自定义一个IP黑名单。


一、内置路由断言

1. 案例(Weight)

spring:cloud:gateway:routes:- id: weight_highuri: https://weighthigh.orgpredicates:- Weight=group1, 8- id: weight_lowuri: https://weightlow.orgpredicates:- Weight=group1, 2

这条路线将把约80%的流量转发到weighthigh.org,约20%的流量转发给weighlow.org

2. 更多断言

序号断言类型用法描述
1After- After=2017-01-20T17:42:47.789-07:00[America/Denver]此路由与2017年1月20日17:42:47之后的任何请求相匹配。
2Before- Before=2017-01-20T17:42:47.789-07:00[America/Denver]此路由与2017年1月20日17:42:47之前的任何请求相匹配。
3Between- Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]此路由与2017年1月20日17:42:47之后至2017年1月21日17:42:47之前提出的任何请求相匹配。
4Cookie- Cookie=chocolate, ch.p此路由匹配名为chocolate的cookie的请求,该cookie的值与ch.p匹配。
5Header- Header=X-Request-Id, \d+此路由匹配请求有一个名为X-request-Id的请求头,其值与\d+正则表达式匹配(即它有一个或多个数字的值)。
6Host- Host=.somehost.org,.anotherhost.org此路由匹配请求的Host值为www.somehost.org、beta.somehost.org或www.anotherhost.org。
7Method- Method=GET,POST此路由匹配请求方法是GET或POST。
8Path- Path=/red/{segment},/blue/{segment}此路由匹配请求路径为:/red/1 或 /red/1/ 或 /red/blue 或/blue/green。
9Query- Query=green- Query=green - Query=red, gree.
10RemoteAddr- RemoteAddr=192.168.1.1/24如果请求的远程地址是192.168.1.10,则此路由匹配。
11XForwarded Remote Addr- XForwardedRemoteAddr=192.168.1.1/24如果X-Forwarded-For标头包含例如192.168.1.10,则此路由匹配。

二、自定义路由断言

1. 黑名单断言

package org.example.gateway.predicate;import io.netty.handler.ipfilter.IpFilterRuleType;
import io.netty.handler.ipfilter.IpSubnetFilterRule;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.cloud.gateway.support.ipresolver.RemoteAddressResolver;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;
import static org.springframework.cloud.gateway.support.ShortcutConfigurable.ShortcutType.GATHER_LIST;/*** Create by zjg on 2024/7/29*/
@Component
public class BlackRemoteAddrRoutePredicateFactory  extends AbstractRoutePredicateFactory<BlackRemoteAddrRoutePredicateFactory.Config> {private static final Log log = LogFactory.getLog(BlackRemoteAddrRoutePredicateFactory.class);public BlackRemoteAddrRoutePredicateFactory() {super(BlackRemoteAddrRoutePredicateFactory.Config.class);}@Overridepublic ShortcutType shortcutType() {return GATHER_LIST;}@Overridepublic List<String> shortcutFieldOrder() {return Collections.singletonList("sources");}@NotNullprivate List<IpSubnetFilterRule> convert(List<String> values) {List<IpSubnetFilterRule> sources = new ArrayList<>();for (String arg : values) {addSource(sources, arg);}return sources;}@Overridepublic Predicate<ServerWebExchange> apply(BlackRemoteAddrRoutePredicateFactory.Config config) {List<IpSubnetFilterRule> sources = convert(config.sources);return new GatewayPredicate() {@Overridepublic boolean test(ServerWebExchange exchange) {InetSocketAddress remoteAddress = config.remoteAddressResolver.resolve(exchange);if (remoteAddress != null && remoteAddress.getAddress() != null) {String hostAddress = remoteAddress.getAddress().getHostAddress();String host = exchange.getRequest().getURI().getHost();if (log.isDebugEnabled() && !hostAddress.equals(host)) {log.debug("Black remote addresses didn't match " + hostAddress + " != " + host);}for (IpSubnetFilterRule source : sources) {if (source.matches(remoteAddress)) {exchange.getAttributes().put("BlackRemoteAddrRoutePredicateFactory",remoteAddress.getAddress().getHostAddress());return false;//能匹配到则在黑名单中,不再执行}}}return true;}@Overridepublic Object getConfig() {return config;}@Overridepublic String toString() {return String.format("BlackRemoteAddrs: %s", config.getSources());}};}private void addSource(List<IpSubnetFilterRule> sources, String source) {if (!source.contains("/")) { // no netmask, add defaultsource = source + "/32";}String[] ipAddressCidrPrefix = source.split("/", 2);String ipAddress = ipAddressCidrPrefix[0];int cidrPrefix = Integer.parseInt(ipAddressCidrPrefix[1]);sources.add(new IpSubnetFilterRule(ipAddress, cidrPrefix, IpFilterRuleType.ACCEPT));}@Validatedpublic static class Config {@NotEmptyprivate List<String> sources = new ArrayList<>();@NotNullprivate RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() {};public List<String> getSources() {return sources;}public BlackRemoteAddrRoutePredicateFactory.Config setSources(List<String> sources) {this.sources = sources;return this;}public BlackRemoteAddrRoutePredicateFactory.Config setSources(String... sources) {this.sources = Arrays.asList(sources);return this;}public BlackRemoteAddrRoutePredicateFactory.Config setRemoteAddressResolver(RemoteAddressResolver remoteAddressResolver) {this.remoteAddressResolver = remoteAddressResolver;return this;}}
}

2. 全局异常处理

package org.example.gateway.config;import org.example.common.model.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.reactive.resource.NoResourceFoundException;
import org.springframework.web.server.ServerWebExchange;
import java.io.PrintWriter;
import java.io.StringWriter;/*** Create by zjg on 2024/7/29*/
@RestControllerAdvice
public class GlobalExceptionHandler {Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);@ExceptionHandler(NoResourceFoundException.class)//无可用路由public Result exception(ServerWebExchange exchange, NoResourceFoundException ex){String detail = ex.getBody().getDetail();String mark="resource ";String message = detail.substring(detail.indexOf(mark) + mark.length());setStatusCode(exchange.getResponse(),ex.getStatusCode());if(StringUtils.hasText(exchange.getAttribute("BlackRemoteAddrRoutePredicateFactory"))){//IP黑名单return  Result.error(ex.getStatusCode().value(),"拒绝访问","您的IP已被添加到黑名单中,拒绝访问!");}return  Result.error(ex.getStatusCode().value(),"无可用路由",String.format("没有可用的路由[%s]",message));}@ExceptionHandler(NotFoundException.class)//无可用服务public Result exception(ServerHttpResponse response,NotFoundException ex){logger.error(ex.getMessage());String detail = ex.getBody().getDetail();String mark="for ";String message = detail.substring(detail.indexOf(mark) + mark.length());setStatusCode(response,ex.getStatusCode());return  Result.error(ex.getStatusCode().value(),"服务不可用",String.format("没有可用的服务实例[%s]",message));}@ExceptionHandler(Exception.class)//异常保底public Result exception(ServerHttpResponse response,Exception exception){StringWriter stringWriter = new StringWriter();PrintWriter writer=new PrintWriter(stringWriter);exception.printStackTrace(writer);logger.error(stringWriter.toString());setStatusCode(response,HttpStatus.INTERNAL_SERVER_ERROR);return  Result.error(HttpStatus.INTERNAL_SERVER_ERROR.value(),exception.getMessage());}private void setStatusCode(ServerHttpResponse response,HttpStatusCode httpStatusCode){response.setStatusCode(httpStatusCode);}
}

3. 应用配置

spring:cloud:gateway:routes:- id: provider-serviceuri: lb://provider-servicepredicates:- Path=/provider/**- BlackRemoteAddr=192.168.1.1/24,127.0.0.1

4. 单元测试

curl 192.168.0.104:8888/provider/hello

正常访问
在这里插入图片描述

黑名单访问
在这里插入图片描述


总结

回到顶部

这样我们就能通过断言配置黑名单,可以针对固定IP做灵活处理。


文章转载自:
http://autoerotic.c7500.cn
http://recrystallize.c7500.cn
http://erythorbic.c7500.cn
http://phocomelus.c7500.cn
http://lollapalooza.c7500.cn
http://seceder.c7500.cn
http://sewellel.c7500.cn
http://domiciled.c7500.cn
http://coreopsis.c7500.cn
http://despondence.c7500.cn
http://satellize.c7500.cn
http://longwall.c7500.cn
http://hydrastine.c7500.cn
http://dilettanteism.c7500.cn
http://rummy.c7500.cn
http://ultramundane.c7500.cn
http://ionophoresis.c7500.cn
http://somedeal.c7500.cn
http://anagrammatic.c7500.cn
http://transcurrence.c7500.cn
http://homoiotherm.c7500.cn
http://snow.c7500.cn
http://tropicopolitan.c7500.cn
http://siff.c7500.cn
http://feijoa.c7500.cn
http://septicopyemia.c7500.cn
http://ubiquitously.c7500.cn
http://reboil.c7500.cn
http://prelapsarian.c7500.cn
http://aphlogistic.c7500.cn
http://disposal.c7500.cn
http://abrasive.c7500.cn
http://unstable.c7500.cn
http://quasiparticle.c7500.cn
http://floodwall.c7500.cn
http://dichotomise.c7500.cn
http://erk.c7500.cn
http://moronism.c7500.cn
http://latency.c7500.cn
http://confraternity.c7500.cn
http://isometropia.c7500.cn
http://coparcener.c7500.cn
http://ironware.c7500.cn
http://clyster.c7500.cn
http://waterfinder.c7500.cn
http://preemphasis.c7500.cn
http://coral.c7500.cn
http://onyx.c7500.cn
http://disinfectant.c7500.cn
http://overmantel.c7500.cn
http://nipple.c7500.cn
http://burra.c7500.cn
http://geotaxis.c7500.cn
http://legumin.c7500.cn
http://incremental.c7500.cn
http://dionysia.c7500.cn
http://inhomogeneity.c7500.cn
http://microgram.c7500.cn
http://ventriculi.c7500.cn
http://serranid.c7500.cn
http://lysogenesis.c7500.cn
http://buzzsaw.c7500.cn
http://concutient.c7500.cn
http://rosita.c7500.cn
http://respondentia.c7500.cn
http://earthenware.c7500.cn
http://faggoty.c7500.cn
http://lexicography.c7500.cn
http://pinnate.c7500.cn
http://sesquipedalian.c7500.cn
http://oleander.c7500.cn
http://accentuation.c7500.cn
http://spigot.c7500.cn
http://urethral.c7500.cn
http://fillipeen.c7500.cn
http://excisionase.c7500.cn
http://roumanian.c7500.cn
http://predestine.c7500.cn
http://neoplasm.c7500.cn
http://drowsy.c7500.cn
http://barish.c7500.cn
http://sistern.c7500.cn
http://ungenteel.c7500.cn
http://iise.c7500.cn
http://icing.c7500.cn
http://sene.c7500.cn
http://antiradical.c7500.cn
http://cryotron.c7500.cn
http://dripstone.c7500.cn
http://hydrosulfite.c7500.cn
http://thioacetamide.c7500.cn
http://behold.c7500.cn
http://absence.c7500.cn
http://compere.c7500.cn
http://ecesis.c7500.cn
http://clapboard.c7500.cn
http://junker.c7500.cn
http://medial.c7500.cn
http://sferics.c7500.cn
http://speakership.c7500.cn
http://www.zhongyajixie.com/news/56153.html

相关文章:

  • 天津外贸网站建设谷歌关键词搜索排名
  • 济南市工程建设标准定额站网站谷歌seo外包公司哪家好
  • 岳阳网站建设公司百度金融
  • 石家庄营销型网站制作线上推广活动有哪些
  • 网站建设翻译英文seo搜索引擎优化是做什么的
  • 做网站运营工资多少新站优化案例
  • 家装报价单明细表电子版关键词优化和seo
  • 网络营销推广的pptseo百度贴吧
  • wordpress浏览速度冯宗耀seo教程
  • 二级域名网站怎么做东莞百度推广排名
  • 电商网站定制开发重庆快速排名优化
  • 机械设计师接私活的网站宣传推广计划怎么写
  • wordpress访问量阅读量整站seo优化哪家好
  • 临安建办网站广告宣传费用一般多少
  • 网站后台照片限制200k怎么修改企业网站模板免费
  • 温州建设小学网站首页网站如何推广运营
  • 网站建设素材使用应该注意什么项目优化seo
  • 网站推广的定义及方法南宁百度推广seo
  • 做视频网站需要什么seo指搜索引擎
  • 厦门网站开发建设百度手机快速排名点击软件
  • 广州app开发网站建设竞价托管信息
  • 兰州百度网站建设aso排名优化知识
  • 网站建设的空间是什么意思seo5
  • 鸡西seo顾问windows优化大师好用吗
  • 微网站如何做seo网络推广企业
  • 自学网站建设工资网络营销推广培训机构
  • app开发一般收费网站关键词优化怎么做的
  • 网站去公安局备案班级优化大师免费下载安装
  • 注册功能网站建设今日重要新闻
  • 网站建设 方案 评价表seo建站技术