您现在的位置是:首页 > 学无止境 > Spring Cloud

spring cloud alibaba(8)基础-geteway路由全局过滤

贾继涛 2019-03-11 1099人围观

相关文章

 spring cloud alibaba(1)基础注册中心nacos

 spring cloud alibaba(2)基础-服务提供者

 spring cloud alibaba(3)基础-创建消费者

 spring cloud alibaba(4)基础-创建消费者(feign)

 spring cloud alibaba(5)基础-熔断器防止雪崩sentinel

 spring cloud alibaba(6)基础-Sentinel 控制台搭建

 spring cloud alibaba(7)基础-Spring Cloud Gateway网关

 spring cloud alibaba(8)基础-geteway路由全局过滤

 spring cloud alibaba(9)基础-nacos云配置服务-nacos-config

 spring cloud alibaba(10)基础-Nacos Config多环境配置


创建全局过滤器

实现 GlobalFilter, Ordered 接口并在类上增加 @Component 注解


1.AuthFilter.java

package com.jjt.hello.spring.cloud.gateway.filters;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
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.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import java.util.Map;
/**
 * 鉴权过滤器
 */
@Component
public class AuthFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getQueryParams().getFirst("token");
        if (token == null || token.isEmpty()) {
            ServerHttpResponse response = exchange.getResponse();
            // 封装错误信息
            Map<String, Object> responseData = Maps.newHashMap();
            responseData.put("code", 401);
            responseData.put("message", "非法请求");
            responseData.put("cause", "Token is empty");
            try {
                // 将信息转换为 JSON
                ObjectMapper objectMapper = new ObjectMapper();
                byte[] data = objectMapper.writeValueAsBytes(responseData);
                // 输出错误信息到页面
                DataBuffer buffer = response.bufferFactory().wrap(data);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                return response.writeWith(Mono.just(buffer));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return chain.filter(exchange);
    }
    /**
     * 设置过滤器的执行顺序
     * @return
     */
    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE;
    }
}


2.访问地址查看区别

http://127.0.0.1:9000/nacos-consumer-feign/c/hi?token=123456 

http://127.0.0.1:9000/nacos-consumer-feign/c/hi 


源码地址

 https://gitee.com/jiajitao/Spring-Cloud-Ali


您的支持