Gateway网关

1.Gateway解决跨域问题

配置CorsWebFilter

@Configuration
public class CrossConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        // 创建跨域配置器
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 设置允许所有请求头
        corsConfiguration.addAllowedHeader("*");
        // 设置允许所有域名 (如:http://localhost:8080)
        corsConfiguration.addAllowedOrigin("*");
        // 设置允许所有请求方法 ==> GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE
        corsConfiguration.addAllowedMethod("*");
        // URL 映射 (如: /admin/**),允许所有路径请求进行跨域
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**",corsConfiguration);
        return new CorsWebFilter(source);
    }
}

配置文件application.properties

#设置路由id,自定义,唯一即可
spring.cloud.gateway.routes[0].id=service-cmn
#设置路由的uri,注册中心配置方式:lb是负载均衡,后面跟服务名称
spring.cloud.gateway.routes[0].uri=lb://service-cmn
#设置路由断言,判断请求是否符合路由规则的条件
spring.cloud.gateway.routes[0].predicates= Path=/*/cmn/**

2.全局过滤器GlobalFilter

处理一切进入网关的请求和微服务响应,需要自己写代码配置

通过全局过滤器可以实现对权限的统一校验,安全性验证等功能。

// 自定义配置类实现GlobalFilter接口,实现内部抽象方法:Mono<Void> filter
@Component
public class Filter implements GlobalFilter, Ordered {
    // 路径匹配器
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
         // 通过交换机获取请求体的请求路径
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        System.out.println("==="+path);

        //内部服务接口,不允许外部访问
        if(antPathMatcher.match("/**/inner/**", path)) {
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.XXXX);
            return response.setComplete();
        }else{
            return chain.filter(exchange); //放行
        }
    }
}

关于过滤器优先级的问题

一种方法是在类上添加@Order(int val)注解,val越小优先级越高

另一种方法是实现GlobalFilter的同时也实现Ordered接口,实现该接口的int getOrder();方法(return 一个值就行了)

public interface Ordered {
    int HIGHEST_PRECEDENCE = -2147483648;
    int LOWEST_PRECEDENCE = 2147483647;

    int getOrder();
}

  转载请注明: 流浪秃球计划 Gateway网关

 上一篇
线程并发 线程并发
一、进程:正在运行的程序。是程序的一次执行过程,或是正在运行的程序 二、线程进程的一个实体,一个进程可以拥有多个线程 单线程:同一个时刻,只允许执行一个线程 多线程:同一个时刻,允许执行多个线程 并发:同一时刻,多个任务交替执行,单核CPU
2022-12-23 Touko
下一篇 
缓存数据 缓存数据
一.作用Spring Cache 是一个非常优秀的缓存组件。自Spring 3.1起,提供了类似于@Transactional注解事务的注解Cache支持,且提供了Cache抽象,方便切换各种底层Cache(如:Redis) Spring
2022-11-19 Touko
  目录