Reputation: 3886
I am new to Cassandra
, and I would like to ask you something. I have some events, and on each event, the application responds with some code that is similar to this:
Cluster cluster = Cluster.builder().addContactPoint(CONTACT_POINT).build();;
Session session = cluster.connect(KEYSPACE);
Statement statement = QueryBuilder.update(KEYSPACE, TABLE_NAME)
.with(set(STATE_COLUMN, status.toString()))
.and(set(PERCENT_DONE_COLUMN, percentDone))
.where(eq(FILE_ID_COLUMN, id));
//or whatever query I might have
session.execute(statement);
cluster.close();
My question is this:
Is it better to call cluster.connect()
and cluster.close()
each time, or just call cluster.connect()
once at application start up?
Thanks
Upvotes: 3
Views: 3412
Reputation: 9475
Connections in Cassandra are designed to be persistent, so they should not be opened and closed for each CQL statement. Setting up a connection is somewhat expensive, since it creates thread pools and obtains a lot of metadata from the cluster.
You want to set up the connection once at application startup and close it when your application is shutting down. If you have multiple threads within your application, you generally want them to all share a single connection.
Upvotes: 6
Reputation: 8263
You need to connect and close as less as possible.
http://docs.datastax.com/en/developer/java-driver/2.1/java-driver/fourSimpleRules.html
While the session instance is centered around query execution, the Session it also manages the per-node connection pools. The session instance is a long-lived object, and it should not be used in a request-response, short-lived fashion. The code should share the same cluster and session instances across your application.
Upvotes: 4