php通过thrift 0.9.0操作HBase
最近项目中需要使用thrift和php来读写HBase中的相关数据,所以就整理了下相关的类,做了下测试.
现在自己用到的操作HBase的方式主要有以下几种:
1.HBase Shell, 主要是配置后执行 shell 通过命令查看 HBase 中的数据,比如 count 'xxxx', scan 'xxxx' 等.
2.通过Native Java Api , 自己封装了一个 RESTfull的Api , 通过提供的Api(http)方式来操作HBase
3.使用Thrift 的序列化技术,Thrift支持C++,PHP,Python等语言,适合其他的异构系统操作HBase,这块刚刚尝试
4.使用HBasExplorer,之前写的一个图形化的客户端来操作HBase, http://www.cnblogs.com/scotoma/archive/2012/12/18/2824311.html
5. Hive/Pig , 这个现在还没真正的用过.
当前主要讲第三种方式 Thrift, 这个是Facebook开源出来的, 官方网站是 http://thrift.apache.org/ .
下载安装和启动,请看参考文章中的内容
查看是否跑成功...
使用php 类文件操作Hbase, 生成类文件的方式,请看参考文章中的生产的方法,不过我自己测试的生成方法有Bug,生成的 类文件中 namespace 是空的, 但是从官方源码库中生成的是 namespace Hbase, 所以这里需要注意一下.
我调试了一个驱动类文件,放到了github上了,大家需要的可以下载使用.
https://github.com/xinqiyang/buddy/tree/master/Vender/thrift
接下来进行测试操作,参考http://blog.csdn.net/hguisu/article/details/7298456 这里的测试类,写了个测试,并调试了下
<?php /*** Thrift Test Class by xinqiyang */ ini_set('display_error', E_ALL); $GLOBALS['THRIFT_ROOT'] = './lib'; /* Dependencies. In the proper order. */ require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TTransport.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TSocket.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Protocol/TProtocol.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Protocol/TBinaryProtocol.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Transport/TBufferedTransport.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Type/TMessageType.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Factory/TStringFuncFactory.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/StringFunc/TStringFunc.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/StringFunc/Core.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Type/TType.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Exception/TException.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Exception/TTransportException.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Thrift/Exception/TProtocolException.php'; /* Remember these two files? */ require_once $GLOBALS['THRIFT_ROOT'].'/Types.php'; require_once $GLOBALS['THRIFT_ROOT'].'/Hbase.php'; use Thrift\Protocol\TBinaryProtocol; use Thrift\Transport\TSocket; use Thrift\Transport\TSocketPool; use Thrift\Transport\TFramedTransport; use Thrift\Transport\TBufferedTransport; use Hbase\HbaseClient; //define host and port $host = '192.168.56.56'; $port = 9090; $socket = new Thrift\Transport\TSocket($host, $port); $transport = new TBufferedTransport($socket); $protocol = new TBinaryProtocol($transport); // Create a calculator client $client = new HbaseClient($protocol); $transport->open(); //echo "Time: " . $client -> time(); $tables = $client->getTableNames(); sort($tables); foreach ($tables as $name) { echo $name."\r\n"; } //create a fc and then create a table $columns = array( new \Hbase\ColumnDescriptor(array( 'name' => 'id:', 'maxVersions' => 10 )), new \Hbase\ColumnDescriptor(array( 'name' => 'name:' )), new \Hbase\ColumnDescriptor(array( 'name' => 'score:' )), ); $tableName = "student"; /* try { $client->createTable($tableName, $columns); } catch (AlreadyExists $ae) { var_dump( "WARN: {$ae->message}\n" ); } */ // get table descriptors $descriptors = $client->getColumnDescriptors($tableName); asort($descriptors); foreach ($descriptors as $col) { var_dump( " column: {$col->name}, maxVer: {$col->maxVersions}\n" ); } //set clomn //add update column data $time = time(); var_dump($time); $row = '2'; $valid = "foobar-".$time; $mutations = array( new \Hbase\Mutation(array( 'column' => 'score', 'value' => $valid )), ); $mutations1 = array( new \Hbase\Mutation(array( 'column' => 'score:a', 'value' => $time, )), ); $attributes = array ( ); //add row, write a row $row1 = $time; $client->mutateRow($tableName, $row1, $mutations1, $attributes); echo "-------write row $row1 ---\r\n"; //update row $client->mutateRow($tableName, $row, $mutations, $attributes); //get column data $row_name = $time; $fam_col_name = 'score:a'; $arr = $client->get($tableName, $row_name, $fam_col_name, $attributes); // $arr = array foreach ($arr as $k => $v) { // $k = TCell echo " ------ get one : value = {$v->value} , <br> "; echo " ------ get one : timestamp = {$v->timestamp} <br>"; } echo "----------\r\n"; $arr = $client->getRow($tableName, $row_name, $attributes); // $client->getRow return a array foreach ($arr as $k => $TRowResult) { // $k = 0 ; non-use // $TRowResult = TRowResult var_dump($TRowResult); } echo "----------\r\n"; /****** //no test public function scannerOpenWithScan($tableName, \Hbase\TScan $scan, $attributes); public function scannerOpen($tableName, $startRow, $columns, $attributes); public function scannerOpenWithStop($tableName, $startRow, $stopRow, $columns, $attributes); public function scannerOpenWithPrefix($tableName, $startAndPrefix, $columns, $attributes); public function scannerOpenTs($tableName, $startRow, $columns, $timestamp, $attributes); public function scannerOpenWithStopTs($tableName, $startRow, $stopRow, $columns, $timestamp, $attributes); public function scannerGet($id); public function scannerGetList($id, $nbRows); public function scannerClose($id); */ echo "----scanner get ------\r\n"; $startRow = '1'; $columns = array ('column' => 'score', ); // $scan = $client->scannerOpen($tableName, $startRow, $columns, $attributes); //$startAndPrefix = '13686667'; //$scan = $client->scannerOpenWithPrefix($tableName,$startAndPrefix,$columns,$attributes); //$startRow = '1'; //$stopRow = '2'; //$scan = $client->scannerOpenWithStop($tableName, $startRow, $stopRow, $columns, $attributes); //$arr = $client->scannerGet($scan); $nbRows = 1000; $arr = $client->scannerGetList($scan, $nbRows); var_dump('count of result :'.count($arr)); foreach ($arr as $k => $TRowResult) { // code... //var_dump($TRowResult); } $client->scannerClose($scan); //close transport $transport->close();
这里操作了 createTable , Insert Row , Get Table , Update Row,Scan Table 这些常用的,先熟悉下.
实际操作的时候,需要注意:
1.php的版本,需要支持命名空间,所以需要5.3以上的支持
2.安装thrift的php扩展,貌似这个没有实际用到,还是得使用相关的php文件,谁能写个扩展就好了.不知道性能是否能够提升.
3.对于scan的相关操作,测试了 start/stop, prefix的Scan,感觉还是可以的.
4.感觉php的命名空间很挫,怎么办..\分割感觉就是那么的不地道......
接下来,有时间的话,会做下其他的几个操作,并进行压力测试,并将这个部署到集群中去.
大家有用Thrift的欢迎交流,感谢hguisu写的这个文章(参考文章),让大家能够尽快的入门.
更新内容:
20130517 在集群上启动了Thrift发现写入操作的时候,还是不稳定,有比较严重的超时现象,对于这块的操作,需要进行 php 操作类的优化. 其实感觉操作类还是写的太复杂的了.
参考文章:
http://blog.csdn.net/hguisu/article/details/7298456

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











PHP 8.4는 상당한 양의 기능 중단 및 제거를 통해 몇 가지 새로운 기능, 보안 개선 및 성능 개선을 제공합니다. 이 가이드에서는 Ubuntu, Debian 또는 해당 파생 제품에서 PHP 8.4를 설치하거나 PHP 8.4로 업그레이드하는 방법을 설명합니다.

VS Code라고도 알려진 Visual Studio Code는 모든 주요 운영 체제에서 사용할 수 있는 무료 소스 코드 편집기 또는 통합 개발 환경(IDE)입니다. 다양한 프로그래밍 언어에 대한 대규모 확장 모음을 통해 VS Code는

이 튜토리얼은 PHP를 사용하여 XML 문서를 효율적으로 처리하는 방법을 보여줍니다. XML (Extensible Markup Language)은 인간의 가독성과 기계 구문 분석을 위해 설계된 다목적 텍스트 기반 마크 업 언어입니다. 일반적으로 데이터 저장 AN에 사용됩니다

문자열은 문자, 숫자 및 기호를 포함하여 일련의 문자입니다. 이 튜토리얼은 다른 방법을 사용하여 PHP의 주어진 문자열의 모음 수를 계산하는 방법을 배웁니다. 영어의 모음은 A, E, I, O, U이며 대문자 또는 소문자 일 수 있습니다. 모음이란 무엇입니까? 모음은 특정 발음을 나타내는 알파벳 문자입니다. 대문자와 소문자를 포함하여 영어에는 5 개의 모음이 있습니다. a, e, i, o, u 예 1 입력 : String = "Tutorialspoint" 출력 : 6 설명하다 문자열의 "Tutorialspoint"의 모음은 u, o, i, a, o, i입니다. 총 6 개의 위안이 있습니다

숙련된 PHP 개발자라면 이미 그런 일을 해왔다는 느낌을 받을 것입니다. 귀하는 상당한 수의 애플리케이션을 개발하고, 수백만 줄의 코드를 디버깅하고, 여러 스크립트를 수정하여 작업을 수행했습니다.

Python은 배우기 쉽고 강력한 기능을 통해 초보자에게 이상적인 프로그래밍 입문 언어입니다. 기본 사항은 다음과 같습니다. 변수: 데이터(숫자, 문자열, 목록 등)를 저장하는 데 사용됩니다. 데이터 유형: 변수의 데이터 유형(정수, 부동 소수점 등)을 정의합니다. 연산자: 수학 연산 및 비교에 사용됩니다. 제어 흐름: 코드 실행(조건문, 루프) 흐름을 제어합니다.

Python은 초보자에게 문제 해결 능력을 부여합니다. 사용자 친화적인 구문, 광범위한 라이브러리 및 변수, 조건문 및 루프 사용 효율적인 코드 개발과 같은 기능을 제공합니다. 데이터 관리에서 프로그램 흐름 제어 및 반복 작업 수행에 이르기까지 Python은 제공합니다.

JWT는 주로 신분증 인증 및 정보 교환을 위해 당사자간에 정보를 안전하게 전송하는 데 사용되는 JSON을 기반으로 한 개방형 표준입니다. 1. JWT는 헤더, 페이로드 및 서명의 세 부분으로 구성됩니다. 2. JWT의 작업 원칙에는 세 가지 단계가 포함됩니다. JWT 생성, JWT 확인 및 Parsing Payload. 3. PHP에서 인증에 JWT를 사용하면 JWT를 생성하고 확인할 수 있으며 사용자 역할 및 권한 정보가 고급 사용에 포함될 수 있습니다. 4. 일반적인 오류에는 서명 검증 실패, 토큰 만료 및 대형 페이로드가 포함됩니다. 디버깅 기술에는 디버깅 도구 및 로깅 사용이 포함됩니다. 5. 성능 최적화 및 모범 사례에는 적절한 시그니처 알고리즘 사용, 타당성 기간 설정 합리적,
