Feign动态设置Header

Feign调用接口

/**
 * @author Liangzhifeng
 * date: 2018/9/13
 */
public interface UserInfoFeignClient {

    /**
     * 根据token获取用户信息
     * @param token
     * @return
     */
    @RequestMapping(value = "/user/info/1.0", method = RequestMethod.POST)
    Object getUserInfoByToken(@RequestParam("token") String token);
}

/**
 * @author Liangzhifeng
 * date: 2018/9/15
 */
@Component
public class AuthorityConfig {

    /**
     * 授权信息Header的key
     */
    public static final String OAUTH_KEY = "token";

    /**
     * 授权信息Header的值的前缀
     */
    public static final String OAUTH_VALUE_PREFIX = "Bearer ";

    @Autowired
    private Client client;

    public UserInfoFeignClient userInfoFeignClient(String token) {
        UserInfoFeignClient authorityServiceLoginInvoker = Feign.builder().client(client)
                .encoder(new GsonEncoder())
                .decoder(new GsonDecoder())
                .contract(new SpringMvcContract())
                .requestInterceptor(template -> template.header(OAUTH_KEY, OAUTH_VALUE_PREFIX + token))
                .target(UserInfoFeignClient.class, GlobalConstant.AUTHORITY_SERVICE_LINK);
        return authorityServiceLoginInvoker;
    }
}

真实接口调用

    @Autowired
    private AuthorityConfig authorityConfig;

    /**
     * 根据token获取用户信息
     *
     * @param token 用户登录的授权token
     * @return 用户信息JSON
     */
    public Object getUserInfo(String token) {
        try {
            Object userInfo = authorityConfig.userInfoFeignClient(token).getUserInfoByToken(token);
            return userInfo;
        } catch (Exception e) {
            log.info("获取用户信息异常", e);
            return null;
        }
    }

你可能感兴趣的:(Feign动态设置Header)