运行 使用 Spring Data Cassandra 查询多个命名空间

Run Query against multiple namespaces with Spring Data Cassandra

有没有什么方法可以使用 Spring 数据在 Cassandra 中的所有键空间上执行查询?

这个答案分为两部分:

  1. 使用 Spring Data Cassandra 1.x 时,您需要为要使用的每个键空间设置单独的 CassandraTemplate 实例。
  2. 使用 Spring Data Cassandra 2.x,我们引入了 SessionFactory interface to control which Session to use. We ship with routing SessionFactory support,因此您可以提供多个会话和鉴别器(通常是基于 ThreadLocal 的东西)select合适Session

2.0 的一些示例代码如下所示:

class MyRoutingSessionFactory extends AbstractRoutingSessionFactory {

    ThreadLocal<String> lookupKey = ThreadLocal.withInitial(() -> "default-session");

    void setLookupKey(String lookupKey) {
        this.lookupKey.set(lookupKey);
    }

    @Override
    protected Object determineCurrentLookupKey() {
        return lookupKey.get();
    }
}

class MyConfig extends AbstractCassandraConfiguration {

    @Bean
    @Override
    public SessionFactory sessionFactory() {

        MyRoutingSessionFactory factory = new MyRoutingSessionFactory();
        factory.setDefaultTargetSessionFactory(getRequiredSession());

        MapSessionFactoryLookup lookup = new MapSessionFactoryLookup();

        Session myOtherSession = …;

        lookup.addSessionFactory("default-session", getRequiredSession());          
        lookup.addSessionFactory("my-other-session", myOtherSession);

        factory.setSessionFactoryLookup(lookup);

        return factory;
    }

    // …
}