spring-bootcouchbaseshedlock

ShedLock with Spring boot with couchbase


Given my Spring boot application code:

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.context.annotation.Bean;
    import org.springframework.scheduling.annotation.EnableScheduling;
    
    import com.couchbase.client.java.Bucket;
    
    import net.javacrumbs.shedlock.provider.couchbase.javaclient3.CouchbaseLockProvider;
    import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock;
    
    @SpringBootApplication
    @EnableScheduling
    @EnableSchedulerLock(defaultLockAtMostFor = "10m")
    public class MythoughtsApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(MythoughtsApplication.class, args);
        }
        @Bean
        public CouchbaseLockProvider lockProvider(Bucket bucket) {
            return new CouchbaseLockProvider(bucket);
        }
    
    }    

pom.xml using the latest shedlock in the below pom.xml file.

         <?xml version="1.0" encoding="UTF-8"?>
            <project xmlns="http://maven.apache.org/POM/4.0.0"
                xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
                <modelVersion>4.0.0</modelVersion>
                <parent>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-parent</artifactId>
                    <version>2.7.0</version>
                    <relativePath /> <!-- lookup parent from repository -->
                </parent>
                <groupId>com.guru</groupId>
                <artifactId>mythoughts</artifactId>
                <version>0.0.1-SNAPSHOT</version>
                <name>mythoughts</name>
                <description>Demo project for Spring Boot</description>
            
                <properties>
                    <java.version>1.8</java.version>
                </properties>
            
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-data-couchbase</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-web</artifactId>
                    </dependency>
            
                    <dependency>
                        <groupId>org.projectlombok</groupId>
                        <artifactId>lombok</artifactId>
                        <optional>true</optional>
                    </dependency>
                        <dependency>
                        <groupId>com.couchbase.client</groupId>
                        <artifactId>java-client</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>com.couchbase.client</groupId>
                        <artifactId>core-io</artifactId>
                        <version>2.3.1</version>
                    </dependency>
                    **<dependency>
                        <groupId>net.javacrumbs.shedlock</groupId>
                        <artifactId>shedlock-spring</artifactId>
                        **<version>4.37.0</version>**
                    </dependency>
                    <dependency>
                        <groupId>net.javacrumbs.shedlock</groupId>
                        <artifactId>shedlock-provider-couchbase-javaclient3</artifactId>
                    **<version>4.37.0</version>**
            </dependency>**
                        
                    <dependency>
                <groupId>com.unboundid</groupId>
                <artifactId>unboundid-ldapsdk</artifactId>
            </dependency>
                    
                    <dependency>
                        <groupId>org.springframework.ldap</groupId>
                        <artifactId>spring-ldap-core</artifactId>
                    </dependency>
                    <dependency>
                        <groupId>org.springframework.security</groupId>
                        <artifactId>spring-security-ldap</artifactId>
                    </dependency>
                    <!-- <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-security</artifactId>
                    </dependency> -->
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-starter-test</artifactId>
                        <scope>test</scope>
                        <exclusions>
                            <exclusion>
                                <groupId>org.junit.vintage</groupId>
                                <artifactId>junit-vintage-engine</artifactId>
                            </exclusion>
                        </exclusions>
                    </dependency>
                </dependencies>
            
                <build>
                    <plugins>
                        <plugin>
                            <groupId>org.springframework.boot</groupId>
                            <artifactId>spring-boot-maven-plugin</artifactId>
                            <configuration>
                                <excludes>
                                    <exclude>
                                        <groupId>org.projectlombok</groupId>
                                        <artifactId>lombok</artifactId>
                                    </exclude>
                                </excludes>
                            </configuration>
                        </plugin>
                    </plugins>
                </build>
            
            </project>

couchbase Connection file

    @Configuration
    public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
    
        @Override
        public String getConnectionString() {
            // TODO Auto-generated method stub
            return "127.0.0.1";
        }
    
        @Override
        public String getUserName() {
            // TODO Auto-generated method stub
            return "admin";
        }
    
        @Override
        public String getPassword() {
            // TODO Auto-generated method stub
            return "1234";
        }
    
        @Override
        public String getBucketName() {
            // TODO Auto-generated method stub
            return "admin";
        }
    
    }

controller file

         import org.springframework.scheduling.annotation.Scheduled;
            import org.springframework.web.bind.annotation.GetMapping;
            import org.springframework.web.bind.annotation.PostMapping;
            import org.springframework.web.bind.annotation.RequestBody;
            import org.springframework.web.bind.annotation.RequestMapping;
            import org.springframework.web.bind.annotation.RestController;
            
            
            import com.guru.mythoughts.service.UserService;
            
            import net.javacrumbs.shedlock.core.LockAssert;
            import net.javacrumbs.shedlock.spring.annotation.SchedulerLock;
            
            @RestController
            public class UserController {   
                
                @Scheduled(cron = "*/5 * * * * *")
                @SchedulerLock(name = "scheduledTaskName", lockAtMostFor = "PT5M", lockAtLeastFor = "PT4M")
                public void scheduledTask() {       
                    LockAssert.assertLocked();
                    System.out.println("cloked");
                }
            }

Output with error:

       
          .   ____          _            __ _ _
         /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
        ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
         \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
          '  |____| .__|_| |_|_| |_\__, | / / / /
         =========|_|==============|___/=/_/_/_/
         :: Spring Boot ::                (v2.7.0)
        
        2022-06-21 17:36:01.346  INFO 21152 --- [           main] c.zzz.mythoughts.MyApplication  : Starting MythoughtsApplication using Java 1.8.0_271 on DESKTOP-O8IM34ASBST with PID 21152 (C:\Users\G\Downloads\mythoughts\target\classes started by in C:\Users\G\Downloads\mythoughts)
        2022-06-21 17:36:01.350  INFO 21152 --- [           main] c.zzz.mythoughts.MythoughtsApplication  : No active profile set, falling back to 1 default profile: "default"
        2022-06-21 17:36:01.889  INFO 21152 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Couchbase repositories in DEFAULT mode.
        2022-06-21 17:36:02.033  INFO 21152 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 139 ms. Found 0 Couchbase repository interfaces.
        2022-06-21 17:36:02.039  INFO 21152 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data Couchbase repositories in DEFAULT mode.
        2022-06-21 17:36:02.061  INFO 21152 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 22 ms. Found 1 Couchbase repository interfaces.
        2022-06-21 17:36:02.504  INFO 21152 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8080 (http)
        2022-06-21 17:36:02.514  INFO 21152 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
        2022-06-21 17:36:02.514  INFO 21152 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.63]
        2022-06-21 17:36:02.751  INFO 21152 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
        2022-06-21 17:36:02.751  INFO 21152 --- [           main] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1346 ms
        2022-06-21 17:36:03.445  INFO 21152 --- [      cb-events] com.couchbase.core                       : [com.couchbase.core][CoreCreatedEvent] {"clientVersion":"3.3.0","clientGitHash":"${buildNumber}","coreVersion":"2.3.1","coreGitHash":"${buildNumber}","userAgent":"couchbase-java/3.3.0 (Windows 10 10.0 amd64; Java HotSpot(TM) 64-Bit Server VM 1.8.0_271-b09)","maxNumRequestsInRetry":32768,"ioEnvironment":{"nativeIoEnabled":true,"eventLoopThreadCount":4,"eventLoopGroups":["NioEventLoopGroup"]},"ioConfig":{"captureTraffic":[],"mutationTokensEnabled":true,"networkResolution":"auto","dnsSrvEnabled":true,"tcpKeepAlivesEnabled":true,"tcpKeepAliveTimeMs":60000,"configPollIntervalMs":2500,"kvCircuitBreakerConfig":"disabled","queryCircuitBreakerConfig":"disabled","viewCircuitBreakerConfig":"disabled","searchCircuitBreakerConfig":"disabled","analyticsCircuitBreakerConfig":"disabled","managerCircuitBreakerConfig":"disabled","eventingCircuitBreakerConfig":"disabled","backupCircuitBreakerConfig":"disabled","numKvConnections":1,"maxHttpConnections":12,"idleHttpConnectionTimeoutMs":4500,"configIdleRedialTimeoutMs":300000,"memcachedHashingStrategy":"StandardMemcachedHashingStrategy"},"compressionConfig":{"enabled":true,"minRatio":0.83,"minSize":32},"securityConfig":{"tlsEnabled":false,"nativeTlsEnabled":true,"hostnameVerificationEnabled":true,"trustCertificates":null,"trustManagerFactory":null,"ciphers":[]},"timeoutConfig":{"kvMs":2500,"kvDurableMs":10000,"managementMs":75000,"queryMs":75000,"viewMs":75000,"searchMs":75000,"analyticsMs":75000,"connectMs":10000,"disconnectMs":10000,"eventingMs":75000,"backupMs":75000},"loggerConfig":{"customLogger":null,"fallbackToConsole":false,"consoleLogLevel":{"name":"INFO","resourceBundleName":"sun.util.logging.resources.logging","localizedName":"INFO"},"consoleLoggerFormatter":"DefaultLoggerFormatter","disableSlf4j":false,"loggerName":"CouchbaseLogger","diagnosticContextEnabled":false},"orphanReporterConfig":{"emitIntervalMs":10000,"sampleSize":10,"queueLength":1024,"enabled":true},"thresholdLoggingTracerConfig":{"enabled":true,"emitIntervalMs":10000,"sampleSize":10,"queueLength":1024,"kvThresholdMs":500,"queryThresholdMs":1000,"searchThresholdMs":1000,"analyticsThresholdMs":1000,"viewThresholdMs":1000},"loggingMeterConfig":{"enabled":true,"emitIntervalMs":600000},"retryStrategy":"BestEffortRetryStrategy","requestTracer":"ThresholdLoggingTracer","meter":"LoggingMeter","numRequestCallbacks":0,"scheduler":"ParallelScheduler","schedulerThreadCount":8,"transactionsConfig":{"durabilityLevel":"MAJORITY","timeoutMs":15000,"cleanupConfig":{"runLostAttemptsCleanupThread":true,"runRegularAttemptsCleanupThread":true,"cleanupWindowMs":60000,"cleanupSet":""},"numAtrs":1024,"metadataCollection":"none","scanConsistency":"none"}} {"coreId":"0xa407cf8700000001","seedNodes":[{"address":"127.0.0.1"}]}
        2022-06-21 17:36:03.445  INFO 21152 --- [      cb-events] com.couchbase.transactions               : [com.couchbase.transactions][TransactionsStartedEvent] Transactions successfully initialised, regular cleanup enabled=true, lost cleanup enabled=true
        2022-06-21 17:36:03.452  INFO 21152 --- [      cb-events] com.couchbase.node                       : [com.couchbase.node][NodeConnectedEvent] Node connected {"coreId":"0xa407cf8700000001","managerPort":"8091","remote":"127.0.0.1"}
        2022-06-21 17:36:03.985  WARN 21152 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'lockProvider' defined in com.guru.mythoughts.MythoughtsApplication: Unsatisfied dependency expressed through method 'lockProvider' parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.couchbase.client.java.Bucket' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
        2022-06-21 17:36:04.026  INFO 21152 --- [      cb-events] com.couchbase.transactions.cleanup       : [com.couchbase.transactions.cleanup][LogEvent] Waiting for 1 regular background threads to exit
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] c.c.transactions.cleanup.regular         : [com.couchbase.transactions.cleanup.regular][LogEvent] Stopping background cleanup thread for transactions from this client
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.transactions.cleanup.lost  : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 has been told to cancel
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.transactions.cleanup.lost  : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 stopping lost cleanup process, 0 threads running
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.transactions.cleanup.lost  : [com.couchbase.transactions.cleanup.lost][LogEvent] Client d9110 stopped lost cleanup process and removed client from client records
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.transactions.cleanup       : [com.couchbase.transactions.cleanup][LogEvent] Background threads have exitted
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.node                       : [com.couchbase.node][NodeDisconnectedEvent][667us] Node disconnected {"coreId":"0xa407cf8700000001","managerPort":"8091","remote":"127.0.0.1"}
        2022-06-21 17:36:04.027  INFO 21152 --- [      cb-events] com.couchbase.core                       : [com.couchbase.core][ShutdownCompletedEvent][19ms] Completed shutdown and closed all open buckets {"coreId":"0xa407cf8700000001"}
        2022-06-21 17:36:04.118  INFO 21152 --- [           main] o.apache.catalina.core.StandardService   : Stopping service [Tomcat]
        2022-06-21 17:36:04.130  INFO 21152 --- [           main] ConditionEvaluationReportLoggingListener : 
        
        Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
        2022-06-21 17:36:04.157 ERROR 21152 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 
        
        ***************************
        APPLICATION FAILED TO START
        ***************************
        
        Description:
        
        Parameter 0 of method lockProvider in com.guru.mythoughts.MythoughtsApplication required a bean of type 'com.couchbase.client.java.Bucket' that could not be found.
        
        
        Action:
        
        Consider defining a bean of type 'com.couchbase.client.java.Bucket' in your configuration.

I have given sample code and when I tried to run the application I am getting the above error. I have scheduled a method in controller and it should run for every 5 seconds. I have followed the above in the given below link https://gitcode.net/mirrors/lukas-krecan/ShedLock/-/tree/master/providers/couchbase

How can i solve this error?


Solution

  • Autowired the Cluster class and used the cluster to get the bucket details with bean creation in main class which return the bucket object. please see the same code and it is working fine.

        @Autowired
        Cluster cluster;
        
        @Bean
        public Bucket getBucket() {     
            return cluster.bucket("bucket");
        }
    }