Search code examples
spring-bootcouchbasebucket

Is it possible to connect to two different buckets of couchbase in spring boot


I am trying to connect to two different buckets in couchbase using spring boot. But in a single spring boot application the database config only takes a single bucket name.

Is it possible to connect to more than one couchbase bucket in spring-boot?


Solution

  • So it seems you want to use Spring Data Couchbase from within a Spring Boot application, and have (at least) two different repositories backed by two different Bucket?

    You'll have to customize your Spring Data configuration programmatically (as opposed to letting Spring Boot do all the heavy lifting), but that's possible.

    • Spring Boot creates a CouchbaseConfigurer through which it creates default Cluster and Bucket (as tuned in the properties file).
    • If you have a CouchbaseRepository on your classpath, it'll also attempt to configure Spring Data by instantiating a SpringBootCouchbaseDataConfiguration class.
    • You can customize that by extending the SpringBootCouchbaseDataConfiguration above in your project, marking it as @Configuration

    Once you're ready to customize the Spring Data configuration programmatically, what you need is to create a second Bucket bean, a second CouchbaseTemplate that uses that bucket, and then instruct Spring Data Couchbase on which template to use with which Repository.

    To that end, there is a configureRepositoryOperationsMapping(...) method. You can use the parameter of this method as a builder to:

    • link a specific Repository interface to a CouchbaseTemplate: map
    • say that any repo with a specific entity type should use a given template: mapEntity
    • even redefine the default template to use (initially the one created by Spring Boot): setDefault.

    This second part is explained in the Spring Data Couchbase documentation.