Search code examples
spring-datacouchbasespring-data-couchbase

How to set couchbase operation timeout in spring data couchbase?


I have a simple spring project which try to retrieve a document from couchbase using spring-data-couchbase. I have configured the config by extending AbstractCouchbaseConfiguration. Everything works perfectly fine.

Since I use couchbase as a cache, now I need to set the operation timeout to a lower value. Anybody can shed some light on how to do it?


Solution

  • To define a timeout for the CouchbaseClient you have to provide it using the ConnectionFactory. Sadly, the current version of spring-data-couchbase doesn't provide a simple way to do that.

    The class responsible to create connection factories is ConnectionFactoryBean, and it has a setter for the operations timeout, but I couldn't find anything for @Configuration classes.

    Since you are extending AbstractCouchbaseConfiguration, you might want to override couchbaseClient():

    public class MyCouchbaseConfiguration extends AbstractCouchbaseConfiguration {
    
         ...
    
         private final CouchbaseConnectionFactoryBuilder builder = new CouchbaseConnectionFactoryBuilder();
         private CouchbaseConnectionFactory connectionFactory;
    
         ...
    
         @Override
         @Bean(destroyMethod = "shutdown")
         public CouchbaseClient couchbaseClient() throws Exception {
               setLoggerProperty(couchbaseLogger());
    
               if(connectionFactory == null){
                   builder.setOpTimeout(myTimeout);
                   // Set another parameters.
                   ...
    
                   connectionFactory = builder.buildCouchbaseConnection(
                       bootstrapUris(bootstrapHosts()),
                       getBucketName(),
                       getBucketPassword()
                   );
               }
    
               return new CouchbaseClient(connectionFactory);
         }
    }
    

    Also, you can call directly CouchbaseFactoryBean but it's not a good practice if you are not configuring your application using XML bean definitions.

    Here is the XML configuration just in case:

    <bean id="couchbase" class="org.springframework.data.couchbase.core.CouchbaseFactoryBean">
        <property name="opTimeout" value="1000"/> <!-- 1 sec -->
        <property name="bucket" value="myBucket"/>
        <property name="password" value="myPassword"/>
        <property name="host" value="myHost"/>
    </bean>
    <couchbase:template id="couchbaseTemplate"/>