Java 如何使用spring并行执行多个数据库调用?
我正在努力提高spring应用程序的性能,它调用大约8-10个查询并结合起来,这将需要大约15到120秒,这取决于它查询的数据量,我建议在Java8中采用一种完全的未来/未来方式。但是,我一直停留在主线程不等待异步线程完成的位置。下面是到目前为止我已经实现的代码 我已经考虑使用“Future”和ThreadPoolExecutor返回并实现它,并且有一个线程等待ThreadPoolExecutor中生成的可调用线程完成以返回数据 问题:在java中实现CompletableFuture,主线程等待线程池中的所有线程完成,然后再将数据返回给客户机的简单方法是什么 InvokeCallable.javaJava 如何使用spring并行执行多个数据库调用?,java,spring,multithreading,java-8,completable-future,Java,Spring,Multithreading,Java 8,Completable Future,我正在努力提高spring应用程序的性能,它调用大约8-10个查询并结合起来,这将需要大约15到120秒,这取决于它查询的数据量,我建议在Java8中采用一种完全的未来/未来方式。但是,我一直停留在主线程不等待异步线程完成的位置。下面是到目前为止我已经实现的代码 我已经考虑使用“Future”和ThreadPoolExecutor返回并实现它,并且有一个线程等待ThreadPoolExecutor中生成的可调用线程完成以返回数据 问题:在java中实现CompletableFuture,主线程等
package net.sampleSpring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
@Component
public class InvokeCallable {
@Autowired
private ApplicationContext context;
// @Autowired
// @Qualifier("threadPoolExecutor")
// private ThreadPoolTaskExecutor executorThreadPool;
public void invokeCallables() throws InterruptedException, ExecutionException {
List<CompletableFuture<Integer>> lst = new ArrayList<>();
CallableOne callableOne = context.getBean(CallableOne.class);
CallableTwo callableTwo = context.getBean(CallableTwo.class);
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
try {
return callableOne.call();
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
);
CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
return callableTwo.call();
} catch (Exception e) {
e.printStackTrace();
}
return "1";
}
}
);
CompletableFuture.allOf(completableFuture1, completableFuture2).thenApply(
i -> {
System.out.println("Completed running the futures");
System.out.println("future 1" + completableFuture1.join().toString());
System.out.println("future 2" + completableFuture2.join().toLowerCase());
return i;
}
);
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.concurrent.Callable;
@Component
@Scope("prototype")
public class CallableTwo {
public String call() throws Exception {
Thread.sleep(2000);
return "1000";
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class CallableOne {
public Integer call() throws Exception {
Thread.sleep(2000);
return 1;
}
}
/* ItemValue Web service
*
*/
@Path("/")
@Service
public class sampleSpringResource {
@Inject
private InvokeCallable callable;
private static final Logger LOG = LogManager.getLogger();
@GET
@Path("/changeme/")
@Produces(APPLICATION_JSON)
public Response getsampleSpring() throws ExecutionException, InterruptedException {
System.out.print("In getSampleSpring()..");
try {
callable.invokeCallables();
System.out.println("returning from the result");
return LOG.exit(Response.status(Response.Status.OK).entity("Success").build());
} catch (DataAccessException ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
} catch (Exception ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
}
}
}
CallableOne.java
package net.sampleSpring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
@Component
public class InvokeCallable {
@Autowired
private ApplicationContext context;
// @Autowired
// @Qualifier("threadPoolExecutor")
// private ThreadPoolTaskExecutor executorThreadPool;
public void invokeCallables() throws InterruptedException, ExecutionException {
List<CompletableFuture<Integer>> lst = new ArrayList<>();
CallableOne callableOne = context.getBean(CallableOne.class);
CallableTwo callableTwo = context.getBean(CallableTwo.class);
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
try {
return callableOne.call();
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
);
CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
return callableTwo.call();
} catch (Exception e) {
e.printStackTrace();
}
return "1";
}
}
);
CompletableFuture.allOf(completableFuture1, completableFuture2).thenApply(
i -> {
System.out.println("Completed running the futures");
System.out.println("future 1" + completableFuture1.join().toString());
System.out.println("future 2" + completableFuture2.join().toLowerCase());
return i;
}
);
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.concurrent.Callable;
@Component
@Scope("prototype")
public class CallableTwo {
public String call() throws Exception {
Thread.sleep(2000);
return "1000";
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class CallableOne {
public Integer call() throws Exception {
Thread.sleep(2000);
return 1;
}
}
/* ItemValue Web service
*
*/
@Path("/")
@Service
public class sampleSpringResource {
@Inject
private InvokeCallable callable;
private static final Logger LOG = LogManager.getLogger();
@GET
@Path("/changeme/")
@Produces(APPLICATION_JSON)
public Response getsampleSpring() throws ExecutionException, InterruptedException {
System.out.print("In getSampleSpring()..");
try {
callable.invokeCallables();
System.out.println("returning from the result");
return LOG.exit(Response.status(Response.Status.OK).entity("Success").build());
} catch (DataAccessException ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
} catch (Exception ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
}
}
}
sampleSpringResource.java使用restful服务调用InvokeCallable.java的代码
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import javax.inject.Inject;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Response;
import java.util.concurrent.ExecutionException;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static org.json.XMLTokener.entity;
/* ItemValue Web service
*
*/
@Path("/")
@Service
public class sampleSpringResource {
@Inject
private InvokeCallable callable;
private static final Logger LOG = LogManager.getLogger();
@GET
@Path("/changeme/")
@Produces(APPLICATION_JSON)
public Response getsampleSpring() throws ExecutionException, InterruptedException {
callable.invokeCallables();
}
}
感谢Abhijit指向正确的位置。我以以下方式实现了它 samplespringresourcc.java
package net.sampleSpring.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;
@Component
public class InvokeCallable {
@Autowired
private ApplicationContext context;
// @Autowired
// @Qualifier("threadPoolExecutor")
// private ThreadPoolTaskExecutor executorThreadPool;
public void invokeCallables() throws InterruptedException, ExecutionException {
List<CompletableFuture<Integer>> lst = new ArrayList<>();
CallableOne callableOne = context.getBean(CallableOne.class);
CallableTwo callableTwo = context.getBean(CallableTwo.class);
CompletableFuture<Integer> completableFuture1 = CompletableFuture.supplyAsync(new Supplier<Integer>() {
@Override
public Integer get() {
try {
return callableOne.call();
} catch (Exception e) {
e.printStackTrace();
}
return 1;
}
}
);
CompletableFuture<String> completableFuture2 = CompletableFuture.supplyAsync(new Supplier<String>() {
@Override
public String get() {
try {
return callableTwo.call();
} catch (Exception e) {
e.printStackTrace();
}
return "1";
}
}
);
CompletableFuture.allOf(completableFuture1, completableFuture2).thenApply(
i -> {
System.out.println("Completed running the futures");
System.out.println("future 1" + completableFuture1.join().toString());
System.out.println("future 2" + completableFuture2.join().toLowerCase());
return i;
}
);
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import java.util.concurrent.Callable;
@Component
@Scope("prototype")
public class CallableTwo {
public String call() throws Exception {
Thread.sleep(2000);
return "1000";
}
}
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
@Component
@Scope("prototype")
public class CallableOne {
public Integer call() throws Exception {
Thread.sleep(2000);
return 1;
}
}
/* ItemValue Web service
*
*/
@Path("/")
@Service
public class sampleSpringResource {
@Inject
private InvokeCallable callable;
private static final Logger LOG = LogManager.getLogger();
@GET
@Path("/changeme/")
@Produces(APPLICATION_JSON)
public Response getsampleSpring() throws ExecutionException, InterruptedException {
System.out.print("In getSampleSpring()..");
try {
callable.invokeCallables();
System.out.println("returning from the result");
return LOG.exit(Response.status(Response.Status.OK).entity("Success").build());
} catch (DataAccessException ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
} catch (Exception ex) {
return LOG.exit(Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(new ServiceError(ErrorCode.INTERNAL_SERVER_ERROR, ex.getMessage())).build());
}
}
}
InvokeCallable
@Component
public class InvokeCallable {
@Autowired
private ApplicationContext context;
@Autowired
private CallableTwo callableTwo;
@Autowired
private CallableOne callableOne;
public void invokeCallables() throws Exception {
List<CompletableFuture<Integer>> lst = new ArrayList<>();
System.out.println("Callable one start " + new Date());
CompletableFuture<Integer> completableFuture1 = callableOne.call();
System.out.println("Callable one end " + new Date());
System.out.println("Callable two start " + new Date());
CompletableFuture<String> completableFuture2 = callableTwo.call();
System.out.println("Callable two end " + new Date());
CompletableFuture.allOf(completableFuture1, completableFuture2).join();
System.out.println("Completable future all end " + new Date());
}
}
@Component
@Scope("prototype")
public class CallableOne {
@Async
public CompletableFuture<Integer> call() throws Exception {
Thread.sleep(2000);
return CompletableFuture.completedFuture(1);
}
}
简单的谷歌搜索:@AbhijitSarkar谢谢,我会试试的。有些人怎么错过了。