Connecting cassandra cluster through scala

前端 未结 4 1633
深忆病人
深忆病人 2021-02-11 10:40

I am new in both scala and cassandra . I know the connectivity of cassandra with java using hector . But I don\'t know how to connect cassandra through scala. I want a simple ex

相关标签:
4条回答
  • 2021-02-11 11:20

    Datastax Driver 3 Scala Integration

    I have found some articles (example) and Maga library showing how you could integrate Java Driver better with Scala and it did not look hard.

    The result is my own library that you can find on GitHub: https://github.com/atais/scassandra

    It allows for seamless integration in Scala for both CQL queries and manipulating the ListenableFuture without mapping it into scala.Future.

    implicit protected val session: com.datastax.driver.core.Session
    implicit protected val executor: java.util.concurrent.Executor
    
    val selectCQL: ListenableFuture[PreparedStatement] = cql"SELECT * FROM $table WHERE key = ?"
    val result: ListenableFuture[ResultSet] = execute(selectCQL, "my-key")
    
    result.map(rs => rs.one())
          .map(...)
    

    Enjoy :)

    0 讨论(0)
  • 2021-02-11 11:28

    I've been working on Scala wrapper of Java Driver to minimize boilerplate code. You could find it here: https://github.com/InnovaCo/binders-cassandra

    Here is an example of class that works with some Cassandra DB:

    class Db(session: com.datastax.driver.core.Session) {
    
      implicit val cache = new SessionQueryCache[PlainConverter](session)
    
      // class for binding input/output parameters
      case class User(userId: Int, name: String)
    
      def insertUser(user: User): Future[Unit] = cql"insert into users(userid, name) values (?, ?)".bind(user).execute
    
      // returns Future[Iterator[User]]
      def selectAllUsers: Future[Iterator[User]] = cql"select * from users".all[User]
    
      // if no user is found will throw NoRowsSelectedException
      def selectUser(userId: Int) = cql"select * from users where userId = $userId".one[User]
    
      // if no user is found will return None, otherwise Some(User)
      def selectUserIfFound(userId: Int) = cql"select * from users where userId = $userId".oneOption[User]
    }
    

    To use library in your playframework project, add this line to the build.sbt file:

    libraryDependencies += "eu.inn" %% "binders-cassandra" % "0.2.0"
    
    0 讨论(0)
  • 2021-02-11 11:31

    I am using the datastax java driver. It's development is still active on github. I looked at Hector earlier but it seemed dying. The doc here's helpful: http://www.datastax.com/documentation/developer/java-driver/1.0/webhelp/index.html#java-driver/quick_start/qsQuickstart_c.html. I translated the first example to scala. Also, look at the akka-cassandra example from typesafe activator. Cheers.

    object Hello extends App {
    
      import com.datastax.driver.core.Cluster;
      import com.datastax.driver.core.Host;
      import com.datastax.driver.core.Metadata;
      import scala.collection.JavaConversions._
    
      var cluster: Cluster = null
      private var session: Session = null
    
      def connect(node: String) {
        cluster = Cluster.builder().addContactPoint(node).build()
        val metadata = cluster.getMetadata()
        printf("Connected to cluster: %s\n",
          metadata.getClusterName())
        metadata.getAllHosts() map {
          case host =>
            printf("Datatacenter: %s; Host: %s; Rack: %s\n",
              host.getDatacenter(), host.getAddress(), host.getRack())
        }
      }
    
      def close() {
        cluster.shutdown()
      }
    
      this.connect("127.0.0.1");
      this.close();
    }
    
    0 讨论(0)
  • 2021-02-11 11:32

    There were some Scala projects that arose to support Cassandra connectivity, including cassie by Twitter, but they all seemed to die off.

    Since you know Hector, if you have the Hector jars in your classpath, you can simply use the Hector API in Scala if you prefer.

    For example, borrowing from the documentation, you could just do this:

    val myCluster = HFactory.getOrCreateCluster("test-cluster","localhost:9160")
    

    or

    val template = new ThriftColumnFamilyTemplate[String, String](ksp, columnFamily, StringSerializer.get(), StringSerializer.get())
    

    I wrote this freehand, so the syntax might be off, but you get the idea.

    0 讨论(0)
提交回复
热议问题