Java异步API调用-触发并忘记HTTP调用

时间:2018-08-30 20:53:03

标签: java spring-boot

我有一个Java spring boot api(数据接收器),一个客户端要求持久化一些数据。一旦完成对数据的持久化,我想进行另一个api调用(应该处理持久化的数据-数据聚合器),它应自行异步运行,并且原始程序应在简单地调用数据聚合器后终止。我不希望数据接收器在完成数据聚合器之前等待它完成。它必须是一种类型,并且会忘记对http url的api调用。您能提出建议吗?

1 个答案:

答案 0 :(得分:0)

我根据上述建议和spring.io

得出了以下解决方案

其类中的公共异步方法

@Service
public class CallAggrAsync 
{
    @Async
    public void fireandforgetrag()
    {
        try
        {
            URL myurl = new URL("http://myurl.com");
            URLConnection myconn = myurl.openConnection();
            BufferedReader in = new BufferedReader(
                                new InputStreamReader(
                                myconn.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) 
                System.out.println(inputLine);
            in.close();
        }
        catch(Exception e)
        {
            System.out.println("Error firing or forgetting: "+e);
        }
    }
}

Application.java,我们在其中启用EnableAsync

@SpringBootApplication
@EnableAsync
public class Application
{
    public static void main(final String args[]) 
    {
        SpringApplication.run(Application.class);
    }

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

我调用上述异步方法

@Service
public class Persist
{

    @Autowired private CallAggrAsync asy;
    public boolean somefunc()
    {
        //do some work  
        asy.fireandforgetrag("server",hostname);
        //do some more work which will continue running without waiting for above 
        function to finish
     }
 }