gpt4 book ai didi

Java 异步 api 调用 - 即发即忘 http 调用

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:56 32 4
gpt4 key购买 nike

我有一个java spring boot api(数据接收器),客户端调用它来保存一些数据。一旦我完成了数据的持久化,我想进行另一个 api 调用(应该处理持久化的数据 - 数据聚合器),它应该自行异步运行,并且原始程序应该在简单地调用数据聚合器后终止。我不希望数据接收器等待数据聚合器完成才能完成。它需要是一种对 http url 的即发即忘 api 调用。您能建议一下如何去做吗?

最佳答案

我根据上述建议和spring.io得出了以下解决方案

自己的类中的公共(public)异步方法

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

关于Java 异步 api 调用 - 即发即忘 http 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52105202/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com