2013-05-16 7 views
0

Я запускаю Cassandra 1.2.0 (CQL3), и я использую Hector 1.0.5. Вот мое определение таблицы:Использование Hector с CQL3 в java

CREATE TABLE group_profiles (
    profile_id text, 
    time timeuuid, 
    document text, 
    PRMARY KEY (profile_id, time) 
) WITH COMPACT STORAGE; 

Я не могу понять, как подключиться к Кассандре кластеру и создать строку. Документы для Hector повсеместны или неполны в случае CQL3. Я не могу найти полный пример подключения к существующему пространству ключей с существующей таблицей и добавления записи с использованием CQL3.

UPDATE

После еще рыть и проклятий я нашел этот пример проекта using the cassandra driver core. Я буду играть с ним, но это все равно, что я имел в виду. На данный момент это просто в бета2, но поскольку это только для личного обучения, я дам этот шанс и посмотрю, как это происходит.

+0

Привет, в какой момент ваш пример (https://github.com/boneill42/naughty- или-nice) начать использовать ядро ​​драйвера cassandra? Все, что я вижу, это использование Astyanax: s – Ar3s

ответ

0

Возможно, вы можете следовать за this и this ссылкой для начала работы с API-интерфейсом Hector.

+0

спасибо, но я хочу помочь с использованием CQL. Я не думаю, что в конечном итоге я воспользуюсь Гектором, потому что во всяком случае водитель кассандры отлично работает для меня на данный момент. –

+0

как @MarkJMiller заявил: «Документы для Гектора повсеместны или неполны в случае CQL3». с которыми я не мог согласиться больше :( – Ar3s

0

Это, как я сделал часть соединения (я использую весна/Maven):

в data-access.properties:

jdbc.driverClassName=org.apache.cassandra.cql.jdbc.CassandraDriver 
jdbc.url=jdbc:cassandra://localhost:9160/mykeyspace 
# not sure if userName and Passwords are really usefull, haven't tested, I should though, I will ... Just did ... No real impact with my cassandra configuration 
jdbc.username=IamG 
jdbc.password=root 

# Properties that control the population of schema and data for a new data source 
jdbc.initLocation=classpath:db/cassandra/initDB.cql 
jdbc.dataLocation=classpath:db/cassandra/populateDB.cql 
jpa.showSql=true 

В data-Source-config.xml

<bean id="dataSource" 
    class="org.apache.tomcat.jdbc.pool.DataSource" 
    p:driverClassName="${jdbc.driverClassName}" 
    p:url="${jdbc.url}" 
    p:username="${jdbc.username}" 
    p:password="${jdbc.password}"/> 

<!-- Database initializer. If any of the script fails, the initialization stops. --> 
<!-- As an alternative, for embedded databases see <jdbc:embedded-database/>. --> 
<jdbc:initialize-database data-source="dataSource"> 
    <jdbc:script location="${jdbc.initLocation}"/> 
    <jdbc:script location="${jdbc.dataLocation}"/> 
</jdbc:initialize-database> 

<bean id="keySpaceManager" 
    class="org.me.cassandra.persistence.KeyspaceManagerImpl" 
    p:dataSource-ref="dataSource" /> 

И тогда все мои временные wimey wibbeley-wobbeley shenanigans с этим классом

import me.prettyprint.hector.api.Cluster; 
import me.prettyprint.hector.api.Keyspace; 
import me.prettyprint.hector.api.factory.HFactory; 

import org.apache.cassandra.cql.jdbc.UtilsProxy; 
import org.apache.tomcat.jdbc.pool.DataSourceProxy; 


public class KeyspaceManagerImpl implements KeyspaceManager { 

    private DataSourceProxy dataSource; 

    @Override 
    public void setDataSource(DataSourceProxy dataSource) { 
     this.dataSource = dataSource; 
    } 

    @Override 
    public Cluster getCluster() { 
     String hostName = getHostName(); 
     String clusterName = "arbitraryClusterNameProbablyShouldBeSetInConfig.xml"; 
     return HFactory.getOrCreateCluster(clusterName, hostName); 
    } 

    @Override 
    public Keyspace getKeyspace() { 
     String databaseName = getDatabaseName(); 
     Cluster cluster = getCluster(); 
     return HFactory.createKeyspace(databaseName, cluster); 
    } 

    private String getHostName() { 
     return getConnectionProperties().getProperty(UtilsProxy.TAG_SERVER_NAME); 
    } 

    private String getDatabaseName() { 
     return getConnectionProperties().getProperty(UtilsProxy.TAG_DATABASE_NAME); 
    } 

    private Properties getConnectionProperties() { 
     return UtilsProxy.getConnectionProperties(dataSource); 
    } 
} 


// and this other class that was needed to proxy some very interesting but not visible (package visible) one 
package org.apache.cassandra.cql.jdbc; // <- package is very important here ! 

import java.sql.SQLException; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Properties; 

import org.apache.tomcat.jdbc.pool.DataSourceProxy; 
import org.apache.tomcat.jdbc.pool.PoolConfiguration; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 

/** 
* This class proxies an utility class that has been declared as "Package visible" 
* 
* Some utility methods were added (1 so far when this javadoc was written) 
* 
* @author gulhe 
* 
*/ 
public class UtilsProxy extends Utils { 

    private static final Logger log = LoggerFactory.getLogger(UtilsProxy.class); 

    private static final Map<String, Properties> urlParseStore = new HashMap<>(); 

    /** 
    * Gets cassandra connection properties from a dataSourceProxy 
    * The information used will be the full connectionUrl. 
    * Said URL will then be parsed. 
    * 
    * To avoid reparsing the same string multiple times, results are stored by their url String. 
    * 
    * @return a java.util.Properties holding Cassandra connection info 
    */ 
    public static Properties getConnectionProperties(DataSourceProxy dataSource) { 
     PoolConfiguration poolProperties = dataSource.getPoolProperties(); 
     String url = poolProperties.getUrl(); 

     Properties alreadyStoredProperties = urlParseStore.get(url); 
     if (alreadyStoredProperties != null) { 
      return alreadyStoredProperties; 
     } 

     try { 
      Properties urlParsedConnectionProperties = Utils.parseURL(url); 
      urlParseStore.put(url, urlParsedConnectionProperties); 
      return urlParsedConnectionProperties; 
     } catch (SQLException e) { 
      log.error("Something went wrong !", e); 
     } 

     return new Properties(); 
    } 

} 

Я использовал в моем pom.xml (между прочим):

<dependencies> 
    <dependency> 
     <groupId>org.apache-extras.cassandra-jdbc</groupId> 
     <artifactId>cassandra-jdbc</artifactId> 
     <version>1.2.1</version> 
    </dependency> 
    <dependency> 
     <groupId>org.hectorclient</groupId> 
     <artifactId>hector-core</artifactId> 
     <exclusions> 
      <!-- some exclusions here due to my environment, I omitted them here I can add them back by popular demand --> 
     </exclusions> 
     <version>2.0-0</version> 
    </dependency> 
</dependencies> 

Часть запроса, ... ну я все еще борется с ним :((см: https://stackoverflow.com/questions/26484525/in-cassandra-i-cant-seem-to-get-column-by-composite-name-with-hector-api)

(я мог бы, как всегда, забыть все, не стесняйтесь сказать мне, я добавлю, что не хватает)

 Смежные вопросы

  • Нет связанных вопросов^_^