当前位置:   article > 正文

GateWay具体的使用!!!

GateWay具体的使用!!!

一、全局Token过滤器

在Spring Cloud Gateway中,实现全局过滤器的目的是对所有进入系统的请求或响应进行统一处理,比如添加日志、鉴权等。下面是如何创建一个全局过滤器的基本步骤:

步骤1: 创建过滤器类

首先,你需要创建一个实现了GatewayFilter接口或者继承AbstractGatewayFilterFactory类的过滤器类。这里以实现GatewayFilter接口为例,创建一个全局token过滤器。

  1. /*
  2. * Copyright (c) 2020, 2024, All rights reserved.
  3. *
  4. */
  5. package com.by.filter;
  6. import cn.hutool.core.collection.CollUtil;
  7. import cn.hutool.core.util.ObjUtil;
  8. import cn.hutool.jwt.JWTValidator;
  9. import cn.hutool.jwt.signers.JWTSignerUtil;
  10. import lombok.extern.slf4j.Slf4j;
  11. import org.springframework.beans.factory.annotation.Value;
  12. import org.springframework.cloud.gateway.filter.GatewayFilterChain;
  13. import org.springframework.cloud.gateway.filter.GlobalFilter;
  14. import org.springframework.http.HttpStatus;
  15. import org.springframework.http.server.RequestPath;
  16. import org.springframework.http.server.reactive.ServerHttpRequest;
  17. import org.springframework.http.server.reactive.ServerHttpResponse;
  18. import org.springframework.stereotype.Component;
  19. import org.springframework.web.server.ServerWebExchange;
  20. import reactor.core.publisher.Mono;
  21. import java.util.List;
  22. /**
  23. * <p>Project: spring-could-alibaba-root - TokenFilter</p>
  24. * <p>Powered by scl On 2024-04-26 17:41:24</p>
  25. * <p>描述:<p>
  26. *
  27. * @author 孙臣龙 [1846080280@qq.com]
  28. * @version 1.0
  29. * @since 17
  30. */
  31. @Component
  32. @Slf4j
  33. public class TokenFilter implements GlobalFilter {
  34. @Value("${cn.smart.tokenx.key}")
  35. private String key;
  36. //设置白名单
  37. private static List<String> whiteList = CollUtil.newArrayList("/api/user/login", "/api/user/register");
  38. @Override
  39. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  40. ServerHttpRequest request = exchange.getRequest();
  41. ServerHttpResponse response = exchange.getResponse();
  42. //判断如果包含白名单中的内容就放行
  43. RequestPath path = request.getPath();
  44. if (whiteList.contains(path)) {
  45. return chain.filter(exchange);
  46. }
  47. //从请求头中获取token
  48. List<String> tokens = request.getHeaders().get("token");
  49. if (ObjUtil.isEmpty(tokens)) {
  50. //设置状态码
  51. log.debug("token为空");
  52. response.setStatusCode(HttpStatus.UNAUTHORIZED);
  53. return response.setComplete();
  54. }
  55. //获取token
  56. String token = tokens.get(0);
  57. if (ObjUtil.isEmpty(token)) {
  58. log.debug("token为空");
  59. response.setStatusCode(HttpStatus.UNAUTHORIZED);
  60. return response.setComplete();
  61. }
  62. //全面增强
  63. Boolean b = false;
  64. try {
  65. JWTValidator.of(token).validateAlgorithm(JWTSignerUtil.hs256(key.getBytes())).validateDate();
  66. b = true;
  67. } catch (Exception e) {
  68. e.printStackTrace();
  69. }
  70. if (!b) {
  71. log.debug("token无效");
  72. response.setStatusCode(HttpStatus.UNAUTHORIZED);
  73. return response.setComplete();
  74. }
  75. return chain.filter(exchange);
  76. }
  77. }

步骤2: 注册全局过滤器

为了让Spring Cloud Gateway应用识别并使用这个过滤器,你通常需要在配置类中注册它。但是,由于我们使用了@Component注解,Spring会自动扫描并注册该Bean。

使用@Component或下面代码,二选一。

  1. @Configuration
  2. public class FilterConfig {
  3. @Bean
  4. public TokenFilter tokenFilter() {
  5. return new TokenFilter();
  6. }
  7. }

二、局部过滤器接口耗时

1.找规律

局部过滤器命名规则 XXXGatewayFilterFactory, 必须以GatewayFilterFactory结尾。

  1. /* 注意名称约定
  2. * AddRequestHeaderGatewayFilterFactory 配置的时候写的是 AddRequestHeader
  3. * AddRequestParameterGatewayFilterFactory 配置的时候写的是 AddRequestParameter
  4. * LogTimeGatewayFilterFactory 配置的时候写什么? LogTime
  5. * */
  6. spring.cloud.gateway.routes[0].filters[0] = LogTime=moreThen,500

2.接口耗时过滤器

  1. /*
  2. * Copyright (c) 2020, 2024, All rights reserved.
  3. *
  4. */
  5. package com.by.filter;
  6. import lombok.extern.slf4j.Slf4j;
  7. import org.springframework.cloud.gateway.filter.GatewayFilter;
  8. import org.springframework.cloud.gateway.filter.GatewayFilterChain;
  9. import org.springframework.cloud.gateway.filter.factory.AbstractNameValueGatewayFilterFactory;
  10. import org.springframework.cloud.gateway.filter.factory.SetRequestHeaderGatewayFilterFactory;
  11. import org.springframework.cloud.gateway.support.GatewayToStringStyler;
  12. import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
  13. import org.springframework.http.server.RequestPath;
  14. import org.springframework.http.server.reactive.ServerHttpRequest;
  15. import org.springframework.stereotype.Component;
  16. import org.springframework.util.MultiValueMap;
  17. import org.springframework.web.server.ServerWebExchange;
  18. import reactor.core.publisher.Mono;
  19. /**
  20. * <p>Project: spring-could-alibaba-root - LogTimeGatewayFilterFactory</p>
  21. * <p>Powered by scl On 2024-04-26 20:01:04</p>
  22. * <p>描述:<p>
  23. *
  24. * @author 孙臣龙 [1846080280@qq.com]
  25. * @version 1.0
  26. * @since 17
  27. */
  28. @Component
  29. @Slf4j
  30. //局部过滤器命名规则 XXXGatewayFilterFactory, 必须以GatewayFilterFactory结尾。还需要配置文件中进行配置
  31. public class LogTimeGatewayFilterFactory extends AbstractNameValueGatewayFilterFactory {
  32. public LogTimeGatewayFilterFactory() {
  33. }
  34. public GatewayFilter apply(final AbstractNameValueGatewayFilterFactory.NameValueConfig config) {
  35. return new GatewayFilter() {
  36. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  37. ServerHttpRequest request = exchange.getRequest();
  38. //获取配置文件中设置的参数
  39. String value = ServerWebExchangeUtils.expand(exchange, config.getValue());
  40. //将参数转换为int类型
  41. Integer time = Integer.valueOf(value);
  42. //设置开始时间
  43. long startTime = System.currentTimeMillis();
  44. //执行过滤器,并且记录请求耗时,通过调用then方法(类似于vue的then方法),记录请求耗时
  45. return chain.filter(exchange).then(Mono.fromRunnable(() -> {
  46. long endTime = System.currentTimeMillis();
  47. long costTime = endTime - startTime;
  48. if (costTime > time*1000) {
  49. log.debug("请求地址:" + request.getPath() + ",请求耗时:" + costTime + "ms");
  50. }
  51. }));
  52. }
  53. public String toString() {
  54. return GatewayToStringStyler.filterToStringCreator(LogTimeGatewayFilterFactory.this).append(config.getName(), config.getValue()).toString();
  55. }
  56. };
  57. }
  58. }

3.如何使用

三、全链路跟踪TraceId日志

1.创建全局过滤器,在请求头上带入traceId参数,穿透到下游服务.

  1. /*
  2. * Copyright (c) 2020, 2024, All rights reserved.
  3. *
  4. */
  5. package com.by.filter;
  6. import cn.hutool.core.util.IdUtil;
  7. import cn.hutool.core.util.ObjectUtil;
  8. import org.springframework.cloud.gateway.filter.GatewayFilterChain;
  9. import org.springframework.cloud.gateway.filter.GlobalFilter;
  10. import org.springframework.http.server.reactive.ServerHttpRequest;
  11. import org.springframework.stereotype.Component;
  12. import org.springframework.web.server.ServerWebExchange;
  13. import reactor.core.publisher.Mono;
  14. import java.util.List;
  15. /**
  16. * <p>Project: spring-could-alibaba-root - TraceIdFilter</p>
  17. * <p>Powered by scl On 2024-04-26 21:10:19</p>
  18. * <p>描述:<p>
  19. *
  20. * @author 孙臣龙 [1846080280@qq.com]
  21. * @version 1.0
  22. * @since 17
  23. */
  24. @Component
  25. public class TraceIdFilter implements GlobalFilter {
  26. @Override
  27. public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
  28. //获取请求头
  29. ServerHttpRequest request = exchange.getRequest();
  30. //判断请求头中有没有traceId
  31. List<String> list = request.getHeaders().get("traceId");
  32. //如果存在就不做处理
  33. if (ObjectUtil.isNotEmpty(list)){
  34. return chain.filter(exchange);
  35. }
  36. //不存在就生成一个traceId
  37. String treaId= IdUtil.simpleUUID();
  38. //在请求头中添加一个traceId
  39. ServerHttpRequest request1 = request.mutate().header("tracedId", treaId).build();
  40. //因为请求头发生了变化,所以需要重新构建一个ServerWebExchange
  41. ServerWebExchange exchange1 = exchange.mutate().request(request1).build();
  42. return chain.filter(exchange1);
  43. }
  44. }

2.MDC原理

当请求来时生成一个traceId放在ThreadLocal里,然后打印时去取就行了。但在不改动原有输出语句的前提下自然需要日志框架的支持了。

MDC 介绍​ MDC(Mapped Diagnostic Context,映射调试上下文)是 log4j 和 logback 提供的一种方便在多线程条件下记录日志的功能。MDC 可以看成是一个与当前线程绑定的Map,可以往其中添加键值对。MDC 中包含的内容可以被同一线程中执行的代码所访问。当前线程的子线程会继承其父线程中的 MDC 的内容。当需要记录日志时,只需要从 MDC 中获取所需的信息即可。MDC 的内容则由程序在适当的时候保存进去。对于一个 Web 应用来说,通常是在请求被处理的最开始保存这些数据。

简而言之,MDC就是日志框架提供的一个InheritableThreadLocal,项目代码中可以将键值对放入其中,然后使用指定方式取出打印即可。

3.下游服务如何使用全链路跟踪Id

3.1在你要跟踪的模块中配置TraceId 过滤器

  1. /*
  2. * Copyright (c) 2020, 2024, All rights reserved.
  3. *
  4. */
  5. package com.by.filter;
  6. import cn.hutool.core.util.IdUtil;
  7. import org.slf4j.MDC;
  8. import org.springframework.util.StringUtils;
  9. import javax.servlet.*;
  10. import javax.servlet.annotation.WebFilter;
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.io.IOException;
  13. /**
  14. * <p>Project: spring-could-alibaba-root - TraceIdFliter</p>
  15. * <p>Powered by scl On 2024-04-26 21:20:15</p>
  16. * <p>描述:<p>
  17. *
  18. * @author 孙臣龙 [1846080280@qq.com]
  19. * @version 1.0
  20. * @since 17
  21. */
  22. @WebFilter
  23. public class TraceIdFliter implements Filter {
  24. @Override
  25. public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
  26. HttpServletRequest httpRequest = (HttpServletRequest) request;
  27. String traceId = httpRequest.getHeader("traceId");
  28. if (StringUtils.isEmpty(traceId)) {
  29. traceId = IdUtil.fastSimpleUUID();
  30. }
  31. MDC.put("traceId", traceId);
  32. try {
  33. chain.doFilter(request, response);
  34. } finally {
  35. MDC.clear();
  36. }
  37. }
  38. }

3.2 启动类开启ServletComponentScan扫描。

  1. @SpringBootApplication
  2. @ServletComponentScan
  3. public class OpenApp {
  4. public static void main(String[] args) {
  5. SpringApplication.run(OpenApp.class, args);
  6. }
  7. }

3.3 配置文件配置日志输出格式

  1. ##日志输出格式
  2. logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} %clr(%-5level) %clr([%X{traceId}]) %clr(${PID:-}) --- %clr(%logger{50}) - %m%n
  3. 

4.Openfeign扩展

  1. @Component
  2. public class OpenFeignRequestInterceptor implements RequestInterceptor {
  3. @Override
  4. public void apply(RequestTemplate requestTemplate) {
  5. String traceId = MDC.get(TraceIdFilter.MDC_TRACE_ID);
  6. requestTemplate.header(TraceIdFilter.MDC_TRACE_ID, traceId);
  7. }
  8. }
  9. 

5.附(Kibana日志图标)



声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/528657
推荐阅读
相关标签
  

闽ICP备14008679号