SpringBoot 中項(xiàng)目中使用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

因?yàn)?pom Hbase引入了Guava 是13 的低版本 如果項(xiàng)目中引入了Guava 高版本的 需要在項(xiàng)目中重寫一個類 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("請?jiān)O(shè)置  默認(rèn) 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);
    }



}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末茵瀑,一起剝皮案震驚了整個濱河市絮宁,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌抽米,老刑警劉巖诡宗,帶你破解...
    沈念sama閱讀 218,451評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件玄糟,死亡現(xiàn)場離奇詭異磷籍,居然都是意外死亡堰氓,警方通過查閱死者的電腦和手機(jī)芽淡,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,172評論 3 394
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來豆赏,“玉大人挣菲,你說我怎么就攤上這事≈腊睿” “怎么了白胀?”我有些...
    開封第一講書人閱讀 164,782評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長抚岗。 經(jīng)常有香客問我或杠,道長,這世上最難降的妖魔是什么宣蔚? 我笑而不...
    開封第一講書人閱讀 58,709評論 1 294
  • 正文 為了忘掉前任向抢,我火速辦了婚禮认境,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘挟鸠。我一直安慰自己叉信,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,733評論 6 392
  • 文/花漫 我一把揭開白布艘希。 她就那樣靜靜地躺著硼身,像睡著了一般。 火紅的嫁衣襯著肌膚如雪覆享。 梳的紋絲不亂的頭發(fā)上佳遂,一...
    開封第一講書人閱讀 51,578評論 1 305
  • 那天,我揣著相機(jī)與錄音撒顿,去河邊找鬼丑罪。 笑死,一個胖子當(dāng)著我的面吹牛凤壁,可吹牛的內(nèi)容都是我干的吩屹。 我是一名探鬼主播,決...
    沈念sama閱讀 40,320評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼客扎,長吁一口氣:“原來是場噩夢啊……” “哼祟峦!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起徙鱼,我...
    開封第一講書人閱讀 39,241評論 0 276
  • 序言:老撾萬榮一對情侶失蹤宅楞,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后袱吆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體厌衙,經(jīng)...
    沈念sama閱讀 45,686評論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,878評論 3 336
  • 正文 我和宋清朗相戀三年绞绒,在試婚紗的時候發(fā)現(xiàn)自己被綠了婶希。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 39,992評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡蓬衡,死狀恐怖喻杈,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情狰晚,我是刑警寧澤筒饰,帶...
    沈念sama閱讀 35,715評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站壁晒,受9級特大地震影響瓷们,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,336評論 3 330
  • 文/蒙蒙 一谬晕、第九天 我趴在偏房一處隱蔽的房頂上張望碘裕。 院中可真熱鬧,春花似錦攒钳、人聲如沸帮孔。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,912評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽你弦。三九已至惊豺,卻和暖如春燎孟,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背尸昧。 一陣腳步聲響...
    開封第一講書人閱讀 33,040評論 1 270
  • 我被黑心中介騙來泰國打工揩页, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人烹俗。 一個月前我還...
    沈念sama閱讀 48,173評論 3 370
  • 正文 我出身青樓爆侣,卻偏偏與公主長得像,于是被迫代替她去往敵國和親幢妄。 傳聞我的和親對象是個殘疾皇子兔仰,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,947評論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn)蕉鸳,斷路器乎赴,智...
    卡卡羅2017閱讀 134,657評論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,815評論 6 342
  • 大學(xué)要找到自己真正感興趣的知識,然后努力學(xué)習(xí)潮尝,不管知識是本專業(yè)還是非專業(yè)榕吼,沒有任何的影響,但是關(guān)鍵點(diǎn)就是在于要學(xué)習(xí)...
    peterzyzson閱讀 236評論 0 0
  • 求職平臺提供的工作機(jī)會看似選擇很多顽素,其實(shí)別無選擇。招聘方每天閱讀的簡歷目不暇接徒蟆,有幸被邀請的面試胁出,基本都會安排在第...
    d2b4348a5c47閱讀 425評論 0 1
  • 舅舅是鄉(xiāng)村醫(yī)生,一年四季都很忙后专,接到電話就要出門給別人看病划鸽。每年過年的幾天,才能休息一下。 這幾天裸诽,我在取暖屋里看...
    lucky乖乖魚閱讀 253評論 0 0