---
title: "cassandra学习笔记4--Cassandra Java客户端3"
author: "csstome"
date: "2011-03-30T13:28:36Z"
tags: []
categories: ["编程语言"]
slug: "cassandra-4-cassandra-java-3"
draft: false
lastmod: "2011-03-30T13:28:36Z"
id: 980378
url: "https://csstome.iteye.com/blog/980378"
---

## Hector

Hector是基于Thrift Java API包装的一个Java客户端，提供一个更加高级的一个抽象。

### 程序范例

import static me.prettyprint.cassandra.utils.StringUtils.bytes;  
import static me.prettyprint.cassandra.utils.StringUtils.string;

import org.apache.cassandra.thrift.Column;  
import org.apache.cassandra.thrift.ColumnPath;

import me.prettyprint.cassandra.service.CassandraClient;  
import me.prettyprint.cassandra.service.CassandraClientPool;  
import me.prettyprint.cassandra.service.CassandraClientPoolFactory;  
import me.prettyprint.cassandra.service.Keyspace;  
import me.prettyprint.cassandra.service.PoolExhaustedException;

public class ExampleClient {    
 public static void main(String\[] args) throws IllegalStateException, PoolExhaustedException,Exception {  
  //setting pool  
  CassandraClientPool pool = CassandraClientPoolFactory.INSTANCE.get();     
  //setting client  
  CassandraClient client = pool.borrowClient("localhost", 9160);     
  //keyspaceName and columnFamily  
  String keyspaceName = "Keyspace1";  
  String columnFamily = "Standard1";  
  //key Name  
  String key = "逖靖寒的世界";  
  //这里可以设置均衡  
  // A load balanced version would look like this:     
  // CassandraClient client = pool.borrowClient(new String\[] {"cas1:9160", "cas2:9160", "cas3:9160"});      
  try {       
   //get keySpace  
   Keyspace keyspace = client.getKeyspace(keyspaceName);    
   //create columnPath  
   ColumnPath columnPath = new ColumnPath(columnFamily);  
   columnPath.setColumn("网址".getBytes("UTF8"));  
   //insert  
   keyspace.insert(key, columnPath, bytes("[http://gpcuster.cnblogs.com](http://gpcuster.cnblogs.com/) "));       // read   
   //get single column  
   Column col = keyspace.getColumn("逖靖寒的世界", columnPath);     
   //print name and value  
   System.out.println("name: " + string(col.getName()));      
   System.out.println("value: " + string(col.getValue()));      
   } finally {       
    // return client to pool. do it in a finally block to make sure it's executed       
    pool.releaseClient(client);     
   }  
 }  
}

### 优点

1 提供连接池。

2 提供错误处理：当操作失败的时候，Hector会根据系统信息（token map）自动连接另一个Cassandra Service。

3 编程接口容易使用。

4 支持JMX。

### 缺点

1 不支持多线程的环境。

2 keyspace封装过多（数据校验和数据重新封装），如果进行大量的数据操作，这里的消耗需要考虑。

3 错误处理不够人性化：如果所有的Cassandra Service都非常繁忙，那么经过多次操作失败后，最终的结果失败。

## 总结

Hector已经是一个基本足够使用的Java客户端了，但是还是缺乏一些相关的功能，比如：

1 线程安全。

2 支持自动的多线程查询和插入，提高操作效率。

3 人性化的错误处理机制。

4 避免过多的封装。