微服务架构--之Gateway(跨域问题/限流结果自定义)总结

网关跨域配置:

当我们基于Ajax技术访问网关时,需要在网关层面进行跨域设计,例如:

1.java代码实现跨域问题

基于过滤器方式进行配置,并且将过滤优先级设置高一些

package com.jt.config;

import org.springframework.context.annotation.Bean;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;

//@Configuration
public class CorsFilterConfig {
    @Bean
    public CorsWebFilter corsWebFilter(){
        //1.构建基于url方式的跨域配置
        UrlBasedCorsConfigurationSource source= new UrlBasedCorsConfigurationSource();
        //2.进行跨域配置
        CorsConfiguration config=new CorsConfiguration();
        //2.1允许所有ip:port进行跨域
        config.addAllowedOrigin("*");
        //2.2允许所有请求头跨域
        config.addAllowedHeader("*");
        //2.3允许所有请求方式跨域:get,post,..
        config.addAllowedMethod("*");
        //2.4允许携带有效cookie进行跨域
        config.setAllowCredentials(true);
        source.registerCorsConfiguration("/**",config);
        return new CorsWebFilter(source);
    }
}

2.gateway配置文件中实现跨域问题解决

spring:
  cloud:
    gateway:
      globalcors: #跨域配置
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedHeaders: "*"
            allowedMethods: "*"
            allowCredentials: true

网关自定义限流结果--返回给前端数据自定义

package com.jt.config;

import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
import com.alibaba.fastjson.JSON;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class GatewayConfig {
    public GatewayConfig(){
        //自定义限流结果
        GatewayCallbackManager.setBlockHandler((
                    serverWebExchange, throwable) ->{
                //构建响应数据
                Map map=new HashMap<>();
                map.put("state",429);
                map.put("message","two many request");
                //基于alibaba 的fastjson将对象转换为json
                String jsonStr= JSON.toJSONString(map);//fastjson
                //创建Mono对象,将结果响应到客户端
                return ServerResponse.ok().body(Mono.just(jsonStr),
                        String.class);//String.class表示响应数据类型
            //WebFlux
        });
    }
}

你可能感兴趣的:(微服务,ajax,java)