码迷,mamicode.com
首页 > 编程语言 > 详细

SpringCloud过滤filter

时间:2019-12-20 12:02:35      阅读:81      评论:0      收藏:0      [点我收藏+]

标签:print   port   pat   url   lex   校验   mem   网关   stc   

目录

技术图片

 

 配置文件 application.yml

eureka:
  client:
    service-url:
      defaultZone: http://localhost:8001/eureka
server:
  port: 9001
spring:
  application:
    name: zuul
##配置zuul网关
zuul:
  routes:
    api-a:
      path: /member-zuul/**
      service-id: memeber-service
    api-b:
      path: /order-zuul/**
      service-id: order-service

 MyZuulFilter类

package com.cloud.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@Component
public class MyZuulFilter extends ZuulFilter {
    /**
     * 过滤类型
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * 请求过滤顺序
     * @return
     */
    @Override
    public int filterOrder() {
        return 0;
    }

    /**
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取token参数
        RequestContext rc = RequestContext.getCurrentContext();
        HttpServletRequest request = rc.getRequest();

        String token = request.getParameter("token");
        if(token!=null){
            return null;
        }
        //表示不进行路由
        rc.setSendZuulResponse(false);
        rc.setResponseStatusCode(401);

        try {
            rc.getResponse().setContentType("text/html;charset=utf-8");
            rc.getResponse().getWriter().write("没有传递正确参数,请校验后重试~");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

启动类

package com.cloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @EnableEurekaClient @SpringBootApplication @EnableZuulProxy public class StartZuul { public static void main(String[] args) { SpringApplication.run(StartZuul.class,args); } }

效果

1、

技术图片

 

2、

技术图片

SpringCloud过滤filter

标签:print   port   pat   url   lex   校验   mem   网关   stc   

原文地址:https://www.cnblogs.com/dabrk/p/12071843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!