1. 程式人生 > >spring cloud(四、路由閘道器)

spring cloud(四、路由閘道器)

Zuul的主要功能是路由轉發和過濾器。路由功能是微服務的一部分,比如/api/user轉發到到user服務,/api/shop轉發到到shop服務。zuul預設和Ribbon結合實現了負載均衡的功能。

一、路由功能

1.建立service-zuul專案

2.引入Eureka Server和Zuul依賴

3.入口類加上註解

@SpringBootApplication
@EnableZuulProxy
@EnableEurekaClient
@EnableDiscoveryClient
public class ServiceZuulApplication {

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

4.設定配置檔案

eureka:
  client:
    serviceUrl:
      defaultZone: http://localhost:8761/eureka/
server:
  port: 8769
spring:
  application:
    name: service-zuul
zuul:
  routes:
    api-a:
      path: /api-a/**
      serviceId: service-feign

啟動相應的專案,訪問http://localhost:8769/api-a/hi?name=forezp 

二、服務過濾

設定過濾配置:

@Component
public class MyFilter extends ZuulFilter {
    private static Logger log = LoggerFactory.getLogger(MyFilter.class);

    /**
     * pre:路由之前
     * routing:路由之時
     * post: 路由之後
     * error:傳送錯誤呼叫
     */
    @Override
    public String filterType() {
        return "pre";
    }
    /**
     * filterOrder:過濾的順序
     */
    @Override
    public int filterOrder() {
        return 0;
    }
    /**
     * shouldFilter:這裡可以寫邏輯判斷,是否要過濾,本文true,永遠過濾。
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }
    /**
     * run:過濾器的具體邏輯。可用很複雜,包括查sql,nosql去判斷該請求到底有沒有許可權訪問。
     */
    @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

訪問http://localhost:8769/api-a/hi?name=forezp&token=22

原始碼:https://github.com/lrn-white/springcloud