Run Query against multiple namespaces with Spring Data Cassandra

♀尐吖头ヾ 提交于 2019-12-13 00:04:32

问题


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:

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

    // …
}


来源:https://stackoverflow.com/questions/45933154/run-query-against-multiple-namespaces-with-spring-data-cassandra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!