SpringCloud 服务间调用添加header

一.使用restTemplete

1.主类中创建

@SpringBootApplication
@EnableDiscoveryClient
@EnableApolloConfig
@Slf4j
@MapperScan(basePackages = {"com.netposa.**.mapper"})
@EnableFeignClients(basePackages = {"com.netposa"})
public class AppFaceApplication {
    
	public static void main(String[] args) {
		ConfigurableApplicationContext context = new SpringApplicationBuilder()
				.sources(AppFaceApplication.class)
				.main(AppFaceApplication.class)
				.listeners(new ApplicationPidFileWriter())
				.run(args);
		
		log.info("----AppFace Service Start----");
		context.registerShutdownHook();
	}

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

 2.调用类



@Slf4j
@Component
public class AlarmFeignRest {

    @Autowired
     private RestTemplate restTemplate;

    @Autowired
    private AlarmFeignClient alarmFeignClient;

    @Value("${disposition.service.addr}")
    private String dispositionip;

    //private String url = "http://172.16.34.203/gateway/disposition-service/netposa/api/public/v1/alarm-message/info";

    private String prifix = "http://";

     private String intefaceName ="/netposa/api/public/v1/alarm-message/info";

    private static ObjectMapper mapper = new ObjectMapper();

    /**
     * 报警信息
     * @param featureSearchParam
     * @return
     */
    public ResponseData alarmInfo (AlarmListModel alarmListModel, HttpServletRequest request){
        HttpHeaders httpHeaders = HeadsUtils.initializationRequestHeads(request);
        String value ="";
        try {
            value = mapper.writeValueAsString(alarmListModel);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }

        HttpEntity<String> entity = new HttpEntity(value,httpHeaders);

        ResponseEntity<ResponseData> exchange = restTemplate.exchange(prifix+dispositionip+intefaceName, HttpMethod.POST, entity, ResponseData.class);
        return exchange.getBody();

     


    }



}

3.head添加信息

public class HeadsUtils {

    public static HttpHeaders initializationRequestHeads(HttpServletRequest httpServletRequest) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        String token = httpServletRequest.getHeader(Constant.TOKEN);
        if (StringUtils.isNotEmpty(token)) {
            headers.add(Constant.TOKEN, token);
        }

        String tokenId = httpServletRequest.getHeader(Constant.TOKEN_ID);
        if(StringUtils.isEmpty(tokenId)) {
            tokenId = httpServletRequest.getAttribute(Constant.TOKEN_ID) + "";
        }
        if (StringUtils.isNotEmpty(tokenId)) {
            List<String> cookies = new ArrayList<>();
            cookies.add(Constant.ACCESS_TOKEN + "=" + tokenId);
            cookies.add(Constant.TOKEN_ID + "=" + tokenId);
            headers.add(HttpHeaders.COOKIE, httpServletRequest.getHeader(HttpHeaders.COOKIE));
            headers.add(Constant.TOKEN_ID, tokenId);
        }

        headers.add("auth","false");

        return headers;
    }
}

二. 使用feign

1.在feign配置类中添加头信息


@Configuration
public class NoAuthFeignConfiguration {
    @Bean
    public Feign.Builder feignBuilder(){
        return Feign.builder().requestInterceptor(new RequestInterceptor() {
            @Override
            public void apply(RequestTemplate requestTemplate) {
                requestTemplate.header("auth", "false");
                ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes();
                if (attributes != null) {
                    HttpServletRequest request = attributes.getRequest();
                    String token= request.getHeader("tokenId");
                    if (!StringUtils.isEmpty(token)) {
                        requestTemplate.header(Constant.TOKEN_ID, token);
                    }
                    requestTemplate.header(HttpHeaders.COOKIE, request.getHeader(HttpHeaders.COOKIE));
                }

            }
        });
    }


}

2.使用

/**
*disposition-service是微服务的名称,/netposa/api/public/v1/alarm-message/info是接口名
*方法参数和被调用者一致
*/
@FeignClient(name = "disposition-service", configuration = NoAuthFeignConfiguration.class)
public interface AlarmFeignClient {

    /**
     * 报警信息
     * @param featureSearchParam
     * @return
     */
    @RequestMapping(value = "/netposa/api/public/v1/alarm-message/info", method = RequestMethod.POST)
    public ResponseData alarmInfo(@RequestBody AlarmListModel alarmListModel);

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值