SpringBoot 中項目中使用Habse

引入POM

<dependency>

 <groupId>org.apache.hbase</groupId>

 <artifactId>hbase-client</artifactId>

 <version>1.1.3</version>

 <exclusions>

 <exclusion>

 <groupId>org.slf4j</groupId>

 <artifactId>slf4j-log4j12</artifactId>

 </exclusion>

 <exclusion>

 <groupId>org.mortbay.jetty</groupId>

 <artifactId>servlet-api-2.5</artifactId>

 </exclusion>

 <exclusion>

 <groupId>org.mortbay.jetty</groupId>

 <artifactId>servlet-api-2.5-6.1.14</artifactId>

 </exclusion>

 <exclusion>

 <groupId>com.google.guava</groupId>

 <artifactId>guava</artifactId>

 </exclusion>

 </exclusions>

 </dependency>

 <dependency>

 <groupId>org.springframework.data</groupId>

 <artifactId>spring-data-hadoop-boot</artifactId>

 <version>[2.5.0.RELEASE](2.5.0.RELEASE)</version>

 <exclusions>

 <exclusion>

 <groupId>javax.servlet</groupId>

 <artifactId>servlet-api</artifactId>

 </exclusion>

 </exclusions>

 </dependency>

 <dependency>

 <groupId>org.springframework.data</groupId>

 <artifactId>spring-data-hadoop</artifactId>

 <version>[2.5.0.RELEASE](2.5.0.RELEASE)</version>

 <exclusions>

 <exclusion>

 <groupId>org.slf4j</groupId>

 <artifactId>slf4j-log4j12</artifactId>

 </exclusion>

 <exclusion>

 <groupId>log4j</groupId>

 <artifactId>log4j</artifactId>

 </exclusion>

 <exclusion>

 <groupId>javax.servlet</groupId>

 <artifactId>servlet-api</artifactId>

 </exclusion>

 </exclusions>

 </dependency>

 <dependency>

 <groupId>com.google.guava</groupId>

 <artifactId>guava</artifactId>

 <version>22.0</version>

 </dependency>

配置文件中 加入

hbase.config.hbase.zookeeper.quorum: XXX hbase.config.hbase.zookeeper.property.clientPort: XXXX

因為 pom Hbase引入了Guava 是13 的低版本 如果項目中引入了Guava 高版本的 需要在項目中重寫一個類 Stopwatch

package com.google.common.base;

package com.google.common.base;

/*

Copyright (C) 2008 The Guava Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

import com.google.common.annotations.GwtCompatible;

import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.base.Ticker;

import java.util.concurrent.TimeUnit;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.util.concurrent.TimeUnit.*;

/**
 * An object that measures elapsed time in nanoseconds. It is useful to measure
 * elapsed time using this class instead of direct calls to {@link
 * System#nanoTime} for a few reasons:
 * An alternate time source can be substituted, for testing or performance
 * reasons.
 * As documented by {@code nanoTime}, the value returned has no absolute
 * meaning, and can only be interpreted as relative to another timestamp
 * returned by {@code nanoTime} at a different time. {@code Stopwatch} is a
 * more effective abstraction because it exposes only these relative values,
 * not the absolute ones.
 * Basic usage:
 * <p>
 * Stopwatch stopwatch = Stopwatch.{@link #createStarted createStarted}();
 * doSomething();
 * stopwatch.{@link #stop stop}(); // optional
 * long millis = stopwatch.elapsed(MILLISECONDS);
 * log.info("time: " + stopwatch); // formatted string like "12.3 ms"
 * Stopwatch methods are not idempotent; it is an error to start or stop a
 * <p>
 * stopwatch that is already in the desired state.
 * When testing code that uses this class, use
 * <p>
 * {@link #createUnstarted(Ticker)} or {@link #createStarted(Ticker)} to
 * supply a fake or mock ticker.
 * This allows you to
 * simulate any valid behavior of the stopwatch.
 * Note: This class is not thread-safe.
 *
 * @author Kevin Bourrillion
 * @SInCE 10.0
 */
@Beta
@GwtCompatible(emulated = true)
public final class Stopwatch {
    private final Ticker ticker;
    private boolean isRunning;
    private long elapsedNanos;
    private long startTick;

    /**
     * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
     * as its time source.
     *
     * @SInCE 15.0
     */
    public static com.google.common.base.Stopwatch createUnstarted() {
        return new com.google.common.base.Stopwatch();
    }

    /**
     * Creates (but does not start) a new stopwatch, using the specified time
     * source.
     *
     * @SInCE 15.0
     */
    public static com.google.common.base.Stopwatch createUnstarted(Ticker ticker) {
        return new com.google.common.base.Stopwatch(ticker);
    }

    /**
     * Creates (and starts) a new stopwatch using {@link System#nanoTime}
     * as its time source.
     *
     * @SInCE 15.0
     */
    public static com.google.common.base.Stopwatch createStarted() {
        return new com.google.common.base.Stopwatch().start();
    }

    /**
     * Creates (and starts) a new stopwatch, using the specified time
     * source.
     *
     * @SInCE 15.0
     */
    public static com.google.common.base.Stopwatch createStarted(Ticker ticker) {
        return new com.google.common.base.Stopwatch(ticker).start();
    }

    /**
     * Creates (but does not start) a new stopwatch using {@link System#nanoTime}
     * as its time source.
     *
     * @deprecated Use {@link com.google.common.base.Stopwatch#createUnstarted()} instead.
     */
    @Deprecated
    public Stopwatch() {
        this(Ticker.systemTicker());
    }

    /**
     * Creates (but does not start) a new stopwatch, using the specified time
     * source.
     *
     * @deprecated Use {@link com.google.common.base.Stopwatch#createUnstarted(Ticker)} instead.
     */
    @Deprecated
    Stopwatch(Ticker ticker) {
        this.ticker = checkNotNull(ticker, "ticker");
    }

    /**
     * Returns {@code true} if {@link #start()} has been called on this stopwatch,
     * and {@link #stop()} has not been called since the last call to {@code
     * start()}.
     */
    public boolean isRunning() {
        return isRunning;
    }

    /**
     * Starts the stopwatch.
     *
     * @return this {@code Stopwatch} instance
     * @throws IllegalStateException if the stopwatch is already running.
     */
    public com.google.common.base.Stopwatch start() {
        checkState(!isRunning, "This stopwatch is already running.");
        isRunning = true;
        startTick = ticker.read();
        return this;
    }

    /**
     * Stops the stopwatch. Future reads will return the fixed duration that had
     * elapsed up to this point.
     *
     * @return this {@code Stopwatch} instance
     * @throws IllegalStateException if the stopwatch is already stopped.
     */
    public com.google.common.base.Stopwatch stop() {
        long tick = ticker.read();
        checkState(isRunning, "This stopwatch is already stopped.");
        isRunning = false;
        elapsedNanos += tick - startTick;
        return this;
    }

    /**
     * Sets the elapsed time for this stopwatch to zero,
     * and places it in a stopped state.
     *
     * @return this {@code Stopwatch} instance
     */
    public com.google.common.base.Stopwatch reset() {
        elapsedNanos = 0;
        isRunning = false;
        return this;
    }

    private long elapsedNanos() {
        return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos;
    }

    /**
     * Returns the current elapsed time shown on this stopwatch, expressed
     * in the desired time unit, with any fraction rounded down.
     * Note that the overhead of measurement can be more than a microsecond, so
     * <p>
     * it is generally not useful to specify {@link TimeUnit#NANOSECONDS}
     * precision here.
     *
     * @SInCE 14.0 (since 10.0 as {@code elapsedTime()})
     */
    public long elapsed(TimeUnit desiredUnit) {
        return desiredUnit.convert(elapsedNanos(), NANOSECONDS);
    }

    /**
     * Returns a string representation of the current elapsed time.
     */
    @GwtIncompatible("String.format()")
    @Override
    public String toString() {
        long nanos = elapsedNanos();
        TimeUnit unit = chooseUnit(nanos);
        double value = (double) nanos / NANOSECONDS.convert(1, unit);

// Too bad this functionality is not exposed as a regular method call
        return String.format("%.4g %s", value, abbreviate(unit));
    }

    private static TimeUnit chooseUnit(long nanos) {
        if (DAYS.convert(nanos, NANOSECONDS) > 0) {
            return DAYS;
        }
        if (HOURS.convert(nanos, NANOSECONDS) > 0) {
            return HOURS;
        }
        if (MINUTES.convert(nanos, NANOSECONDS) > 0) {
            return MINUTES;
        }
        if (SECONDS.convert(nanos, NANOSECONDS) > 0) {
            return SECONDS;
        }
        if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) {
            return MILLISECONDS;
        }
        if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) {
            return MICROSECONDS;
        }
        return NANOSECONDS;
    }

    private static String abbreviate(TimeUnit unit) {
        switch (unit) {
            case NANOSECONDS:
                return "ns";
            case MICROSECONDS:
                return "\u03bcs"; // μs
            case MILLISECONDS:
                return "ms";
            case SECONDS:
                return "s";
            case MINUTES:
                return "min";
            case HOURS:
                return "h";
            case DAYS:
                return "d";
            default:
                throw new AssertionError();
        }
    }
}


工具類

@Data
@Component
public class HbaseStorage {
    @Autowired(required = false)
    HbaseTemplate hbaseTemplate;
    private String familyName;

    public boolean save(String tableName,String rowKey,String familyName,Map<String,Object>  data) {
        if (StringUtils.isBlank(familyName)){
            throw new RuntimeException("請設置  默認 familyName 的值");
        }

        for (Map.Entry<String, Object> entry : data.entrySet()) {
            hbaseTemplate.put(tableName,rowKey,familyName,entry.getKey(), Bytes.toBytes(String.valueOf(entry.getValue())));
        }
        return true;
    }
    public <T>boolean save(String tableName,String rowKey,String familyName,T data) {
        Map<String, Object> dataMap = BaseBeanUtils.beanToMap(data);
        return save(tableName, rowKey, familyName, dataMap);
    }
    public <T>boolean save(String tableName,String rowKey,T data) {
        return save(tableName, rowKey, familyName, data);
    }



    public <T>List<T> getByPre (String tableName,String pre,Class<T> type){
        Map<String, Map<String,String>> resultMap = Maps.newHashMap();
        Scan scan = new Scan();
        Filter filter = new PrefixFilter(Bytes.toBytes(pre));
        scan.setFilter(filter);
        hbaseTemplate.find(tableName, scan, (RowMapper) (result, rowNum) -> {
            List<Cell> ceList = result.listCells();
            if (ceList != null && ceList.size() > 0) {
                for (Cell cell : ceList) {
                    String rowKey = Bytes.toString(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength());
                    String qualifierName = Bytes.toString(cell.getQualifierArray(), cell.getQualifierOffset(), cell.getQualifierLength());
                    String qualifierValue = Bytes.toString(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
                    if (!resultMap.containsKey(rowKey)){
                        resultMap.put(rowKey, Maps.newHashMap());
                    }
                    resultMap.get(rowKey).put(qualifierName, qualifierValue);
                }
            }
            return "";
        });

        List<T> list = Lists.newArrayList();
        for (Map.Entry<String, Map<String, String>> entry : resultMap.entrySet()) {
            T convert = BaseBeanUtils.convert(entry.getValue(), type);
            list.add(convert);
        }
        return list;
    }

    public static void main(String[] args) {
        Bean userContact = new Bean();
        userContact.setA("1");
        userContact.setB(1L);
        userContact.setC(1L);
        userContact.setF(1);
        userContact.setG(1);
        userContact.setH(new Object());
        userContact.setI(true);
        Map<String, String> result = Maps.newHashMap();
        Map<String, Object> stringObjectMap = BaseBeanUtils.beanToMap(userContact);
        System.out.println(stringObjectMap);
        for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {
            byte[] bytes = Bytes.toBytes(String.valueOf(entry.getValue()));
            result.put(entry.getKey(), Bytes.toString(bytes));
        }

        Bean convert = BaseBeanUtils.convert(result, Bean.class);
        System.out.println(convert);
    }



}

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 227,428評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,024評論 3 413
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 175,285評論 0 373
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,548評論 1 307
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,328評論 6 404
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 54,878評論 1 321
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 42,971評論 3 439
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,098評論 0 286
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,616評論 1 331
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,554評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,725評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,243評論 5 355
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 43,971評論 3 345
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,361評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,613評論 1 280
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,339評論 3 390
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,695評論 2 370

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,776評論 18 139
  • Spring Boot 參考指南 介紹 轉載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,887評論 6 342
  • 大學要找到自己真正感興趣的知識,然后努力學習,不管知識是本專業還是非專業,沒有任何的影響,但是關鍵點就是在于要學習...
    peterzyzson閱讀 241評論 0 0
  • 求職平臺提供的工作機會看似選擇很多,其實別無選擇。招聘方每天閱讀的簡歷目不暇接,有幸被邀請的面試,基本都會安排在第...
    d2b4348a5c47閱讀 441評論 0 1
  • 舅舅是鄉村醫生,一年四季都很忙,接到電話就要出門給別人看病。每年過年的幾天,才能休息一下。 這幾天,我在取暖屋里看...
    lucky乖乖魚閱讀 264評論 0 0