设置Feign的Header信息(两种形式)

 在使用微服务SpringCloud全家桶组件Fegin的时候,我们在进行远程服务之间调用的同时,为了防止客户端劫持信息,我们需要将一些敏感信息添加到我们的Fegin头部(Header)当中,今天朋友问起,总结一下:那么工作中常见的方式有两种

1.在方法参数前面添加@RequestHeader注解

@PostMapping(value = "/getPersonDetail") 
public ServerResponse getPersonDetail(@RequestBody Map map,@RequestHeader(name = "id") String id);

   使用@RequestHeader(name = "id")可以传递动态header属性

 

2.实现RequestInterceptor接口,设置Header(所有的Fegin请求)

import org.springframework.context.annotation.Configuration; 
import org.springframework.web.context.request.RequestContextHolder; 
import org.springframework.web.context.request.ServletRequestAttributes; 
import feign.RequestInterceptor; 
import feign.RequestTemplate; 
@Configuration 
public class FeignConfiguration implements RequestInterceptor {    
        @Override    
        public void apply(RequestTemplate template) {      
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();       
                HttpServletRequest request = attributes.getRequest();        
                Enumeration headerNames = request.getHeaderNames();        
                if (headerNames != null) {            
                        while (headerNames.hasMoreElements()) {             
                                String name = headerNames.nextElement();              
                                String values = request.getHeader(name);             
                                template.header(name, values);            
                        }            
                }    
        } 
}


@Component
@FeignClient(value = "abc",fallback = abcServiceHystric.class ,configuration = FeignConfiguration.class) public interface AbcService { }

希望可以帮助到大家,也喜欢大家分享自己的想法嘻嘻

你可能感兴趣的:(微服务,springcloud,Springboot)