spring-cloud傳遞分頁查詢

服務(wù)提供者使用Pageable傳遞分頁請求, 使用Page<T>傳遞分頁結(jié)果
在接口中加入Pageable對象, mvc會接收如下參數(shù): (所有參數(shù)均為可選項(xiàng))

  • Integer page
    頁碼, 第一頁為0
  • Integer size
    每頁數(shù)據(jù)量
  • List<String> sort
    排序規(guī)則,字符串格式是 property[, direction], 例如 "datetime, DESC", 可以使用多值參數(shù)傳遞多個排序

可以使用@PageableDefault表明默認(rèn)參數(shù)

@GetMapping("/countries")
public Page<Country> listCountry(@RequestParam(required = false) String continent,
                                 @PageableDefault(page = 0, size = 10) Pageable pageable) {

如果想讓swagger識別Pageable對象, 需要加入以下配置:

/**
 * swagger不會自動解析Pageable, 需要加入以下配置
 */
@Configuration
public static class SpringDataConfiguration {
    @Bean
    public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) {
        return new AlternateTypeRuleConvention() {
            @Override
            public int getOrder() {
                return Ordered.HIGHEST_PRECEDENCE;
            }

            @Override
            public List<AlternateTypeRule> rules() {
                return newArrayList(AlternateTypeRules.newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class)));
            }
        };
    }

    @ApiModel
    @Data
    static class Page {
        @ApiModelProperty(position = 0, value = "頁碼,第一頁為0")
        private Integer page;

        @ApiModelProperty(position = 1, value = "每頁的數(shù)據(jù)量")
        private Integer size;

        @ApiModelProperty(position = 2, value = "排序字段,可以是多個, 格式為\"{屬性}[,{方向}]\"", example = "createDatetime, DESC")
        private List<String> sort;
    }
}

使用RestTemplate訪問的時候, 無法解析Page或者PageImpl對象, 報錯:

Can not construct instance of org.springframework.data.domain.Page: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

一個解決方法是繼承一個帶默認(rèn)構(gòu)造函數(shù)的具體類:

public class RestPageImpl<T> extends PageImpl<T> {

    @JsonCreator(mode = JsonCreator.Mode.PROPERTIES)
    public RestPageImpl(@JsonProperty("content") List<T> content,
                        @JsonProperty("number") int page,
                        @JsonProperty("size") int size,
                        @JsonProperty("totalElements") long total) {
        super(content, new PageRequest(page, size), total);
    }

    public RestPageImpl(List<T> content, Pageable pageable, long total) {
        super(content, pageable, total);
    }

    public RestPageImpl(List<T> content) {
        super(content);
    }

    public RestPageImpl() {
        super(new ArrayList<T>());
    }
}

并使用這個具體類來解析:

ResponseEntity<RestPageImpl<Country>> response = restTemplate.exchange(searchCountries, new ParameterizedTypeReference<RestPageImpl<Country>>() {
        });

通過FeignClient傳遞Pageable還沒有找到特別好的辦法 ,選擇直接傳遞剛才提到的幾個參數(shù)(page,size, sort):

@GetMapping("/countries")
public RestPageImpl<Country> searchCountries(@RequestParam(required = false, name = "continent") String continent,
                                             @RequestParam(required = false, name = "page") Integer page,
                                             @RequestParam(required = false, name = "size") Integer size,
                                             @RequestParam(required = false, name = "sort") List<String> sort

另外FeignClient也是不能解析Page接口, 也是繼承一個具體類

調(diào)用端拆包Pageable:

@GetMapping("/search")
public Page<Country> listCountry(@RequestParam(required = false) String continent,
                                 @PageableDefault(page = 0, size = 10) Pageable pageable) {

    Page<Country> asia = countryService.searchCountries(continent, pageable.getPageNumber(), pageable.getPageSize(), convert(pageable.getSort()));
    return asia;
}
default List<String> convert(Sort sort) {
    if (sort == null) {
        return null;
    }

    Iterator<Sort.Order> iterator = sort.iterator();

    List<String> sortList = Stream.generate(sort.iterator()::next)
            .map(order -> order.getProperty() + "," + order.getDirection())
            .collect(Collectors.toList());

    return sortList;
}

測試代碼項(xiàng)目見 https://gitee.com/liuxy9999/mytest-spring-cloud

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,628評論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語法,類相關(guān)的語法,內(nèi)部類的語法,繼承相關(guān)的語法,異常的語法,線程的語...
    子非魚_t_閱讀 34,740評論 18 399
  • 1、通過CocoaPods安裝項(xiàng)目名稱項(xiàng)目信息 AFNetworking網(wǎng)絡(luò)請求組件 FMDB本地數(shù)據(jù)庫組件 SD...
    陽明AI閱讀 16,211評論 3 119
  • Hello!大家好~~星星王子——《生日書》又與你見面啦!★★這周我們來研究5月21日—5月27日這七天當(dāng)中出生的...
    璞學(xué)苑閱讀 1,283評論 0 0

友情鏈接更多精彩內(nèi)容