如何正确实现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 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 list = mapper.readValue(responseBody,new TypeReference>(){}); 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 indexObjects = list.subList(fromIndex,toIndex);#获取当前页数据 Page page = new PageImpl<>(indexObjects,pageable,totalElements); return page; } catch (IOException e) { e.printStackTrace(); return null; } }

 

 

转载于:https://www.cnblogs.com/asker009/p/10188041.html

你可能感兴趣的:(如何正确实现Page接口分页,用PageImpl 自定义分页)