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:
当使用Feign调用下游服务时,可能需要在URL中传递多个查询参数。如果参数较少,可以使用@Param注解传递。但参数多时,代码会变得复杂。一种解决方案是使用@QueryMap从映射中构造查询参数,但这种方式不够友好且可读性差。另一种更好的方式是通过QueryMapEncoder从POJO对象生成查询参数,提高代码的可读性和组织性。
5046

被折叠的 条评论
为什么被折叠?



