springCloud之zuul路由网关

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/thqtzq/article/details/90700043

Zuul的主要功能是路由转发和过滤器,路由功能是微服务的一部分,比如/api/user转发到user服务,/api/shop转发到shop服务。zuul默认和ribbon结合实现了负载均衡的功能。
核心代码和配置如下:


eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul

#    zuul起到了路由的作用,以/api-a/ 开头的请求都转发给service-ribbon服务;
#     以/api-b/开头的请求都转发给service-feign服务
zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-ribbon
    api-b:
      path: /api-b/**
      serviceId: service-feign
/**
 *  路由网关(zuul)
 *  注解@EnableZuulProxy,开启zuul的功能
 */
@EnableZuulProxy
@EnableEurekaClient
@SpringBootApplication
public class ServiceZuulApplication {
    public static void main(String[] args) {
        SpringApplication.run(ServiceZuulApplication.class, args);
    }
}

在这里插入图片描述
zuul不仅只是路由,并且还能过滤,做一些安全验证。

package com.dalingjia.servicezuul;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * zuul不仅只是路由,并且还能过滤,做一些安全验证
 */
@Component
public class MyFilter extends ZuulFilter {

    private static Logger log = LoggerFactory.getLogger(MyFilter.class);


    /**
     * filterType:返回一个字符串代表过滤器的类型,在zuul中定义了四种不同生命周期的过滤器类型,具体如下:
     *      pre:路由之前
     *      routing:路由之时
     *      post: 路由之后
     *      error:发送错误调用
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }

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

    /**
     * 这里可以写逻辑判断,是否要过滤,本文true,永远过滤
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * 过滤器的具体逻辑。可用很复杂,包括查sql,nosql去判断该请求到底有没有权限访问
     * @return
     */
    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));

        Object accessToken = request.getParameter("token");
        if(accessToken == null) {
            log.warn("token is empty");
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(401);
            try {
                ctx.getResponse().getWriter().write("token is empty");
            }catch (Exception e){

            }
            return null;
        }

        log.info("ok");
        return null;
    }
}

这时访问:http://localhost:8769/api-a/hi?name=forezp ;网页显示:

token is empty

访问 http://localhost:8769/api-a/hi?name=forezp&token=22 ;网页显示:

hi forezp,i am from port:8762

参考博客:https://blog.csdn.net/forezp/article/details/69939114

展开阅读全文

没有更多推荐了,返回首页