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

springcloud3 GateWay章节-Nacos+gateway(跨域,filter过滤等5

一 常用工具类

1.1 结构

 1.2 跨域

@Configuration
public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}

1.3 filter过滤

1.验证制定请求,是否可以通过。

package com.atguigu.gateway.filter;import com.google.gson.JsonObject;
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.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;import java.nio.charset.StandardCharsets;
import java.util.List;/*** <p>* 全局Filter,统一处理会员登录与外部不允许访问的服务* </p>** @author qy* @since 2019-11-21*/
@Component
public class AuthGlobalFilter implements GlobalFilter, Ordered {private AntPathMatcher antPathMatcher = new AntPathMatcher();@Overridepublic Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {ServerHttpRequest request = exchange.getRequest();String path = request.getURI().getPath();//谷粒学院api接口,校验用户必须登录if(antPathMatcher.match("/api/**/auth/**", path)) {List<String> tokenList = request.getHeaders().get("token");if(null == tokenList) {ServerHttpResponse response = exchange.getResponse();return out(response);} else {
//                Boolean isCheck = JwtUtils.checkToken(tokenList.get(0));
//                if(!isCheck) {ServerHttpResponse response = exchange.getResponse();return out(response);
//                }}}//内部服务接口,不允许外部访问if(antPathMatcher.match("/**/inner/**", path)) {ServerHttpResponse response = exchange.getResponse();return out(response);}return chain.filter(exchange);}@Overridepublic int getOrder() {return 0;}private Mono<Void> out(ServerHttpResponse response) {JsonObject message = new JsonObject();message.addProperty("success", false);message.addProperty("code", 28004);message.addProperty("data", "鉴权失败");byte[] bits = message.toString().getBytes(StandardCharsets.UTF_8);DataBuffer buffer = response.bufferFactory().wrap(bits);//response.setStatusCode(HttpStatus.UNAUTHORIZED);//指定编码,否则在浏览器中会中文乱码response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");return response.writeWith(Mono.just(buffer));}
}

1.4 异常的处理

1.4.1 异常定义

1.异常配置类

package com.ljf.mscloud.handler;import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.result.view.ViewResolver;import java.util.Collections;
import java.util.List;/*** 覆盖默认的异常处理** @author yinjihuan**/
@Configuration
@EnableConfigurationProperties({ServerProperties.class, ResourceProperties.class})
public class ErrorHandlerConfig {private final ServerProperties serverProperties;private final ApplicationContext applicationContext;private final ResourceProperties resourceProperties;private final List<ViewResolver> viewResolvers;private final ServerCodecConfigurer serverCodecConfigurer;public ErrorHandlerConfig(ServerProperties serverProperties,ResourceProperties resourceProperties,ObjectProvider<List<ViewResolver>> viewResolversProvider,ServerCodecConfigurer serverCodecConfigurer,ApplicationContext applicationContext) {this.serverProperties = serverProperties;this.applicationContext = applicationContext;this.resourceProperties = resourceProperties;this.viewResolvers = viewResolversProvider.getIfAvailable(Collections::emptyList);this.serverCodecConfigurer = serverCodecConfigurer;}@Bean@Order(Ordered.HIGHEST_PRECEDENCE)public ErrorWebExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes) {JsonExceptionHandler exceptionHandler = new JsonExceptionHandler(errorAttributes,this.resourceProperties,this.serverProperties.getError(),this.applicationContext);exceptionHandler.setViewResolvers(this.viewResolvers);exceptionHandler.setMessageWriters(this.serverCodecConfigurer.getWriters());exceptionHandler.setMessageReaders(this.serverCodecConfigurer.getReaders());return exceptionHandler;}}

2.异常响应类

package com.ljf.mscloud.handler;import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.*;import java.util.HashMap;
import java.util.Map;/*** 自定义异常处理** <p>异常时用JSON代替HTML异常信息<p>** @author yinjihuan**/
public class JsonExceptionHandler extends DefaultErrorWebExceptionHandler {public JsonExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties,ErrorProperties errorProperties, ApplicationContext applicationContext) {super(errorAttributes, resourceProperties, errorProperties, applicationContext);}/*** 获取异常属性*/@Overrideprotected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {Map<String, Object> map = new HashMap<>();map.put("success", false);map.put("code", 20005);map.put("message", "网关失败");map.put("data", null);return map;}/*** 指定响应处理方法为JSON处理的方法* @param errorAttributes*/@Overrideprotected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);}/*** 根据code获取对应的HttpStatus* @param errorAttributes*/@Overrideprotected int getHttpStatus(Map<String, Object> errorAttributes) {return 200;}
}

1.4.2 测试

1.将调用的微服务都关闭,只保留网关服务。

http://localhost:7004/payment/nacos/222

 

http://www.lryc.cn/news/141361.html

相关文章:

  • Nodejs+Typescript+Eslint+Prettier+Husky项目构建
  • 轻松正确使用代理IP
  • SpringCloud教程 | 第二篇: 服务消费者(rest+ribbon)
  • lintcode 961 · 设计日志存储系统预【系统设计题 中等】
  • windows下Qt、MinGW、libmodbus源码方式的移植与使用
  • leetcode做题笔记104. 二叉树的最大深度
  • 【Luniux】解决Ubuntu外接显示器不显示的问题
  • 【C++初阶】模拟实现list
  • 三维模拟推演电子沙盘虚拟数字沙盘开发教程第13课
  • flask中GET和POST的区别
  • 基于Spring Boot的游泳馆管理系统的设计与实现(Java+spring boot+MySQL)
  • git冲突处理(已commit但忘pull的情况)
  • 嵌入式设备应用开发(发现需求和提升价值)
  • Redis Replication
  • 软件研发CI/CD流水线图解
  • 代码随想录第五十九天
  • “yarn“、“npm“、“cnpm“和“pnpm“的区别
  • 批量将txt文件转化为excel文件
  • StringIndexOutOfBoundsException: String index out of range: 458
  • R语言主成分分析
  • 单片机学习-蜂鸣器如何发出声音
  • 利用敏捷开发工具实现敏捷项目管理的实践经验分享
  • 代码随想录训练营 贪心02
  • Linux安装NVM(简洁版)
  • vue 弹出框 引入另一个vue页面
  • 为Android做一个ShowModal窗口
  • 神经网络的工作原理
  • Pandas数据分析教程-数据清洗-字符串处理
  • Nginx 核心配置
  • yum命令安装程序