Java异步api调用 - 触发并忘记http调用

问题描述 投票:1回答:1

我有一个java spring boot api(数据接收器),它要求持久保存一些数据。一旦我完成持久化数据,我想进行另一个api调用(它应该处理持久数据 - 数据聚合器),它应该自己异步运行,原始程序应该在调用数据聚合器后终止。我不希望数据接收器在完成之前等待数据聚合器完成。它需要是一种火,忘记api调用http url。你能建议如何去做吗?

java spring-boot
1个回答
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);
        }
    }
}

我们打开EnableAsync的Application.java

@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
     }
 }
© www.soinside.com 2019 - 2024. All rights reserved.