Filter in spring cloud Zuul

Keywords: Spring JSON Google

1. Import dependency information. Since Zuul depends on feign and hystrix, you need to import the corresponding package

<!--Add to Eureka Client dependency-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

<!--Feign Declarative service call-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

<!--hystrix-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-hystrix-dashboard</artifactId>
    <version>1.4.0.RELEASE</version>
</dependency>

<!--integration zuul-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
</dependency>

 

2. Add @ EnableZuulProxy annotation to the main program

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
public class ServerGatewayApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServerGatewayApplication.class, args);
    }
}

 

There are four kinds of filters in zuul: pre, route, error, post.

 

filterType(): the return value of the method is used to execute one of the four above.

filterOrder(): filter sorting. Customize the order of filter execution. The larger the value is, the later it will be executed. The smaller the value is, the earlier it will be executed

shouldFilter(): used to control whether the current filter executes

run():filter logic

package com.ooyhao.cloud.servergateway.filter;

import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.ooyhao.cloud.servergateway.api.ApiResult;
import com.ooyhao.cloud.servergateway.exception.NoAccountException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @ClassName LoginFilter
 * @Author ouYang
 * @Date 2019/4/29 23:13
 * @Description Describe the role of this class
 * @Version 2.0
 */
@Component
public class LoginFilter extends ZuulFilter {

    private Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    //Four types: pre,routing,error,post
    //pre: mainly used in the routing mapping stage to find the routing mapping table
    //Routing: the specific routing and forwarding filter is called in the routing router when forwarding specific requests
    //Error: once the previous filter fails, the error filter will be called.
    //post: the filter will be called only after routing and error are run. It is in the last stage
    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    //Customize the order of filter execution. The larger the value, the later the execution, and the smaller the value, the earlier the execution
    @Override
    public int filterOrder() {
        return -1;
    }

    //If the control filter is not effective, you can write a string of logic to control it
    //Whether to execute the filter? true means to filter
    @Override
    public boolean shouldFilter() {
        //Get Request object
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String token = request.getParameter("token");
        logger.info("----------< token:{} >----------",token);
        if (token.equals("123456")){
            return false;
        }
        return true;
    }

    //Perform filtering logic
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        try {
            System.out.println("Certified filter");
            int i = 1/0;

        }catch (Exception e){
            System.out.println("e:"+e);
            context.setSendZuulResponse(false);//Indicates that the corresponding service is no longer called
            context.setResponseStatusCode(400);//Return status code of browser
            ApiResult apiResult = new ApiResult();
            apiResult.setCode(403);
            apiResult.setMessage("user name does not exist");
            apiResult.setSuccess(false);
            apiResult.setObj("account no found");
            Gson gson = new Gson();
            String json = gson.toJson(apiResult);
            response.setCharacterEncoding("utf8");
            response.setContentType("application/json;charset=UTF-8");//Set UTF8 and return in json format
            context.setResponseBody(json);
//            throw new NoAccountException(e,"account no found",403, "user name does not exist");
//            return null;
        }
        return null;
    }
}

 

Generally, preFilter is used for authentication and permission. At this time, you need to return data to inform the client whether to access and log in with permission. There are two ways:

1. Set the data returned to the front end through response in the filter

If you use response to return directly, subsequent filter s will not be executed.

2. Throw the corresponding exception information in the filter, use the same exception handling mechanism, receive it through the implementation of ErrorController, and return the corresponding data to inform the front end.

If you use the ErrorController to receive, subsequent error and post filters will execute.

 

------------------------------------------------

Pay attention to Xiaobian WeChat public number for more resources

Posted by davidjam on Mon, 18 Nov 2019 09:35:34 -0800