简体   繁体   中英

Multiple concurrent connections to Cassandra in Java

I'm developing a multi-threaded application in which each thread accesses Cassandra in Java. Shall I create multiple clusters and close them after each access or multiple sessions? Can I create the cluster or the session as static data members?

Here is the log I got when declaring both as static:

14:40:50.361 [cluster1-nio-worker-0] DEBUG com.datastax.driver.core.Connection - Connection[localhost/127.0.0.1:9042-1, inFlight=0, closed=false] was inactive for 30 seconds, sending heartbeat
14:40:50.361 [cluster1-nio-worker-0] DEBUG com.datastax.driver.core.Connection - Connection[localhost/127.0.0.1:9042-1, inFlight=0, closed=false] heartbeat query succeeded

If you are writing a multi-thread application I would create Cluster and Session as static member . Session maintain multiple threads per instance and is thread-safe . I would use one Session object per keyspace .

From cassandra-java-driver docs:

Session instances are thread-safe and usually a single instance is enough per application. As a given session can only be "logged" into one keyspace at a time (where the "logged" keyspace is the one used by query if the query doesn't explicitely use a fully qualified table name), it can make sense to create one session per keyspace used. This is however not necessary to query multiple keyspaces since it is always possible to use a single session with fully qualified table name in queries.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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