/**
* 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;
}
}