Skip to content

Commit 5006a4e

Browse files
author
Magesh Chandramouli
committed
adding code for connection retry at startup
1 parent f594b25 commit 5006a4e

1 file changed

Lines changed: 25 additions & 10 deletions

File tree

  • backends/cassandra/src/main/scala/com/expedia/www/haystack/trace/storage/backends/cassandra/client

backends/cassandra/src/main/scala/com/expedia/www/haystack/trace/storage/backends/cassandra/client/CassandraSession.scala

Lines changed: 25 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -20,28 +20,45 @@ package com.expedia.www.haystack.trace.storage.backends.cassandra.client
2020
import java.nio.ByteBuffer
2121
import java.util.Date
2222

23-
import com.datastax.driver.core.BatchStatement.Type
2423
import com.datastax.driver.core._
24+
import com.datastax.driver.core.exceptions.NoHostAvailableException
2525
import com.datastax.driver.core.querybuilder.QueryBuilder
2626
import com.expedia.www.haystack.trace.storage.backends.cassandra.config.entities.{ClientConfiguration, KeyspaceConfiguration}
2727
import org.slf4j.LoggerFactory
2828
import com.expedia.www.haystack.trace.storage.backends.cassandra.client.CassandraTableSchema._
2929

3030
import scala.collection.JavaConverters._
31-
import scala.util.Try
31+
import scala.util.{Failure, Success, Try}
3232

33-
class CassandraSession(config: ClientConfiguration, factory: ClusterFactory) {
33+
object CassandraSession {
3434
private val LOGGER = LoggerFactory.getLogger(classOf[CassandraSession])
3535

36+
def connect(config: ClientConfiguration,
37+
factory: ClusterFactory): (Cluster, Session) = this.synchronized {
38+
def tryConnect(): (Cluster, Session) = {
39+
val cluster = factory.buildCluster(config)
40+
Try(cluster.connect()) match {
41+
case Success(session) => (cluster, session)
42+
case Failure(e: NoHostAvailableException) =>
43+
LOGGER.warn("Failed to connect to cassandra. Will try again", e)
44+
Thread.sleep(5000)
45+
tryConnect()
46+
case Failure(e) => throw e
47+
}
48+
}
49+
50+
tryConnect()
51+
}
52+
}
53+
54+
class CassandraSession(config: ClientConfiguration, factory: ClusterFactory) {
55+
import CassandraSession._
56+
3657
/**
3758
* builds a session object to interact with cassandra cluster
3859
* Also ensure that keyspace and table names exists in cassandra.
3960
*/
40-
private val (cluster, session) = {
41-
val cluster = factory.buildCluster(config)
42-
val newSession = cluster.connect()
43-
(cluster, newSession)
44-
}
61+
lazy val (cluster, session) = connect(config, factory)
4562

4663
def ensureKeyspace(keyspace: KeyspaceConfiguration): Unit = {
4764
LOGGER.info("ensuring kespace exists with {}", keyspace)
@@ -118,6 +135,4 @@ class CassandraSession(config: ClientConfiguration, factory: ClusterFactory) {
118135
* @return future object of ResultSet
119136
*/
120137
def executeAsync(statement: Statement): ResultSetFuture = session.executeAsync(statement)
121-
122-
123138
}

0 commit comments

Comments
 (0)