简体   繁体   English

多线程与 PostgreSQL JDBC

[英]Multithreading with PostgreSQL JDBC

I'm still a student and not so experienced with multithreading and databases so I might have missed some obvious stuff - hoping for an answer at a more beginner level.我仍然是一名学生,对多线程和数据库没有那么丰富的经验,所以我可能错过了一些明显的东西——希望能得到初学者水平的答案。 I'm busy creating a dummy Java application that allows users to submit subway station locations and then lookup the nearest station to their location.我正忙于创建一个虚拟 Java 应用程序,允许用户提交地铁站位置,然后查找离他们位置最近的车站。 This is all happening over HTTP. The backend for this application is PostgreSQL (with PostGis) and I connect to the database via the PostgreSQL JDBC. I want my application to be as multithreaded as possible.这一切都发生在 HTTP 上。此应用程序的后端是 PostgreSQL(使用 PostGis),我通过 PostgreSQL JDBC 连接到数据库。我希望我的应用程序尽可能多线程。 Every time I receive a new HTTP connection, I spin up a new thread and service the users request.每次我收到一个新的 HTTP 连接时,我都会启动一个新线程并为用户请求提供服务。 But I'm not sure how much point there is to this if reads and writes to the database themselves cannot be parallel.但是,如果对数据库的读写本身不能并行,我不确定这有多大意义。 According to this , PostgreSQL JDBC is not thread safe.据此,PostgreSQL JDBC 不是线程安全的。 But what does that mean exactly?但这到底是什么意思呢? Does that just mean that reads and writes within a single connection are not thread safe (ie in each instance of DriverManager.getConnection())?这是否仅仅意味着单个连接中的读取和写入不是线程安全的(即在 DriverManager.getConnection() 的每个实例中)? But what about if I made a new connection every time an HTTP request came in?但是,如果每次收到 HTTP 请求时我都建立一个新连接怎么办? Would that be safe to do in parallel?并行执行是否安全? And would that affect performance badly?这会严重影响性能吗? Any other suggestions on broad approach to take?关于采取广泛方法的任何其他建议?

JDBC in general is not thread-safe, not just the Postgres driver. JDBC 通常不是线程安全的,不仅仅是 Postgres 驱动程序。

This means you can not run multiple statements created from the same Connection instance in multiple threads at the same time.这意味着您不能同时在多个线程中运行从同一个Connection实例创建的多个语句。

If you want to run two statements in parallel, you need to create two different physical connections to the database.如果要并行运行两条语句,则需要创建两个不同的数据库物理连接。

As creating connections isn't cost-free, the usual approach is to have a connection pool (eg through a ConnectionPoolDataSource ) that keeps a set of connections open.由于创建连接不是免费的,通常的方法是有一个连接池(例如通过ConnectionPoolDataSource )来保持一组连接打开。 The application then takes connections from the pool and puts them back when the query (or transaction) is done.然后,应用程序从池中获取连接,并在查询(或事务)完成后将它们放回原处。

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

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