一、使用@RequestHeader添加请求头

package com.supcon.mare.tankinfo.service.feign;

import com.alibaba.fastjson.JSONObject;
import com.supcon.mare.tankinfo.constant.Constants;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

/**
 * @author: zhaoxu
 * @description:
 */
@FeignClient(name = Constants.ARE_CODE_GENERATOR)
@Component
public interface CodeGeneratorService {
    /**
     * 生成编码
     *
     * @param params
     * @param token
     * @return
     */
    @PostMapping("code/generateCode")
    String codeGenerator(@RequestBody JSONObject params, @RequestHeader(name = "token", required = true) String token);
}

使用方式:

package com.supcon.mare.tankinfo.util;

import com.alibaba.fastjson.JSONObject;
import com.supcon.mare.common.util.exception.InterfaceException;
import com.supcon.mare.tankinfo.constant.Constants;
import com.supcon.mare.tankinfo.service.feign.CodeGeneratorService;
import com.supcon.mare.tankinfo.service.feign.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.HashMap;
import java.util.Map;

/**
 * @author: zhaoxu
 * @description:
 */
@Component
public class FeignRequestUtil {
    @Autowired
    CodeGeneratorService codeGeneratorService;

    @Autowired
    OrderService orderService;

    /**
     * 生成编码
     *
     * @param code
     * @param datas
     * @return
     */
    public String codeGenerator(String code, Map<String, Object> datas) {
        JSONObject params = new JSONObject();
        params.put("code", code);
        params.put("datas", datas);
        String result = codeGeneratorService.codeGenerator(params, ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest().getHeader("token"));
        JSONObject resultObj = JSONObject.parseObject(result);
        if (Constants.SUCCESS_CODE.equals(resultObj.get(Constants.CODE).toString())) {
            //获取返回json中的result中的data数据
            return JSONObject.parseObject(JSONObject.parseObject(result).get("result").toString()).get("data").toString();
        } else {
            throw new InterfaceException(Integer.valueOf(resultObj.get("code").toString()), resultObj.get("msg").toString());
        }
    }
}

二、统一添加请求头

添加configuration = FeignConfiguration.class如下:

package com.supcon.mare.tankinfo.service.feign;

import com.alibaba.fastjson.JSONObject;
import com.supcon.mare.tankinfo.constant.Constants;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;

/**
 * @author: zhaoxu
 * @description:
 */
@FeignClient(name = Constants.ARE_CODE_GENERATOR, configuration = FeignConfiguration.class)
@Component
public interface CodeGeneratorService {
    /**
     * 生成编码
     *
     * @param params
     * @param token
     * @return
     */
    @PostMapping("code/generateCode")
    String codeGenerator(@RequestBody JSONObject params, @RequestHeader(name = "token", required = true) String token);
}

FeignConfiguration.class内容如下:

package com.supcon.mare.tankinfo;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

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

/**
 * @author: zhaoxu
 * @description:
 */
@Configuration
public class FeignConfiguration implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate template) {
   //开启线程共享     
   RequestContextHolder.setRequestAttributes(RequestContextHolder.getRequestAttributes(),true);
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 对消息头进行配置
        Enumeration<String> headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                String name = headerNames.nextElement();
                String values = request.getHeader(name);
                template.header(name, values);
            }
        }
        // 对请求体进行配置
       /* Enumeration<String> bodyNames = request.getParameterNames();
        StringBuffer body = new StringBuffer();
        if (bodyNames != null) {
            while (bodyNames.hasMoreElements()) {
                String name = bodyNames.nextElement();
                String values = request.getParameter(name);
                body.append(name).append("=").append(values).append("&");
            }
        }
        if (body.length() != 0) {
            body.deleteCharAt(body.length() - 1);
            template.body(body.toString());
        }*/
    }

}


*.yml配置文件添加如下内容:*

hystrix:
  command:
    default:
      coreSize: 100
      execution:
        timeout:
          enabled: true
        isolation:
          strategy: SEMAPHORE
          thread:
            # 请求超时
            timeoutInMilliseconds: 60000
          semaphore:
            # 降级
            maxConcurrentRequests: 1000
      circuitBreaker:
        # 设置在回路被打开,拒绝请求到再次尝试请求并决定回路是否继续打开的时间。
        sleepWindowInMilliseconds: 5000
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐