简体   繁体   English

如何与 CompletableFuture 一起使用 SpringBoot 实现宁静服务

[英]How to work with CompletableFuture with SpringBoot for restful service

I am facing trouble to understand how an async method works in SpringBoot.我在理解 SpringBoot 中异步方法的工作方式时遇到了麻烦。

Consider I am implementing a micro-service to get the Current, In-process or SoldOff Property of a user or All, depending on the query parameter from the user.考虑我正在实现一个微服务来获取用户或所有的 Current、In-process 或 SoldOff 属性,具体取决于来自用户的查询参数。 I am calling two methods which calls sql scripts to give me the answer.我正在调用两种调用 sql 脚本的方法来给我答案。 I want to run those methods Asynchronously as it can take time.我想异步运行这些方法,因为这可能需要时间。

Example:示例:

@Service
public class PropertyService {

  public PropertyVO getPropertySummary() {

        CompletableFuture<List<Property>> currentProperty = null;
        CompletableFuture<List<Property>> soldProperty = null;
        CompletableFuture<List<Property>> inProcessProperty = null;

        CompletableFuture<List<Property>> allProperty = null;

        if(status.equals("ALL")) {

            allProperty = propertyDAO.getAllProperty(userId);

        }else {

            String[] statuses = status.split(",");

            for (String st : statuses) {

                if (st.equals("CURRENT")) {

                    currentProperty = propertyDAO.getCurrentProperty(userId);

                } else if (st.equals("SOLD")) {

                    soldProperty = propertyDAO.getSoldProperty(userId);

                } else if (st.equals("IN-Process")) {

                    inProcessProperty = propertyDAO.getInProcessProperty(userId);
                }
            }

            // Do I need this? How would it work when user just needs CURRENT and SOLD. Will it get stuck on IN-PROCESS?
            // CompletableFuture.allOf(currentProperty,soldProperty,inProcessProperty).join();
        }

        // Will it wait here for the above methods to run?
        List<Property> allPropertyList = getResult(allProperty);

        List<Property> currentPropertyList = getResult(currentProperty);
        List<Property> soldPropertyList = getResult(soldProperty);
        List<Property> inProcessPropertyList = getResult(inProcessProperty);

        ..... return Object Property
  }  


  private List<Property> getResult(final CompletableFuture<List<Property>> completableFuture) {

        if(completableFuture == null) {
            return Lists.newArrayList();
        }

        return completableFuture.get(30,TIMEUNIT.SEC);
    }

}  

@Repository
class PropertyRepository {

 @Async
 @Transactional(readOnly = true)
 public CompletableFuture<List<Property>> getCurrentProperty(int userId) {

     String query = sqlRetriever.getQueryByKey("SQL_GET_CURRENT_PROPERTY");

     return CompletableFuture.completedFuture(getNamedParameterJdbcTemplate().query(query,new PropertyMapper()));
}    


@SpringBootApplication
@EnableAsync
public class SpringBootApp {

    /**
     * The entry point into the application.
     *
     * @param args
     */
    public static void main(String[] args) {
        SpringApplication.run(SpringBootApp.class, args).close();
    }

    @Bean
    public Executor asyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("Property-");
        executor.initialize();
        return executor;
    }
}

Question:问题:

  • Will this asynchronous call work?这个异步调用会起作用吗?
  • Do I need to use the join method of CompletableFuture?是否需要使用 CompletableFuture 的 join 方法? It may happen that other CompletebleFuture instances can be null, if not如果不是,其他 CompletebleFuture 实例可能为 null
    provided through query parameter.通过查询参数提供。 for eg, User only provides CURRENT.例如,用户只提供电流。
  • Do I need to mention @EnableAsync and asyncExecutor?我需要提及 @EnableAsync 和 asyncExecutor 吗?

Any Help would be appreciated, I read through all the notes online but I am still confused a little.任何帮助将不胜感激,我在网上通读了所有笔记,但我仍然有点困惑。 I cannot run it locally because i still do not have a full fledged code.我无法在本地运行它,因为我仍然没有完整的代码。

sample Implementation of CompletebleFuture: CompletebleFuture 的示例实现:

private final ExecutorService ioBound;私有最终 ExecutorService ioBound;

  CompletableFuture.supplyAsync(() -> this.getCurrentProperty(record), this.ioBound)
                    .exceptionally(exception -> false)
                    .thenAccept(input -> {
                        if (Boolean.FALSE.equals(input)) {
                            log.error("exception occured:{}", input);
                        } else
                            log.info("Success:{}", input);

                    })
CompletableFuture<String> future1  
  = CompletableFuture.supplyAsync(() -> "Hello");
CompletableFuture<String> future2  
  = CompletableFuture.supplyAsync(() -> "Beautiful");
CompletableFuture<String> future3  
  = CompletableFuture.supplyAsync(() -> "World");

CompletableFuture<Void> combinedFuture 
  = CompletableFuture.allOf(future1, future2, future3);

// ...

combinedFuture.get();

assertTrue(future1.isDone());
assertTrue(future2.isDone());
assertTrue(future3.isDone());

Please check section 8 - Running Multiple Futures in Parallel here请在此处查看第 8 节 - 并行运行多个期货

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM