腾讯微服务平台TSF学习笔记(二)--如何使用spring cloud zuul实现线上流量复制

需求提了n遍了,好好好,那这个需求就由我测试来做

1.在zuul端配置:
●假设provider-mirror是provider-demo的灰度应用

package com.tencent.tsf.msgw.zuul1.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

import org.slf4j.Logger;

public class TrafficCopyFilter extends ZuulFilter {
    private static final Logger LOG = LoggerFactory.getLogger(TrafficCopyFilter.class);

    private RestTemplate restTemplate = new RestTemplate();

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

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

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

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();

        // 检查请求是否是发送给服务A的
        if (request.getRequestURI().contains("/provider-demo")) {
            LOG.info("复制请求到mirror服务");
            // 将请求复制到服务B

            String param = request.getRequestURI().substring(request.getRequestURI().lastIndexOf("/") + 1); // 提取参数
            String bServiceUrl = "http://svcb host ip:port/echo/" + param; //这里写mirror服务的镜像地址,后期可从配置文件中读入
            HttpMethod method = HttpMethod.valueOf(request.getMethod());
            HttpHeaders headers = new HttpHeaders();

            Enumeration<String> headerNames = request.getHeaderNames();
            while (headerNames.hasMoreElements()) {
                String headerName = headerNames.nextElement();
                headers.add(headerName, request.getHeader(headerName));
            }

            HttpEntity<String> entity = new HttpEntity<>(headers);
            try {
                restTemplate.exchange(bServiceUrl, method, entity, Void.class);
            } catch (Exception e) {
                // 捕获异常,避免影响客户端
                LOG.error("复制请求到mirror服务失败: {}", e.getMessage());
            }
        }

        return null;
    }
}

配置类

package com.tencent.tsf.msgw.zuul1.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZuulConfig {

    @Bean
    public TrafficCopyFilter trafficCopyFilter() {
        return new TrafficCopyFilter();
    }
}

最后,我们会发现,通过zuul请求provider时,流量会被复制到provider-mirror

你可能感兴趣的:(微服务,学习,笔记)