在Feign客户端+ Spring Cloud中使用带有动态值的@Headers(Brixton RC2)

时间:2016-05-06 07:07:03

标签: spring spring-cloud spring-cloud-netflix

是否可以将动态值设置为标题?

@FeignClient(name="Simple-Gateway")
interface GatewayClient {
    @Headers("X-Auth-Token: {token}")
    @RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
        String getSessionId(@Param("token") String token);
    }

注册RequestInterceptor的实现会添加标头,但无法动态设置标头值

@Bean
    public RequestInterceptor requestInterceptor() {

        return new RequestInterceptor() {

            @Override
            public void apply(RequestTemplate template) {

                template.header("X-Auth-Token", "some_token");
            }
        };
    } 

我在github上发现了以下问题,其中一位评论者( lpborges )尝试使用@RequestMapping注释中的标题执行类似操作。

https://github.com/spring-cloud/spring-cloud-netflix/issues/288

亲切的问候

6 个答案:

答案 0 :(得分:42)

解决方案是使用@RequestHeader注释而不是假装特定注释

@FeignClient(name="Simple-Gateway")
interface GatewayClient {    
    @RequestMapping(method = RequestMethod.GET, value = "/gateway/test")
    String getSessionId(@RequestHeader("X-Auth-Token") String token);
}

答案 1 :(得分:2)

@RequestHeader对我不起作用。工作是什么:

@Headers("X-Auth-Token: {access_token}")
@RequestLine("GET /orders/{id}")
Order get(@Param("id") String id, @Param("access_token") String accessToken);

答案 2 :(得分:1)

我有这个例子,我使用@HeaderParam代替@RequestHeader:

import rx.Single;

import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;


@Consumes(MediaType.APPLICATION_JSON)
public interface  FeignRepository {

  @POST
  @Path("/Vehicles")
  Single<CarAddResponse> add(@HeaderParam(HttpHeaders.AUTHORIZATION) String authorizationHeader, VehicleDto vehicleDto);

}

答案 3 :(得分:0)

我使用@HeaderMap,因为如果您正在使用Open feign,这似乎非常方便。通过这种方式,您可以动态传递标题键和值。

@Headers({"Content-Type: application/json"})
public interface NotificationClient {

    @RequestLine("POST")
    String notify(URI uri, @HeaderMap Map<String, Object> headers, NotificationBody body);
}

答案 4 :(得分:0)

@ HeaderMap,@ Header和@Param不适用于我,下面是在有多个标题参数要通过FeignClient传递时使用@RequestHeader的解决方案

@PostMapping("/api/channelUpdate")
EmployeeDTO updateRecord(
      @RequestHeader Map<String, String> headerMap,
      @RequestBody RequestDTO request);

调用代理的代码如下:

Map<String, String> headers = new HashMap<>();
headers.put("channelID", "NET");
headers.put("msgUID", "1234567889");
ResponseDTO response = proxy.updateRecord(headers,requestDTO.getTxnRequest());

答案 5 :(得分:-1)

https://github.com/spring-cloud/spring-cloud-netflix/issues/760 https://github.com/OpenFeign/feign/#basics

17.3 Creating Feign Clients Manually
http://cloud.spring.io/spring-cloud-static/Dalston.SR4/single/spring-cloud.html#_creating_feign_clients_manually

POJO:

public class User...

服务:

@RestController
public class HelloController ...
    public User getUser(@RequestParam("name") String name) {
        User user = new User();
        user.setName(name + "[result]");
        System.out.println("name: " + name);
        return user;
    }
    ...

客户端:

public interface HelloClient {
    @RequestLine("POST /getUser?name={name}")
    User getUser(@Param("name") String name);
}

使用:

import feign.codec.Decoder;
import feign.codec.Encoder;
import feign.Client;
public class Demo {
    private HelloClient helloClient;
    @Autowired
    public Demo(Decoder decoder, Encoder encoder, Client client) {
        this.userAnotherService = Feign.builder().client(client)
                .encoder(encoder)
                .decoder(decoder)
                // for spring security
                .requestInterceptor(new BasicAuthRequestInterceptor("username", "password"))
                .target(UserAnotherService.class, "http://your-service-name");
    }
...
...method...
// output --> hello spring cloud![result]
System.out.println(helloClient.getUser("hello spring cloud!").getName());
...