如何使用SpringBoot与CompletableFuture一起提供宁静的服务

时间:2018-04-16 01:09:09

标签: java spring-boot asynchronous

我很难理解异步方法在SpringBoot中是如何工作的。

考虑我正在实现一个微服务来获取用户或All的Current,In-process或SoldOff属性,具体取决于用户的查询参数。我正在调用两个调用sql脚本的方法给我答案。我想以异步方式运行这些方法,因为它需要时间。

示例:

@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;
    }
}

问题:

  • 这个异步调用会起作用吗?
  • 我是否需要使用CompletableFuture的join方法?它可能会发生 其他CompletebleFuture实例可以为null,如果不是
    通过查询参数提供。例如,用户仅提供CURRENT。
  • 我是否需要提及@EnableAsync和asyncExecutor?

任何帮助将不胜感激,我在线阅读所有笔记,但我仍然感到困惑。我无法在本地运行,因为我还没有完整的代码。

2 个答案:

答案 0 :(得分:1)

CompletebleFuture的示例实现:

私有最终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);

                    })

答案 1 :(得分:0)

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());

请检查第8节-并行here运行多个期货

相关问题