通过特定Web容器工厂TomcatServletWebServerFactory定制

1、Pom.xml文件



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    
    com.jane
    tralink
    0.0.1-SNAPSHOT
    tralink
    Demo project for Spring Boot

    
        1.8
        Greenwich.SR2
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    


2、Controller文件Test

package com.jane.tralink.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/test")
public class Test {

    @PostMapping("/hello")
    public String hello(HttpServletRequest request) {
        System.out.println( request.getHeader("traceid"));
        return "hello";
    }
}

3、自定义Web容易定制器

package com.jane.tralink.controller;

import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.stereotype.Component;

@Component
public class MyTomcatCustomize implements WebServerFactoryCustomizer {

    @Override
    public void customize(TomcatServletWebServerFactory factory) {
        //TraceValve 是实际的增加Header的类
        factory.addEngineValves(new TraceValve());
    }
}

4、TraceValve

package com.jane.tralink.controller;

import org.apache.catalina.Valve;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.valves.ValveBase;

import javax.servlet.ServletException;
import java.io.IOException;
import java.util.UUID;

public class TraceValve extends ValveBase {

    @Override
    public void invoke(Request request, Response response) throws IOException, ServletException {
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        request.getCoyoteRequest().getMimeHeaders().addValue("traceid").setString(uuid);

        Valve next = getNext();
        if(null == next) return;
        next.invoke(request, response);
    }
}

5、运行结果:http://127.0.0.1:8081/test/hello
SpringBoot-定制Web容器Tomcat,请求头增加traceid参数_第1张图片