Is there any way in which using Spring Data a query can be executed on all keyspaces in Cassandra?
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
There are two parts to this answer:
- When using Spring Data Cassandra 1.x, you are need to setup individual
CassandraTemplate
instances for each keyspace you want to use. - With Spring Data Cassandra 2.x, we introduced the
SessionFactory
interface to control whichSession
to use. We ship with routingSessionFactory
support so you can provide multiple sessions and a discriminator (usually somethingThreadLocal
-based) to select the appropriateSession
.
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;
}
// …
}