注意点
1.不要添加web依赖,否则报错
org.springframework.cloud spring-cloud-starter-gatewaycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoverycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-configcom.alibaba.cloud spring-cloud-starter-alibaba-sentinelorg.springframework.boot spring-boot-starter-actuatorcom.alibaba.cloud spring-cloud-alibaba-sentinel-gateway
server: port: 9000 spring: application: name: sca-resource-gateway cloud: nacos: discovery: server-addr: localhost:8848 config: server-addr: localhost:8848 file-extension: yml gateway: discovery: locator: enabled: true routes: - id: router01 uri: lb://sca-resource predicates: - Path=/sca/resource/upload/** filters: - StripPrefix=1 - id: router02 uri: lb://sca-auth predicates: - Path=/auth/oauth/** #微服务架构下,需要令牌 filters: - StripPrefix=1 globalcors: #跨域配置 corsConfigurations: '[/**]': allowedOrigins: "*" allowedHeaders: "*" allowedMethods: "*" allowCredentials: true sentinel: #限流设计 transport: dashboard: localhost:8180 eager: true
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); } }
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) ->{ //构建响应数据 Mapmap=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 }); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)