简体   繁体   中英

Play Framework 2.5 with Couchbase 4.5

I am currently playing around with Play Framework and as database I wanna use Couchbase 4.5 (which is in beta right now, but shouldn't be a problem).

Here's my question: In the Couchbase documentation they suggest using only one instance of CoucbaseCluster and just one instance of Bucket . But how do I establish these instances at startup and use them globally in all my controllers. I am already so far to know that I have to use Dependency Injection but I don't have a clue how to realize this.

Wait now by writing this I realize that some kind of global Object with those instances is old school. I have to inject those instances into all my controllers that should use them, right?

Any help would be appreciated!

So, after some tinkering I got it working:

I created a Singleton class with my buckets

@Singleton
class CouchbaseConnectionPool @Inject() (appLifecycle: ApplicationLifecycle){
  val cluster=CouchbaseCluster.create("127.0.0.1")
  val dataBucket=cluster.openBucket("data")
  val fileBucket=cluster.openBucket("files")
  appLifecycle.addStopHook { () =>
    cluster.disconnect()
    Future.successful(())
  }
}

and the controller looks like this

class DirectDBAccess @Inject() (pool:CouchbaseConnectionPool) extends Controller {
  def listAll(dbtype:String) = Action {
    val result:N1qlQueryResult  = pool.dataBucket.query(N1qlQuery.simple("select bucket.* from bucket where type=\""+dbtype+"\""))
    val data=result.allRows().mkString(",")
    val total=result.allRows().length
    val response="{data:["+data+"],total:"+total+"}"

    Ok(response).as("application/json")
  }
}

and to finally bind it all together I added

bind(classOf[CouchbaseConnectionPool]).asEagerSingleton()

to module.scala and it works!

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