首页 > 解决方案 > 如何依赖注入 CqlSession?

问题描述

根据文档,为了ShedLock与 Cassandra 一起使用,我需要CqlSession创建一个.CassandraLockProvider

但是,我总是收到以下错误:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.datastax.oss.driver.api.core.CqlSession' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}

下面这个完整的最小示例重现了该问题:

src/main/kotlin/com/foo/cqlsessioninjection/application.kt

package com.foo.cqlsessioninjection


import com.datastax.oss.driver.api.core.CqlSession
import net.javacrumbs.shedlock.core.LockProvider
import net.javacrumbs.shedlock.provider.cassandra.CassandraLockProvider
import net.javacrumbs.shedlock.spring.annotation.EnableSchedulerLock
import net.javacrumbs.shedlock.spring.annotation.SchedulerLock
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.runApplication
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.scheduling.annotation.EnableScheduling
import org.springframework.scheduling.annotation.Scheduled
import org.springframework.stereotype.Component


@SpringBootApplication
@EnableScheduling
@EnableSchedulerLock(defaultLockAtMostFor = "PT23H")
class CqlSessionInjection


@Configuration
class SchedulerConfiguration {
    @Bean
    fun lockProvider(cqlSession: CqlSession): LockProvider {
        return CassandraLockProvider(cqlSession)
    }
}

@Component
class SomeTask {
    @Scheduled(cron = "*/1 * * * * ?") // every second
    @SchedulerLock(name = "some_task")
    fun runSomeTask() {
        println("some task")
    }
}

fun main(args: Array<String>) {
    runApplication<CqlSessionInjection>(*args)
}

build.gradle

buildscript {
    ext {
        kotlinVersion = '1.3.71'
        springBootVersion = '2.2.6.RELEASE'
    }
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
        classpath("org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}")
        classpath("org.jetbrains.kotlin:kotlin-allopen:${kotlinVersion}")
    }
}

apply plugin: 'kotlin'
apply plugin: 'kotlin-spring'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'

group = 'com.foo'
version = '1.0.0-SNAPSHOT'
sourceCompatibility = 1.8
compileKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}
compileTestKotlin {
    kotlinOptions {
        freeCompilerArgs = ["-Xjsr305=strict"]
        jvmTarget = "1.8"
    }
}

repositories {
    mavenCentral()
}

dependencies {
    implementation group: 'net.javacrumbs.shedlock', name: 'shedlock-spring', version: '4.9.1'
    implementation group: 'net.javacrumbs.shedlock', name: 'shedlock-provider-cassandra', version: '4.9.1'

    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-data-cassandra'
    implementation group: 'org.springframework.boot', name: 'spring-boot-starter-web'
    implementation group: 'org.jetbrains.kotlin', name: 'kotlin-stdlib-jdk8'
    implementation group: 'org.jetbrains.kotlin', name: 'kotlin-reflect'
    implementation group: 'org.jetbrains.kotlinx', name: 'kotlinx-coroutines-core', version: '1.3.3'

    compile group: 'com.google.guava', name: 'guava', version: '23.3-jre'

    testCompile group: 'org.cassandraunit', name: 'cassandra-unit-spring', version: '3.11.2.0'
    testCompile group: 'org.springframework.boot', name: 'spring-boot-starter-test'
    annotationProcessor group: 'org.springframework.boot', name: 'spring-boot-configuration-processor'
}

task downloadDependencies(type: Exec) {
    configurations.testRuntime.files
    commandLine 'echo', 'Downloaded all dependencies'
}

compileKotlin.dependsOn(processResources)
compileJava.dependsOn(processResources)

settings.gradle

rootProject.name = 'CqlSessionInejction'

src/test/kotlin/com/foo/cqlsessioninjection/integration/ContextTest.kt

package com.foo.cqlsessioninjection.integration

import org.cassandraunit.spring.CassandraDataSet
import org.cassandraunit.spring.CassandraUnitDependencyInjectionTestExecutionListener
import org.cassandraunit.spring.EmbeddedCassandra
import org.junit.Test
import org.junit.runner.RunWith
import org.springframework.boot.test.context.SpringBootTest
import org.springframework.test.context.TestExecutionListeners
import org.springframework.test.context.junit4.SpringRunner

@RunWith(SpringRunner::class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestExecutionListeners(
    listeners = [CassandraUnitDependencyInjectionTestExecutionListener::class],
    mergeMode = TestExecutionListeners.MergeMode.MERGE_WITH_DEFAULTS
)
@CassandraDataSet(value = ["cql/cql_session_injection.cql"], keyspace = "shedlock")
@EmbeddedCassandra
class ContextTest {
    @Test
    fun `test task`() {
        println("starting to sleep")
        Thread.sleep(4000)
        println("done sleeping")
    }
}

src/test/resources/application.yml

spring:
  data:
    cassandra:
      contact-points: localhost
      port: 9142
      keyspace_name: shedlock

src/test/resources/cql/cql_session_injection.cql

DROP KEYSPACE IF EXISTS shedlock;

CREATE KEYSPACE shedlock
WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':1};

CREATE TABLE shedlock.lock (
    name text PRIMARY KEY,
    lockUntil timestamp,
    lockedAt timestamp,
    lockedBy text
);

标签: spring-bootkotlindependency-injectioncassandrashedlock

解决方案


您引用的文档指出CqlSession必须创建一个 bean,但它并没有真正解释您是如何到达那里的。我会将其作为文档问题报告给该项目,以使其更加明确。

您需要 Spring Boot 2.3 才能获得 Cassandra v4 支持。您使用的版本 (2.2x) 使用 Cassandra v3 和完全不同的 API。


推荐阅读