SpringBoot多线程查询实战-查询库中所有数据多线程实现
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
@Service
public class MultiThreadQueryService {
@Autowired
private YourRepository yourRepository;
public List<YourEntity> queryAllDataMultiThread(int pageSize) {
ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建线程池
List<Future<List<YourEntity>>> futures = new ArrayList<>();
List<YourEntity> allData = new ArrayList<>();
int totalPages = (int) yourRepository.count() / pageSize + 1;
for (int i = 0; i < totalPages; i++) {
int page = i;
Future<List<YourEntity>> future = executorService.submit(new Callable<List<YourEntity>>() {
@Override
public List<YourEntity> call() throws Exception {
PageRequest pageRequest = PageRequest.of(page, pageSize);
Page<YourEntity> pageData = yourRepository.findAll(pageRequest);
return pageData.getContent();
}
});
futures.add(future);
}
// 合并所有线程的结果
for (Future<List<YourEntity>> future : futures) {
try {
allData.addAll(future.get());
} catch (Exception e) {
e.printStackTrace();
}
}
executorService.shutdown(); // 关闭线程池
return allData;
}
}
这段代码使用了Spring Data JPA的YourRepository
来查询数据,并且使用了Java的ExecutorService
来实现多线程查询。通过创建一个固定大小的线程池,并提交多个Callable任务来分页查询数据库中的数据,最后合并所有线程的结果。这种方式可以有效提高数据查询的效率,尤其是在处理大量数据时。
评论已关闭