http网关/转发 - spring boot zuul方案

一、方案概述

        普通restTemplate & httpclient 包转发时,阻塞线程,性能低下,需要使用非阻塞方式,可选zuul & asynchttpclient,本文讨论zuul方案

二、引入包

        注意:spring boot & cloud的版本必须一致, 否则会出现兼容异常

    
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.2.RELEASE
        
    

    
    
        
            org.springframework.cloud
            spring-cloud-starter-netflix-zuul
        
    

    
    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                Greenwich.RELEASE
            
        
    

三、配置转发规则

# application.properties
#==============================================
# zuul
#==============================================
zuul.routes.path1.path=/path1/admin/**
zuul.routes.path1.url=http://192.168.232.125:8080/admin/
zuul.routes.path2.path=/path2/admin/**
zuul.routes.path2.url=http://192.168.232.126:8080/admin/
zuul.routes.path3.path=/path3/admin/**
zuul.routes.path3.url=http://192.168.232.127:8080/admin/

yml配置

# application.yml
zuul:
	routes:
		path1:
			path:/path1/admin/**
			url:http://192.168.232.125:8080/admin/
		path2:
			path:/path2/admin/**
			url:http://192.168.232.126:8080/admin/
		path3:
			path:/path3/admin/**
			url:http://192.168.232.127:8080/admin/

四、添加自定义过滤器

        过滤器功能可选- 如果不需要过滤啥操作, 可以不添加,服务正常转发

@Component
public class TokenFilter extends ZuulFilter {

    private static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

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

    @Override
    public Object run() throws ZuulException {

        
        RequestContext rc = RequestContext.getCurrentContext();
        HttpServletRequest request = rc.getRequest();
        String method = request.getMethod();
        String path = request.getRequestURI();
        String ip = request.getRemoteAddr();
        Map> mq = rc.getRequestQueryParams();

        String tk = mq.get("token");
        if(tk == null){
	        rc.setSendZuulResponse(false);
	        rc.setResponseStatusCode(401);
	        rc.setResponseBody("{status:401, message:\"未登录\"}");
	        rc.getResponse().setContentType("application/json;charset=UTF-8");
        } else {
        	// TODO
        }
        return null;
    }
}

五、配置zuul启动

// - 启动类添加@EnableZuulProxy

@SpringBootApplication
@EnableZuulProxy
public class Application {
	xxxxx
}

六、测试

http://localhost:8080/path1/admin/hello

http://localhost:8080/path2/admin/hello

http://localhost:8080/path3/admin/hello

你可能感兴趣的:(SpringCloud,SpringBoot,JAVA,spring,boot,java,后端)