Hector动态创建keyspace与columnFamily

在项目中想通过程序判断cassandra中是否已经有相应的keyspace。如果没有就建一个。就像普通db的自动建表

代码片断如下:

    private Cluster cluster;
    private Keyspace keyspace;

    public static final String KEYSPACE_NAME = "NOAH";

    public static final String COLUMN_FAMILY_NAME = "TimeData";
    
    private Logger logger= LoggerFactory.getLogger(this.getClass());


    public void init() {
        
        cluster = HFactory.getOrCreateCluster("Test Cluster", "localhost:9160");

        if (cluster.describeKeyspace(KEYSPACE_NAME) == null) {

            logger.info("create keyspace:"+KEYSPACE_NAME);

            BasicColumnFamilyDefinition columnFamilyDefinition = new BasicColumnFamilyDefinition();
            columnFamilyDefinition.setKeyspaceName(KEYSPACE_NAME);
            columnFamilyDefinition.setName(COLUMN_FAMILY_NAME);

            ColumnFamilyDefinition cfDefStandard = new ThriftCfDef(columnFamilyDefinition);


            KeyspaceDefinition keyspaceDefinition =
                    HFactory.createKeyspaceDefinition(KEYSPACE_NAME, SimpleStrategy.class.getName(),
                            1, Arrays.asList(cfDefStandard));

            cluster.addKeyspace(keyspaceDefinition);

        }
}

你可能感兴趣的:(cassandra,hector)