作者热门文章
- android - AmazonSNS - AwsCredentials.properties - NullPointerException
- android - ListView invalidate() 与 invalidateViews() 之间的区别?
- android - 获取上下文的问题
- Android M 权限模型
我有一个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/
我是一名优秀的程序员,十分优秀!