How to custom QueryMapEncoder when using annotation @QueryMap to construct a query in Feign

燕烨
2023-12-01

When we use Feign to call downstream services, we may need to pass several query parameters in URL. If there are just one or two query parameters, we can use annotation @Param to pass the value of the quey parameters.

@RequestLine("GET /repos?owner={owner}&repo={repo}")
List<Contributor> getContributors(@Param("owner") String owner, @Param("repo") String repo);

But if there are many query parameters, the code will look a little complicated.

@RequestLine("GET /repos?owner={owner}&repo={repo}&branches={branches}&commitStartDate={commitStartDate}&commitEndDate={commitEndDate}")
List<Contributor> getContributors(@Param("owner") String owner,
                                  @Param("repo") String repo,
                                  @Param("branches") String branches,
                                  @Param("commitStartDate") String commitStartDate,
                                  @Param("commitEndDate") String commitEndDate);

One solution is to use the annotation @QueryMap to construct a query that uses the contents of the map as its query parameters. But it is not so friendly and not readable.

@RequestLine("GET /repos")
List<Contributor> getContributors(@QueryMap Map<String, Object> queryMap);

Another solution is to generate the query parameters from a POJO object using a QueryMapEncoder.

@RequestLine("GET /repos")
List<Contributor> getContributors(@QueryMap GitHub gitHub);
public class GitHub
{
    private String owner;
    private String repository;
    private List<String> branchs;
    private Date commitStartDate;
    private Date commitEndDate;

    public GitHub(String owner, String repository, List<String> branchs, Date commitStartDate, Date commitEndDate) {
        this.owner = owner;
        this.repository = repository;
        this.branchs = branchs;
        this.commitStartDate = commitStartDate;
        this.commitEndDate = commitEndDate;
    }
}

Reference:

https://github.com/OpenFeign/feign

 类似资料:

相关阅读

相关文章

相关问答