Run Query against multiple namespaces with Spring

2019-07-31 11:38发布

Is there any way in which using Spring Data a query can be executed on all keyspaces in Cassandra?

1条回答
叛逆
2楼-- · 2019-07-31 12:42

There are two parts to this answer:

  1. When using Spring Data Cassandra 1.x, you are need to setup individual CassandraTemplate instances for each keyspace you want to use.
  2. With Spring Data Cassandra 2.x, we introduced the SessionFactory interface to control which Session to use. We ship with routing SessionFactory support so you can provide multiple sessions and a discriminator (usually something ThreadLocal-based) to select the appropriate Session.

Some example code for 2.0 would look like:

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;
    }

    // …
}
查看更多
登录 后发表回答