I love the java series --- [certification -Feign interceptors between micro-services]

1.feign usage scenarios

Note: Who initiated the request to feign, feign interceptors on the definition of who is who, the purpose of the interceptor is to transfer token.

2. Use these steps:

(1) create interceptor

Changgou_common create a service interceptor com.changgou.interceptor.FeignInterceptor, and all the first document data added to the header Feign micro service request again, as follows:

@Component
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate requestTemplate) {

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();

        if (requestAttributes!=null){

            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request!=null){
                Enumeration<String> headerNames = request.getHeaderNames();
                if (headerNames!=null){
                    while (headerNames.hasMoreElements()){
                        String headerName = headerNames.nextElement();
                        if (headerName.equals("authorization")){
                            String headerValue = request.getHeader(headerName);
                            requestTemplate.header(headerName,headerValue);//核心代码
                        }
                    }
                }
            }
        }
        }
}

2) Change the changgou_order_web startup class, add the interceptor statement (feign who initiated the request, put the interceptor on who feign above)

@Bean
public FeignInterceptor feignInterceptor(){
    return new FeignInterceptor();
}

 

Guess you like

Origin www.cnblogs.com/hujunwei/p/11426005.html