日期:2014-05-17 浏览次数:21222 次
在完成了Apache Cassandra的四个基本学习步骤之后,可以尝试下实战性的编码了。
?
如有必要,建议再简单回顾一下:
?
?
?
?
?
?
?
?
基于第四点的建模思路,接下来我们要做的,就是搭建一个叫做JTwissandra的实战性项目,就是所谓的Java版本的Twissandra了。
?
其目的是为了以Twitter为假想对象,使用最简约(或者直接说简陋得了)的建模和实现,表达采用Apache Cassandra作为NoSQL平台的基本实现过程。
?
JTwissandra的基本编码环境:
1. Maven来管理
2. JUnit来测试
?
3. 基于hector client来作为Apache Cassandra的Java 客户端
?
大家可以通过下面的Github链接,直接clone出来最新的代码:
JTwissandra:?https://github.com/itstarting/jtwissandra
?
也欢迎大家Fork或在这里直接拍砖——反正咱在NoSQL也是新手,脸皮厚点不要紧啦:)
?
1. 首先需要一个HFactoryHelper来初始化并建立Cassandra的客户端连接池和必要的对象:
?
import java.io.IOException;
import java.util.Properties;
import me.prettyprint.cassandra.model.ConfigurableConsistencyLevel;
import me.prettyprint.hector.api.Cluster;
import me.prettyprint.hector.api.HConsistencyLevel;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.factory.HFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Helper for Cassandra initialization
*
* @author bright_zheng
*
*/
public class HFactoryHelper {
private static Logger logger = LoggerFactory.getLogger(HFactoryHelper.class);
private static Cluster cluster;
private static Keyspace keyspace = initKeyspace();
private static Properties properties;
private HFactoryHelper(){}
public static Keyspace getKeyspace(){
return keyspace;
}
private static Keyspace initKeyspace() {
properties = new Properties();
try {
properties.load(HFactoryHelper.class.getResourceAsStream("/config.properties"));
} catch (IOException ioe) {
ioe.printStackTrace();
}
String cluster_name = properties.getProperty("cluster.name", "Test Cluster");
logger.debug("cluster.name={}", cluster_name);
String cluster_hosts = properties.getProperty("cluster.hosts", "127.0.0.1:9160");
logger.debug("cluster.hosts={}", cluster_hosts);
String active_keyspace = properties.getProperty("keyspace", "JTWISSANDRA");
logger.debug("keyspace={}", active_keyspace);
cluster = HFactory.getOrCreateCluster(cluster_name, cluster_hosts);
ConfigurableConsistencyLevel ccl = new ConfigurableConsistencyLevel();
ccl.setDefaultReadConsistencyLevel(HConsistencyLevel.ONE);
return HFactory.createKeyspace(
active_keyspace,
cluster,
ccl);
}
}
?
?