如何正确实现Page接口分页,用PageImpl 自定义分页

/**
* Constructor of {@code PageImpl}.
*
* @param content the content of this page, must not be {@literal null}.
* @param pageable the paging information, must not be {@literal null}.
* @param total the total amount of items available. The total might be adapted considering the length of the content
* given, if it is going to be the content of the last page. This is in place to mitigate inconsistencies.
*/
public PageImpl(List<T> content, Pageable pageable, long total)
 
 
content:当前页的记录。
total:全部记录数
也就是用PageImpl实现Page接口的时候,不能把数据全取回来放入content,得按分页的size放入。而最后一个参数须要记录的是全部数据的计数。
 
 
public Page<ESIndexObject> getAllESIndex(Pageable pageable) {
        String strQuery = "/_cat/indices?v&h=uuid,health,status,index,docsCount,storeSize,cds&s=cds:desc&format=json";
        Request request = new Request("GET", strQuery);
        try {
            Response response = restClient.performRequest(request);
            String responseBody = EntityUtils.toString(response.getEntity());
            ObjectMapper mapper = new ObjectMapper();
       List<ESIndexObject> list = mapper.readValue(responseBody,new TypeReference<List<ESIndexObject>>(){}); int totalElements = list.size(); if(pageable==null) { pageable = PageRequest.of(0,10); } int fromIndex = pageable.getPageSize()*pageable.getPageNumber(); int toIndex = pageable.getPageSize()*(pageable.getPageNumber()+1); if(toIndex>totalElements) toIndex = totalElements;
       //若是list的内容取回后基本不变化,能够考虑放入类对象变量里或者其余缓存里,而后判断list是否可用,不用每次都去取list,适合取数的时候没法真分页只能伪分页状况。            //相似取mysql数据库的状况,由于数据取数自己支持分页,因此list的数据每次都取当前页就能够,可是须要先要计算全部记录数,而后传入totalElements变量
            List<ESIndexObject> indexObjects = list.subList(fromIndex,toIndex);#获取当前页数据
            Page<ESIndexObject> page = new PageImpl<>(indexObjects,pageable,totalElements);
            return page;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
相关文章
相关标签/搜索