熟悉hbase的用户们都会看到在$HBASE_HOME/bin 目录中有几个扩展名为rb的文件,$HBASE_HOME/lib/ruby目录中的文件都是.rb文件,这些文件都是使用jruby语言对hbase
进行操作的程序。
那么什么是jrbuy呢?
JRuby是一个纯Java实现的Ruby解释器。通过JRuby,你可以在JVM上直接运行Ruby程序,调用Java的类库。很多Java编写的Ruby IDE都是使用JRuby来解释语法的。
JRuby,JVM下的一个开源Ruby解释器,能够在Java里面使用Ruby类库。就像标准的Ruby解释器一样,除开使用Ruby调用本地方法(C代码)或者Java类库以外,Ruby代码都能够在JRuby里面正确执行。
而且使用jruby语言不用编译就可以调试java程序,因此仿照hbase shell中的代码写了一个jruby操作hbase的demo
include Java Dir.glob(File.join(File.dirname(__FILE__),"javalib","*.jar")).each do |jar_path| require jar_path end import java.io.IOException import org.apache.hadoop.conf.Configuration import org.apache.hadoop.hbase.HBaseConfiguration import org.apache.hadoop.hbase.HColumnDescriptor import org.apache.hadoop.hbase.HTableDescriptor import org.apache.hadoop.hbase.KeyValue import org.apache.hadoop.hbase.MasterNotRunningException import org.apache.hadoop.hbase.ZooKeeperConnectionException import org.apache.hadoop.hbase.client.Delete import org.apache.hadoop.hbase.client.Get import org.apache.hadoop.hbase.client.HBaseAdmin import org.apache.hadoop.hbase.client.HTable import org.apache.hadoop.hbase.client.HTablePool import org.apache.hadoop.hbase.client.Put import org.apache.hadoop.hbase.client.Result import org.apache.hadoop.hbase.client.ResultScanner import org.apache.hadoop.hbase.client.Scan import org.apache.hadoop.hbase.client.coprocessor.AggregationClient import org.apache.hadoop.hbase.filter.Filter import org.apache.hadoop.hbase.filter.FilterList import org.apache.hadoop.hbase.filter.SingleColumnValueFilter import org.apache.hadoop.hbase.filter.CompareFilter import org.apache.hadoop.hbase.util.Bytes table_name='test' configuration = HBaseConfiguration.new configuration.set("hbase.zookeeper.property.clientPort", "2181") configuration.set("hbase.zookeeper.quorum", "192.168.205.6") configuration.set("hbase.master", "192.168.205.6:60000") configuration.setInt("hbase.client.retries.number", 7) admin = HBaseAdmin.new(configuration) =begin if (admin.tableExists(table_name)) puts "table is exist" else tableDescriptor = HTableDescriptor.new(table_name) col1=HColumnDescriptor.new("col1") col2=HColumnDescriptor.new("col2") tableDescriptor.addFamily(col1) tableDescriptor.addFamily(col2) admin.createTable(tableDescriptor) puts "table create" end tables = admin.listTables p [:tables, tables] =end table = HTable.new(configuration,table_name) scan = Scan.new scanner = table.get_scanner(scan) begin while (row = scanner.next()) do row_key = Bytes.toString(row.getRow()) row.raw().each do |kv| family=Bytes.toString(kv.getFamily()) timestamp=kv.getTimestamp() value= Bytes.toString(kv.getValue()) p [row_key,family,timestamp,value] end end ensure scanner.close end
jruby hbasejruby.rb 即可看到hbase表中记录结果。