在 Java 中执行这种代码模式的最佳且最快的方法是什么?

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

我必须将以下代码模式迁移到 Java。我想知道在 Java 中使用或不使用任何库的最佳方法是什么:

async def call_external_service(user):  
    async with session.get(url, headers=headers) as response:  
    response = await response.json()  
    # extract some field from the response  
    country = response.json()['country']  
    print(country)

async def get_countries(users):  
    tasks = [asyncio.ensure_future(call_external_service(user)) for user in users]  
    await asyncio.gather(*tasks, return_exceptions=True)

users = list()  
with open("users.txt", "r") as f:  
    for line in f.readlines():  
    users.append(line.strip('\n'))

asyncio.run(get_countries(users))

谢谢

python java networking io
1个回答
0
投票

在 Java 21 及更高版本中,使用 虚拟线程,几乎不需要复杂的异步/反应式编程。您可以让数百万个线程运行简单的代码。

Java 附带 HTTP 客户端类

Java 有方便的 try-with-resources 语法来自动关闭资源,例如

ExecutorService

Collection < User > users = … ; // Fetch. 
try
(
    ExecutorService es = Executors. newVirtualThreadPerTaskExecutor() ;
)
{
    for ( User : user ) 
    { 
        es.submit( … some task object — `Runnable` or `Callable` … ) ;
    }
}

搜索以了解更多信息。 Stack Overflow 上广泛涵盖了这些主题。

© www.soinside.com 2019 - 2024. All rights reserved.