1. 程式人生 > >Hbase 學習筆記一 》Example

Hbase 學習筆記一 》Example

Putting it all together Example

Now that you’ve seen how to interact with HBase, let’s assemble what you know into a

working example. To start, define a simple model object for the User instances, as in

the next listing.

<span style="font-size:14px;">package HBaseIA.TwitBase.model;
public abstract class User {
public String user;
public String name;
public String email;
public String password;
@Override
public String toString() {
return String.format("<User: %s, %s, %s>", user, name, email);
}
}</span>

Let’s wrap all the user-centric HBase interactions in a single class. Start by declaring

the commonly used byte[] constants. Then define some helper methods to encapsulate

command creation. Follow that with the public interfaces and a private implementation

of the User model, as shown next.

<span style="font-size:14px;"><pre name="code" class="java">package HBaseIA.TwitBase.hbase;


//...
public class UsersDAO {
    public static final byte[] TABLE_NAME = Bytes.toBytes("users");
    public static final byte[] INFO_FAM = Bytes.toBytes("info");
    private static final byte[] USER_COL = Bytes.toBytes("user");
    private static final byte[] NAME_COL = Bytes.toBytes("name");
    private static final byte[] EMAIL_COL = Bytes.toBytes("email");
    private static final byte[] PASS_COL = Bytes.toBytes("password");
    public static final byte[] TWEETS_COL = Bytes.toBytes("tweet_count");
    private HTablePool pool;


    public UsersDAO(HTablePool pool) {
        this.pool = pool;
    }


    private static Get mkGet(String user) {
        Get g = new Get(Bytes.toBytes(user));
        g.addFamily(INFO_FAM);


        return g;
    }


    private static Put mkPut(User u) {
        Put p = new Put(Bytes.toBytes(u.user));
        p.add(INFO_FAM, USER_COL, Bytes.toBytes(u.user));
        p.add(INFO_FAM, NAME_COL, Bytes.toBytes(u.name));
        p.add(INFO_FAM, EMAIL_COL, Bytes.toBytes(u.email));
        p.add(INFO_FAM, PASS_COL, Bytes.toBytes(u.password));


        return p;
    }


    private static Delete mkDel(String user) {
        Delete d = new Delete(Bytes.toBytes(user));


        return d;
    }


    public void addUser(String user, String name, String email, String password)
        throws IOException {
        HTableInterface users = pool.getTable(TABLE_NAME);
        Put p = mkPut(new User(user, name, email, password));
        users.put(p);
        users.close();
    }


    public HBaseIA.TwitBase.model.User getUser(String user)
        throws IOException {
        HTableInterface users = pool.getTable(TABLE_NAME);
        Get g = mkGet(user);
        Result result = users.get(g);


        if (result.isEmpty()) {
            return null;
        }


        User u = new User(result);
        users.close();


        return u;
    }


    public void deleteUser(String user) throws IOException {
        HTableInterface users = pool.getTable(TABLE_NAME);
        Delete d = mkDel(user);
        users.delete(d);
        users.close();
    }


    private static class User extends HBaseIA.TwitBase.model.User {
        private User(Result r) {
            this(r.getValue(INFO_FAM, USER_COL),
                r.getValue(INFO_FAM, NAME_COL),
                r.getValue(INFO_FAM, EMAIL_COL),
                r.getValue(INFO_FAM, PASS_COL),
                (r.getValue(INFO_FAM, TWEETS_COL) == null) ? Bytes.toBytes(0L)
                                                           : r.getValue(
                    INFO_FAM, TWEETS_COL));
        }


        private User(byte[] user, byte[] name, byte[] email, byte[] password,
            byte[] tweetCount) {
            this(Bytes.toString(user), Bytes.toString(name),
                Bytes.toString(email), Bytes.toString(password));
            this.tweetCount = Bytes.toLong(tweetCount);
        }


        private User(String user, String name, String email, String password) {
            this.user = user;
            this.name = name;
            this.email = email;
            this.password = password;
        }
    }
}
</span>

Listing 2.1 Userdata model

Listing 2.2 CRUD operations in UsersDAO.

The last piece of this puzzle is a main() method. Let’s make a UsersTool, shown in the

next listing, to simplify interaction with the users table in HBase.

<span style="font-size:14px;">package HBaseIA.TwitBase;

//...
public class UsersTool {
    public static final String usage = "UsersTool action ...\n" +
        " help - print this message and exit.\n" +
        " add user name email password" + " - add a new user.\n" +
        " get user - retrieve a specific user.\n" +
        " list - list all installed users.\n";

    public static void main(String[] args) throws IOException {
        if ((args.length == 0) || "help".equals(args[0])) {
            System.out.println(usage);
            System.exit(0);
        }

        HTablePool pool = new HTablePool();
        UsersDAO dao = new UsersDAO(pool);

        if ("get".equals(args[0])) {
            System.out.println("Getting user " + args[1]);

            User u = dao.getUser(args[1]);
            System.out.println(u);
        }

        if ("add".equals(args[0])) {
            System.out.println("Adding user...");
            dao.addUser(args[1], args[2], args[3], args[4]);

            User u = dao.getUser(args[1]);
            System.out.println("Successfully added user " + u);
        }

        if ("list".equals(args[0])) {
            for (User u : dao.getUsers()) {
                System.out.println(u);
            }
        }

        pool.closeTablePool(UsersDAO.TABLE_NAME);
    }
}
</span>

With all the code available, you can try the whole thing. In the root directory of this

book’s source code, compile the application jar:

<span style="font-size:14px;">$ mvn package
...
[INFO] -----------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] -----------------------------------------------------
[INFO] Total time: 20.467s</span>

This produces a twitbase-1.0.0.jar file in the target directory.

Using UsersTool to add Mark to the users table is easy:

$ java -cp target/twitbase-1.0.0.jar \

<span style="font-size:14px;">HBaseIA.TwitBase.UsersTool \
add \
TheRealMT \
"Mark Twain" \
[email protected] \
abc123
Successfully added user <User: TheRealMT></span>

You can list the contents of your table:

<span style="font-size:14px;">$ java -cp target/twitbase-1.0.0.jar \
HBaseIA.TwitBase.UsersTool \
list
21:49:30 INFO cli.UsersTool: Found 1 users.
<User: TheRealMT></span>

Now that you’ve seen a little of how to interact with HBase, let’s better understand the

logical and physical data models present in HBase.

相關推薦

Hbase 學習筆記Example

Putting it all together Example Now that you’ve seen how to interact with HBase, let’s assemble what you know into a working example. To

hbase 學習筆記---基本概念

      說在前面,本文部分內容來源於社群官網經過適度翻譯,部分根據經驗總結,部分是抄襲網路博文,(不一一列舉引用,在此致歉)一併列在一起,本文的目的,希望能總結出一些有用的,應該注意到的東西,基本思路是先提出一個話題,在此話題內,把相關聯的東西加進去,而不是單獨分出章節單獨介紹,雖然條理性欠差,但有利於後

hbase學習筆記

hbase Hbase是一個分散式的、持久的、強一致性的儲存系統,具有近似最優的寫效能(能使I/O利用率達到飽和)和出色的讀效能,他充分利用了磁碟的空間,支援特定列族切換可壓縮演算法。 HBase繼承自BigTable模型,只考慮單一的索引,類似於RDBMS

HBase學習筆記)——基礎入門

1、what:什麼是HBase HBase的原型是Google的BigTable論文,受到了該論文思想的啟發,目前作為Hadoop的子專案來開發維護,用於支援結構化的資料儲存。 HBase是一個高可靠性、高效能、面向列、可伸縮的分散式儲存系統,利用HBASE技術可在廉價PC Server上搭建起大規模結構化儲

AngularJS入門學習筆記

rect directive 技術分享 attr 兩個 ava 內容 module 大括號 首先聲明: 本博客源自於學習:跟我學AngularJs:AngularJs入門及第一個實例。通過學習,我自己的一些學習筆記。 1.AngularJS的一些基本特性 (1)使用雙大括號

Halcon學習筆記()

direct fusion 采集 das com nom pat 學習 filter 一、Halcon編程之圖像處理 1、讀取圖片 1、讀取單個圖片: 1.1 直接用算子read_image read_image (Image, ‘D:/3.tiff‘) 2

django學習筆記

site url ssa .com tin sessions .site add 註冊 2017年5月9日 ps 強烈推薦,django教程寫的很棒 http://code.ziqiangxuetang.com/django/django-tutorial.html 〇

Linux學習筆記()

版本 家目錄 動向 用戶 lin 絕對路徑 退出 鏈接庫 智能提示 1、Ubuntu 版本主版本年號+副版本月號,4月為穩定版,10月為測試版,單數為短期支持,雙數為長期支持。 2、shell為命令解析器,(shell--unix,bash--linux),大家也將bash

Tomcat學習筆記()

manage linux下 star bin servlet users 分析 clas oca Tomcat目錄結構的認識   tomcat是Apache旗下的一個開源Servlet的容器,實現了對Servlet和JSP技術支持。 通過http://tomcat

ELK學習筆記()---安裝ELK 5.x版

elk安裝ELK日誌平臺是一個完整的日誌分析系統,有三個開源工具構建組成,分別是:Elasticsearch、Logstash和Kibana。Elasticsearch用於數據分析和深度搜索;Logstash作用是從其他服務器上傳輸和轉發日誌,對其集中管理,進行分析;Kibana則是提供了強大的UI展示,將數

Git學習筆記()

編譯 缺點 watermark 索引 規範 存在 alt 回退 dsm 版本號控制系統簡單介紹 版本號控制系統是一種記錄若幹文件內容變化。以便將來查閱特定版本號修訂情況的系統。該系統不僅能夠度軟件源碼的文本文件進行版本號控制管理。也能夠對不論什麽其它類型的文件進行版本號

轉:C#制作ORM映射學習筆記 自定義Attribute類

技術 sage 其中 username pac ont 學習 collect reat 之前在做unity項目時發現只能用odbc連接數據庫,感覺非常的麻煩,因為之前做web開發的時候用慣了ORM映射,所以我想在unity中也用一下ORM(雖然我知道出於性能的考慮這樣做事不

ES6學習筆記()

message 提升 java syn log mes scrip 默認值 script 1.ES6學習之let、const (1).var、let、const 變(常)量聲明 ES5 只有全局作用域和函數作用域,沒有塊級作用域,這帶來很多不合理的場景。 在ES6中l

backbone學習筆記

router 內置 ear cti small 失敗 str 視圖view 避免 事件event on(bind) 在對象上綁定一個函數,只要該event被觸發,綁定函數即被調用。可以用第三個參數提供一個上下文 off(unbind) 移除對象上綁定的函數,可以傳遞上下文和

Microsoft.SQL.Server2012.Performance.Tuning.Cookbook學習筆記()

str perm phi prev pid brush -c rpc enabled 一、Creating a trace or workload 註意點: In the Trace Properties dialog box, there is a checkbox op

python學習筆記()

href ons xxx 自動下載 fail 響應 cdn pat pda   因為工作需要,經常需要到新浪某博客去找資料,在博文目錄裏一頁頁地肉眼搜索,看到合適的標題再點擊開鏈接查看內容,知道合適地再復制下來。很煩人。於是一直有個想法,學會爬蟲。   拿著單位發的購書卡去

QuartZ .Net 學習筆記: 源碼下載與查看

net href cnblogs 方法 category solution ges 博客 存在 最近因為工作需要研究一下QuartZ .net , 之前也用過不過但沒有深入了解, 現想深入研究一下 網上相關QuartZ .net 的文章不少, 但大部分都是源於張善友的博

Redis 學習筆記

支持 模式 包括 sun 有序 網頁 hyper 原子 類型 Redis特點:   1、速度快   2、支持豐富的數據類型:字符串、哈希列表、集合   3、操作具有原子性,所有Redis操作都是原子操作   4、多實用工具,可應用如緩存,消息隊列,應用程序中任何短期數據,如

React學習筆記

pre class cnblogs har set head 源碼 span dom 一:安裝react 1:直接下載react源碼包,把需要用到的js文件引入自己的頁面即可。 2:BootCDN 的 React CDN 庫: 在頁面代碼中導入即可: <head&

【canvas學習筆記】基本認識

基本認識 設置 supported eight -c 失真 ont 之前 上下 <canvas>標簽定義了一塊畫布,畫布可以在網頁中繪制2D和3D圖象,現在先學習如何繪制2D圖象,繪制3D圖象屬於WebGL的內容(也就是網頁版的OpenGL,3D圖形接口)。 屬