0

应用程序属性

zuul.routes.commonservice.path=/root/path/commonservice/**
zuul.routes.commonservice.service-id=commonservice

zuul.routes.customer.path=/root/path/customer/**
zuul.routes.customer.service-id=customer

zuul.routes.student.path=/root/path/student/**
zuul.routes.student.service-id=student 

下面是我的自定义过滤器

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.openreach.gateway.common.constant.CommonConstant;

import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Component
public class HeaderFilter extends ZuulFilter {

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

    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
        RequestContext context = RequestContext.getCurrentContext();

        HttpSession httpSession = context.getRequest().getSession();
        String idOrEmail = context.getRequest().getHeader("coustom");

        if (httpSession.getAttribute("someAttributes") == null) {
            if (idOrEmail != null) {
                //call the common-service and get details and set it first
                //then call the customer service with common-service details
            } else {
                //call the customer service
            }

        } else {
            log.info("data excits");
            // routrs the request to the backend with the excisting data details
        }

        context.addZuulResponseHeader("Cookie", "JSESSIONID=" + httpSession.getId());


        return null;
    }
}

我正在使用带有 zuul 的功能区负载平衡器。我的问题是我应该如何首先调用公共服务?我需要我的所有请求来检查标头值,然后调用实际的服务端点。

4

1 回答 1

0

首先,使用 @LoadBalanced 限定符创建负载平衡的 RestTemplate bean。

@LoadBalanced
@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

并将豆子注入过滤器

@Autowired
RestTemplate restTemplate;

然后你可以通过restTemplate的方法得到结果,如下所示

String result = restTemplate.postForObject("http://commonservice/url", object, String.class);

参考:http ://cloud.spring.io/spring-cloud-static/spring-cloud.html#_spring_resttemplate_as_a_load_balancer_client

于 2017-09-14T07:57:58.370 回答