简体   繁体   English

Java通过线程与API服务器建立许多连接

[英]Java many connections to API server with threads

I have created a custom web API for submitting data to a MYSQL server for my Java application. 我创建了一个自定义Web API,用于将数据提交给Java应用程序的MYSQL服务器。 Within my Java application I need to add/update 200 rows, and I already have it making these requests one at a time. 在我的Java应用程序中,我需要添加/更新200行,并且我已经让它一次发出一个请求。

  1. This can be pretty time consuming, so can I create threads for all of these different connections? 这可能会非常耗时,因此我可以为所有这些不同的连接创建线程吗?
  2. Should I limit the number of maximum connections made at a time? 我应该限制一次最多连接的数量吗? Maybe like 10 at a time? 一次大概10个?
  3. Will this cause any issues with mysql possibly adding rows at exactly the same time? 这会导致与mysql完全相同的时间添加行的任何问题吗? (No 2 rows would ever be needed to be changed at a single point in time) (无需在单个时间点更改2行)

Inserting records in multiple connections will potentially speed up the 200 inserts, but you can only know for sure by testing and measuring after introducing multiple threads. 在多个连接中插入记录可能会加快200个插入的速度,但是只有在引入多个线程之后进行测试和测量,您才能确定。 I will also suggest trying JDBC batch and sending all 200 inserts to the database in one go (if that is possible in your implementation), as that might provide a performance boost by saving round trips to the database. 我还将建议尝试JDBC批处理并一次性将所有200个插入发送到数据库(如果在实现中可能的话),因为这可以通过节省往返数据库的时间来提高性能。

To create a connection pool, look at HikariCP which is a JDBC connection pool implementation. 要创建连接池,请查看HikariCP ,它是JDBC连接池的实现。 It will allow you to specify the min/max concurrent connections along with other settings. 它将允许您指定最小/最大并发连接数以及其他设置。 Your worker threads then can request connections from the pool and perform the inserts. 然后,您的工作线程可以从池中请求连接并执行插入。

Inserting multiple records concurrently could have issues at mySQL level if it acquires a table lock for each insert. 如果它为每个插入获取一个表锁,则在mySQL级别上并发插入多个记录可能会出现问题。 In that case you would not get a speed improvement with multiple threads and might need some tuning at the database level to work around it. 在这种情况下,使用多个线程将无法提高速度,并且可能需要在数据库级别进行一些调整才能解决该问题。 Here's a good article that should help: High rate insertion with mySQL 这是一篇很好的文章,应该对您有所帮助: 使用mySQL进行高速率插入

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM