Java客戶端訪問HBase集群解決方案(優化)

測試環境:Idea+Windows10

準備工作:

? ?<1>、打開本地 C:\Windows\System32\drivers\etc(系統默認)下名為hosts的系統文件,如果提示當前用戶沒有權限打開文件;第一種方法是將hosts文件拖到桌面進行配置后再拖回原處;第二種一勞永逸的方法是修改當前用戶對該文件的權限為完全控制;

? ?<2>、打開后hosts文件后,添加HBase集群服務器的用戶名及IP地址如下:

hosts文件參考格式?

? ?<3>、由于是windows系統下遠程連接HBase,而HBase底層依賴Hadoop,所以需要下載hadoop二進制包存放到本地目錄將來會在程序中引用該目錄,否則會報錯。你也可以理解為windows下需要模擬linux環境才能正常連接HBasehadoop;(注:windows下的版本需要和linux下一致,這里我僅僅提供的2.6.0hadoop版本解析包)

程序代碼:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.example</groupId><artifactId>spring_hbase</artifactId><version>0.0.1-SNAPSHOT</version><packaging>jar</packaging><name>spring_hbase</name><description>Demo project for Spring Boot</description><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.0.4.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><properties><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding><project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!--HBase依賴--><dependency><groupId>org.apache.hbase</groupId><artifactId>hbase-client</artifactId><version>1.2.0</version><exclusions><exclusion><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId></exclusion></exclusions></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-hadoop</artifactId><version>2.5.0.RELEASE</version></dependency><dependency><groupId>org.apache.hadoop</groupId><artifactId>hadoop-hdfs</artifactId><version>2.5.1</version></dependency><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-hadoop-core</artifactId><version>2.4.0.RELEASE</version></dependency><dependency><groupId>org.apache.hbase</groupId><artifactId>hbase</artifactId><version>1.2.1</version><type>pom</type></dependency><!--HBase依賴--></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

HBaseUtils.class:

package com.example.spring_hbase;import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*; import org.springframework.data.hadoop.hbase.HbaseTemplate; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; /** * HBase工具類 * Author JiaPeng_lv */ public class HBaseUtils { private static Connection connection; private static Configuration configuration; private static HBaseUtils hBaseUtils; private static Properties properties; /** * 創建連接池并初始化環境配置 */ public void init(){ properties = System.getProperties(); //實例化HBase配置類 if (configuration==null){ configuration = HBaseConfiguration.create(); } try { //加載本地hadoop二進制包 properties.setProperty("hadoop.home.dir", "D:\\hadoop-common-2.6.0-bin-master"); //zookeeper集群的URL配置信息 configuration.set("hbase.zookeeper.quorum","k1,k2,k3,k4,k5"); //HBase的Master configuration.set("hbase.master","hba:60000"); //客戶端連接zookeeper端口 configuration.set("hbase.zookeeper.property.clientPort","2181"); //HBase RPC請求超時時間,默認60s(60000) configuration.setInt("hbase.rpc.timeout",20000); //客戶端重試最大次數,默認35 configuration.setInt("hbase.client.retries.number",10); //客戶端發起一次操作數據請求直至得到響應之間的總超時時間,可能包含多個RPC請求,默認為2min configuration.setInt("hbase.client.operation.timeout",30000); //客戶端發起一次scan操作的rpc調用至得到響應之間的總超時時間 configuration.setInt("hbase.client.scanner.timeout.period",200000); //獲取hbase連接對象 if (connection==null||connection.isClosed()){ connection = ConnectionFactory.createConnection(configuration); } } catch (IOException e) { e.printStackTrace(); } } /** * 關閉連接池 */ public static void close(){ try { if (connection!=null)connection.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 私有無參構造方法 */ private HBaseUtils(){} /** * 唯一實例,線程安全,保證連接池唯一 * @return */ public static HBaseUtils getInstance(){ if (hBaseUtils == null){ synchronized (HBaseUtils.class){ if (hBaseUtils == null){ hBaseUtils = new HBaseUtils(); hBaseUtils.init(); } } } return hBaseUtils; } /** * 獲取單條數據 * @param tablename * @param row * @return * @throws IOException */ public static Result getRow(String tablename, byte[] row) throws IOException{ Table table = null; Result result = null; try { table = connection.getTable(TableName.valueOf(tablename)); Get get = new Get(row); result = table.get(get); }finally { table.close(); } return result; } /** * 查詢多行信息 * @param tablename * @param rows * @return * @throws IOException */ public static Result[] getRows(String tablename,List<byte[]> rows) throws IOException{ Table table = null; List<Get> gets = null; Result[] results = null; try { table = connection.getTable(TableName.valueOf(tablename)); gets = new ArrayList<Get>(); for (byte[] row : rows){ if(row!=null){ gets.add(new Get(row)); } } if (gets.size() > 0) { results = table.get(gets); } } catch (IOException e) { e.printStackTrace(); }finally { table.close(); } return results; } /** * 獲取整表數據 * @param tablename * @return */ public static ResultScanner get(String tablename) throws IOException{ Table table = null; ResultScanner results = null; try { table = connection.getTable(TableName.valueOf(tablename)); Scan scan = new Scan(); scan.setCaching(1000); results = table.getScanner(scan); } catch (IOException e) { e.printStackTrace(); }finally { table.close(); } return results; } /** * 單行插入數據 * @param tablename * @param rowkey * @param family * @param cloumns * @throws IOException */ public static void put(String tablename, String rowkey, String family, Map<String,String> cloumns) throws IOException{ Table table = null; try { table = connection.getTable(TableName.valueOf(tablename)); Put put = new Put(rowkey.getBytes()); for (Map.Entry<String,String> entry : cloumns.entrySet()){ put.addColumn(family.getBytes(),entry.getKey().getBytes(),entry.getValue().getBytes()); } table.put(put); } catch (IOException e) { e.printStackTrace(); }finally { table.close(); close(); } } } 

①、保證該工具類唯一實例

②、全局共享重量級類Connection,該類為線程安全,使用完畢后關閉連接池

③、每次執行內部CRUD方法會創建唯一對象Table,該類為非線程安全,使用完畢后關閉

由于時間原因,內部功能方法及測試較少,有其他需求的可以自行百度添加更多方法,這里主要以類結構及配置為主。

Test.class:

package com.example.spring_hbase;import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.util.Bytes;
import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.*; @RunWith(SpringRunner.class) @SpringBootTest public class SpringHbaseApplicationTests { @Test public void contextLoads() { } @Test public void test01(){ HBaseUtils.getInstance(); try { Long time = System.currentTimeMillis(); Result result = HBaseUtils.getRow("GPS_MAP", Bytes.toBytes(1)); System.out.println("本次查詢耗時:"+(System.currentTimeMillis()-time)*1.0/1000+"s"); NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>> navigableMap = result.getMap(); for (byte[] family:navigableMap.keySet()){ System.out.println("columnFamily:"+ new String(family)); for (byte[] column : navigableMap.get(family).keySet()){ System.out.println("column:"+new String(column)); for (Long t : navigableMap.get(family).get(column).keySet()){ System.out.println("value:"+new String(navigableMap.get(family).get(column).get(t))); } } } } catch (IOException e) { e.printStackTrace(); }finally { HBaseUtils.close(); } } @Test public void test02(){ HBaseUtils.getInstance(); ResultScanner results = null; try { Long time = System.currentTimeMillis(); results = HBaseUtils.get("GPS_MAP"); System.out.println("本次查詢耗時:"+(System.currentTimeMillis()-time)*1.0/1000+"s"); for (Result result : results){ NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>> navigableMap = result.getMap(); for (byte[] family:navigableMap.keySet()){ System.out.println("columnFamily:"+ new String(family)); for (byte[] column : navigableMap.get(family).keySet()){ System.out.println("column:"+new String(column)); for (Long t : navigableMap.get(family).get(column).keySet()){ System.out.println("value:"+new String(navigableMap.get(family).get(column).get(t))); } } } } } catch (IOException e) { e.printStackTrace(); }finally { results.close(); HBaseUtils.close(); } } @Test public void test03(){ HBaseUtils.getInstance(); Result[] results = null; List<byte[]> list = null; try { list = new ArrayList<byte[]>(); list.add(Bytes.toBytes(1)); list.add(Bytes.toBytes(2)); Long time = System.currentTimeMillis(); results = HBaseUtils.getRows("GPS_MAP",list); System.out.println("本次查詢耗時:"+(System.currentTimeMillis()-time)*1.0/1000+"s"); for (Result result : results){ NavigableMap<byte[],NavigableMap<byte[],NavigableMap<Long,byte[]>>> navigableMap = result.getMap(); for (byte[] family:navigableMap.keySet()){ System.out.println("columnFamily:"+ new String(family)); for (byte[] column : navigableMap.get(family).keySet()){ System.out.println("column:"+new String(column)); for (Long t : navigableMap.get(family).get(column).keySet()){ System.out.println("value:"+new String(navigableMap.get(family).get(column).get(t))); } } } } } catch (IOException e) { e.printStackTrace(); }finally { HBaseUtils.close(); } } @Test public void test04(){ HBaseUtils.getInstance(); try { Map<String,String> cloumns = new HashMap<String, String>(); cloumns.put("test01","test01"); cloumns.put("test02","test02"); Long time = System.currentTimeMillis(); HBaseUtils.put("GPS_MAP","3","TEST",cloumns); System.out.println("本次插入耗時:"+(System.currentTimeMillis()-time)*1.0/1000+"s"); } catch (IOException e) { e.printStackTrace(); }finally { HBaseUtils.close(); } } } 

測試后發現查詢和插入效率相對于沒有優化過的類耗時大大縮減;

轉載于:https://www.cnblogs.com/java-free/p/9522514.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/388756.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/388756.shtml
英文地址,請注明出處:http://en.pswp.cn/news/388756.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

WPF布局系統

WPF之路——WPF布局系統 前言 前段時間忙了一陣子Google Earth&#xff0c;這周又忙了一陣子架構師論文開題報告&#xff0c;現在終于有時間繼續<WPF之路>了。先回憶一下上篇的內容&#xff0c;在《從HelloWorld到WPF World》中&#xff0c;我們對WPF有了個大概的了解&am…

PostGIS容器運行

2019獨角獸企業重金招聘Python工程師標準>>> 獲取鏡像&#xff1a; docker pull mdillon/postgis 該 mdillon/postgis 鏡像提供了容器中運行Postgres&#xff08;內置安裝PostGIS 2.5&#xff09; 。該鏡像基于官方 postgres image&#xff0c;提供了多種變體&#…

小型數據庫_如果您從事“小型科學”工作,那么您是否正在利用數據存儲庫?

小型數據庫If you’re a scientist, especially one performing a lot of your research alone, you probably have more than one spreadsheet of important data that you just haven’t gotten around to writing up yet. Maybe you never will. Sitting idle on a hard dri…

BitmapEffect位圖效果是簡單的像素處理操作。它可以呈現下面幾種特殊效果。

BitmapEffect位圖效果是簡單的像素處理操作。它可以呈現下面幾種特殊效果。 BevelBitmapEffect 凹凸效果 BlurBitmapEffect 模糊效果 DropShadowBitmapEffect投影效果 EmbossBitmapEffect 浮雕效果 Outer…

AutoScaling 與函數計算結合,賦予更豐富的彈性能力

目前&#xff0c;彈性伸縮服務已經接入了負載均衡&#xff08;SLB&#xff09;、云數據庫RDS 等云產品&#xff0c;但是暫未接入 云數據庫Redis&#xff0c;有時候我們可能會需要彈性伸縮服務在擴縮容的時候自動將擴縮容涉及到的 ECS 實例私網 IP 添加到 Redis 白名單或者從 Re…

參考文獻_參考

參考文獻Recently, I am attracted by the news that Tanzania has attained lower middle income status under the World Bank’s classification, five years ahead of projection. Being curious on how they make the judgement, I take a look of the World Bank’s offi…

java語言靜態分析工具_PMD 6.16.0 發布,跨語言靜態代碼自動分析工具

PMD 6.16.0 發布了。PMD 是一個代碼分析器&#xff0c;能夠幫助發現常見的編程問題&#xff0c;比如未使用的變量、空的 catch 塊、不必要的對象創建等等。最初僅支持 Java 代碼&#xff0c;目前還可支持 JavaScript、Salesforce.com Apex 和 Visualforce、PLSQL、Apache Veloc…

B1922 [Sdoi2010]大陸爭霸 最短路

我一直都不會dij的堆優化&#xff0c;今天搞了一下。。。就是先弄一個優先隊列&#xff0c;存每個點的數據&#xff0c;然后這個題就加了一點不一樣的東西&#xff0c;每次的最短路算兩次&#xff0c;一次是自己的最短路&#xff0c;另一次是機關的最短路&#xff0c;兩者取最大…

WPF中的鼠標事件詳解

WPF中的鼠標事件詳解 Uielement和ContentElement都定義了十個以Mouse開頭的事件&#xff0c;8個以PreviewMouse開頭的事件&#xff0c;MouseMove,PreviewMouseMove,MouseEnter,Mouseleave的事件處理器類型都是MouseEventHandler類型。這些事件都具備對應得MouseEventargs對象。…

數據統計 測試方法_統計測試:了解如何為數據選擇最佳測試!

數據統計 測試方法This post is not meant for seasoned statisticians. This is geared towards data scientists and machine learning (ML) learners & practitioners, who like me, do not come from a statistical background.?他的職位是不是意味著經驗豐富的統計人…

前端介紹-35

前端介紹-35 # 前端## 一、什么是前端 前端即網站前臺部分&#xff0c;運行在PC端&#xff0c;移動端等瀏覽器上展現給用戶瀏覽的網頁。隨著互聯網技術的發展&#xff0c;HTML5&#xff0c;CSS3&#xff0c;前端框架的應用&#xff0c;跨平臺響應式網頁設計能夠適應各種屏幕…

spring的幾個通知(前置、后置、環繞、異常、最終)

1、沒有異常的 2、有異常的 1、被代理類接口Person.java 1 package com.xiaostudy;2 3 /**4 * desc 被代理類接口5 * 6 * author xiaostudy7 *8 */9 public interface Person { 10 11 public void add(); 12 public void update(); 13 public void delete();…

每個Power BI開發人員的Power Query提示

If someone asks you to define the Power Query, what should you say? If you’ve ever worked with Power BI, there is no chance that you haven’t used Power Query, even if you weren’t aware of it. Therefore, one could easily say that Power Query is the “he…

c# PDF 轉換成圖片

1.新建項目 2.新增一個新文件夾“lib”&#xff08;主要是為了存放引用的dll&#xff09; 3.將“gsdll32.dll 、PDFLibNet.dll 、PDFView.dll”3個dll添加到文件夾中 4.項目添加“PDFLibNet.dll 、PDFView.dll”2個類庫的引用&#xff0c;并將gsdll32.dll 拷貝到項目生產根…

java finally在return_Java finally語句到底是在return之前還是之后執行?

點擊上方“方志朋”&#xff0c;選擇“置頂或者星標”你的關注意義重大&#xff01;網上有很多人探討Java中異常捕獲機制try...catch...finally塊中的finally語句是不是一定會被執行&#xff1f;很多人都說不是&#xff0c;當然他們的回答是正確的&#xff0c;經過我試驗&#…

oracle 死鎖

為什么80%的碼農都做不了架構師&#xff1f;>>> ORA-01013: user requested cancel of current operation 轉載于:https://my.oschina.net/8808/blog/2994537

面試題:二叉樹的深度

題目描述&#xff1a;輸入一棵二叉樹&#xff0c;求該樹的深度。從根結點到葉結點依次經過的結點&#xff08;含根、葉結點&#xff09;形成樹的一條路徑&#xff0c;最長路徑的長度為樹的深度。 思路&#xff1a;遞歸 //遞歸 public class Solution {public int TreeDepth(Tre…

a/b測試_如何進行A / B測試?

a/b測試The idea of A/B testing is to present different content to different variants (user groups), gather their reactions and user behaviour and use the results to build product or marketing strategies in the future.A / B測試的想法是將不同的內容呈現給不同…

hibernate h2變mysql_struts2-hibernate-mysql開發案例 -解道Jdon

Hibernate專題struts2-hibernate-mysql開發案例與源碼源碼下載本案例展示使用Struts2&#xff0c;Hibernate和MySQL數據庫開發一個個人音樂管理器Web應用程序。&#xff0c;可將您的音樂收藏添加到數據庫中。功能有&#xff1a;顯示一個添加記錄的表單和所有的音樂收藏的列表。…

P5024 保衛王國

傳送門 我現在還是不明白為什么NOIPd2t3會是一道動態dp…… 首先關于動態dp可以看這里 然后這里就是把把矩陣給改一改&#xff0c;改成這個形式\[\left[dp_{i-1,0},dp_{i-1,1}\right]\times \left[\begin{matrix}\infty&ldp_{i,1}\\ldp_{i,0}&ldp_{i,1}\end{matrix}\ri…