1.环境

  • Mysql 5.6
  • Sqoop 1.4.6
  • Hadoop 2.5.2
  • HBase 0.98
  • Elasticsearch 2.3.5

2.安装(略过)

3.HBase Coprocessor实现

HBase Observer

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.CoprocessorEnvironment;
import org.apache.hadoop.hbase.client.Delete;
import org.apache.hadoop.hbase.client.Durability;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
import org.apache.hadoop.hbase.coprocessor.ObserverContext;
import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
import org.apache.hadoop.hbase.util.Bytes;
import org.elasticsearch.client.Client;
//import org.elasticsearch.client.transport.TransportClient;
//import org.elasticsearch.common.settings.ImmutableSettings;
//import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.InetSocketTransportAddress; import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//import java.util.NavigableMap; public class DataSyncObserver extends BaseRegionObserver { private static Client client = null;
private static final Log LOG = LogFactory.getLog(DataSyncObserver.class); /**
* 读取HBase Shell的指令参数
*
* @param env
*/
private void readConfiguration(CoprocessorEnvironment env) {
Configuration conf = env.getConfiguration();
Config.clusterName = conf.get("es_cluster");
Config.nodeHost = conf.get("es_host");
Config.nodePort = conf.getInt("es_port", -);
Config.indexName = conf.get("es_index");
Config.typeName = conf.get("es_type"); LOG.info("observer -- started with config: " + Config.getInfo());
} @Override
public void start(CoprocessorEnvironment env) throws IOException {
readConfiguration(env);
// Settings settings = ImmutableSettings.settingsBuilder()
// .put("cluster.name", Config.clusterName).build();
// client = new TransportClient(settings)
// .addTransportAddress(new InetSocketTransportAddress(
// Config.nodeHost, Config.nodePort));
client = MyTransportClient.client;
} @Override
public void postPut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability) throws IOException {
try {
String indexId = new String(put.getRow());
Map<byte[], List<Cell>> familyMap = put.getFamilyCellMap();
// NavigableMap<byte[], List<Cell>> familyMap = put.getFamilyCellMap();
Map<String, Object> json = new HashMap<String, Object>();
for (Map.Entry<byte[], List<Cell>> entry : familyMap.entrySet()) {
for (Cell cell : entry.getValue()) {
String key = Bytes.toString(CellUtil.cloneQualifier(cell));
String value = Bytes.toString(CellUtil.cloneValue(cell));
json.put(key, value);
}
}
System.out.println();
ElasticSearchOperator.addUpdateBuilderToBulk(client.prepareUpdate(Config.indexName, Config.typeName, indexId).setDoc(json).setUpsert(json));
LOG.info("observer -- add new doc: " + indexId + " to type: " + Config.typeName);
} catch (Exception ex) {
LOG.error(ex);
}
} @Override
public void postDelete(final ObserverContext<RegionCoprocessorEnvironment> e, final Delete delete, final WALEdit edit, final Durability durability) throws IOException {
try {
String indexId = new String(delete.getRow());
ElasticSearchOperator.addDeleteBuilderToBulk(client.prepareDelete(Config.indexName, Config.typeName, indexId));
LOG.info("observer -- delete a doc: " + indexId);
} catch (Exception ex) {
LOG.error(ex);
}
} }

ES方法

import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.update.UpdateRequestBuilder;
import org.elasticsearch.client.Client;
//import org.elasticsearch.client.transport.TransportClient;
//import org.elasticsearch.common.settings.ImmutableSettings;
//import org.elasticsearch.common.settings.Settings;
//import org.elasticsearch.common.transport.InetSocketTransportAddress; import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; public class ElasticSearchOperator { // 缓冲池容量
private static final int MAX_BULK_COUNT = ;
// 最大提交间隔(秒)
private static final int MAX_COMMIT_INTERVAL = * ; private static Client client = null;
private static BulkRequestBuilder bulkRequestBuilder = null; private static Lock commitLock = new ReentrantLock(); static { // elasticsearch1.5.0
// Settings settings = ImmutableSettings.settingsBuilder()
// .put("cluster.name", Config.clusterName).build();
// client = new TransportClient(settings)
// .addTransportAddress(new InetSocketTransportAddress(
// Config.nodeHost, Config.nodePort)); // 2.3.5
client = MyTransportClient.client; bulkRequestBuilder = client.prepareBulk();
bulkRequestBuilder.setRefresh(true); Timer timer = new Timer();
timer.schedule(new CommitTimer(), * , MAX_COMMIT_INTERVAL * );
} /**
* 判断缓存池是否已满,批量提交
*
* @param threshold
*/
private static void bulkRequest(int threshold) {
if (bulkRequestBuilder.numberOfActions() > threshold) {
BulkResponse bulkResponse = bulkRequestBuilder.execute().actionGet();
if (!bulkResponse.hasFailures()) {
bulkRequestBuilder = client.prepareBulk();
}
}
} /**
* 加入索引请求到缓冲池
*
* @param builder
*/
public static void addUpdateBuilderToBulk(UpdateRequestBuilder builder) {
commitLock.lock();
try {
bulkRequestBuilder.add(builder);
bulkRequest(MAX_BULK_COUNT);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
commitLock.unlock();
}
} /**
* 加入删除请求到缓冲池
*
* @param builder
*/
public static void addDeleteBuilderToBulk(DeleteRequestBuilder builder) {
commitLock.lock();
try {
bulkRequestBuilder.add(builder);
bulkRequest(MAX_BULK_COUNT);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
commitLock.unlock();
}
} /**
* 定时任务,避免RegionServer迟迟无数据更新,导致ElasticSearch没有与HBase同步
*/
static class CommitTimer extends TimerTask {
@Override
public void run() {
commitLock.lock();
try {
bulkRequest();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
commitLock.unlock();
}
}
} }

打包并上传到hdfs

mvn clean compile assembly:single
mv observer-1.0-SNAPSHOT-jar-with-dependencies.jar observer-hb0.-es2.3.5.jar
hdfs dfs -put observer-hb0.-es2.3.5.jar /hbase/lib/

4.创建HBase表,并启用Coprocessor

mysql

hbase shell
create 'region','data'
disable 'region'
alter 'region', METHOD => 'table_att', 'coprocessor' => 'hdfs:///hbase/lib/observer-hb0.98-es2.3.5.jar|com.gavin.observer.DataSyncObserver|1001|es_cluster=elas2.3.4,es_type=mysql_region,es_index=hbase,es_port=9300,es_host=localhost'
enable 'region'

oracle

create 'sp','data'
disable 'sp'
alter 'sp', METHOD => 'table_att', 'coprocessor' => 'hdfs:///hbase/lib/observer-hb0.98-es2.3.5.jar|com.gavin.observer.DataSyncObserver|1001|es_cluster=elas2.3.4,es_type=oracle_sp,es_index=hbase,es_port=9300,es_host=localhost'
enable 'sp'

查看

hbase(main)::* describe 'ora_test'
Table ora_test is ENABLED
ora_test, {TABLE_ATTRIBUTES => {coprocessor$ => 'hdfs:///appdt/hbase
/lib/observer-hb1.2.2-es2.3.5.jar|com.gavin.observer.DataSyncObserver
||es_cluster=elas2.3.4,es_type=ora_test,es_index=hbase,es_port=
,es_host=localhost'}
COLUMN FAMILIES DESCRIPTION
{NAME => 'data', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW',
REPLICATION_SCOPE => '', VERSIONS => '', COMPRESSION => 'NONE', MI
N_VERSIONS => '', TTL => 'FOREVER', KEEP_DELETED_CELLS => 'FALSE', B
LOCKSIZE => '', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
row(s) in 0.0260 seconds

删除Coprocessor

disable 'ora_test'
alter 'ora_test',METHOD => 'table_att_unset',NAME =>'coprocessor$1'
enable 'ora_test'

查看删除效果

hbase(main)::> describe 'ora_test'
Table ora_test is ENABLED
ora_test
COLUMN FAMILIES DESCRIPTION
{NAME => 'data', DATA_BLOCK_ENCODING => 'NONE', BLOOMFILTER => 'ROW',
REPLICATION_SCOPE => '', VERSIONS => '', COMPRESSION => 'NONE', MI
N_VERSIONS => '', TTL => 'FOREVER', KEEP_DELETED_CELLS => 'FALSE', B
LOCKSIZE => '', IN_MEMORY => 'false', BLOCKCACHE => 'true'}
row(s) in 0.0200 seconds

5.使用sqoop上传数据

mysql

bin/sqoop import --connect jdbc:mysql://192.168.1.187:3306/trade_dev --username mysql --password 111111 --table TB_REGION --hbase-table region --hbase-row-key REGION_ID --column-family data

oracle

bin/sqoop import --connect jdbc:oracle:thin:@192.168.16.223:/orcl --username sitts --password password --table SITTS.ESB_SERVICE_PARAM --split-by PARAM_ID --hbase-table sp --hbase-row-key PARAM_ID --column-family data

6.校验

HBase

scan 'region'

ES

7.参考

HBase Observer同步数据到ElasticSearch

8.注意

  • 同一个Coprocessor用一个index,不同表可以设置不同type,不然index会乱
  • 修改Java代码后,上传到HDFS的jar包文件必须和之前不一样,否则就算卸载掉原有的coprocessor再重新安装也不能生效
  • 如果你有多个表对多个索引/类型的映射,每个表所加载Observer对应的jar包路径不能相同,否则ElasticSearch会串数据

Sqoop导入HBase,并借助Coprocessor协处理器同步索引到ES的更多相关文章

  1. sqoop与hbase导入导出数据

    环境:sqoop1.4.6+hadoop2.6+hbase1.1+mysql5.7 说明: 1.文中的导入导出的表结构借鉴了网上的某篇博客 2.mysql导入hbase可以直接通过sqoop进行 3. ...

  2. HBase协处理器同步二级索引到Solr

    一. 背景二. 什么是HBase的协处理器三. HBase协处理器同步数据到Solr四. 添加协处理器五. 测试六. 协处理器动态加载 一. 背景 在实际生产中,HBase往往不能满足多维度分析,我们 ...

  3. 使用sqoop将MySQL数据库中的数据导入Hbase

    使用sqoop将MySQL数据库中的数据导入Hbase 前提:安装好 sqoop.hbase. 下载jbdc驱动:mysql-connector-java-5.1.10.jar 将 mysql-con ...

  4. HBase 二级索引与Coprocessor协处理器

    Coprocessor简介 (1)实现目的 HBase无法轻易建立“二级索引”: 执行求和.计数.排序等操作比较困难,必须通过MapReduce/Spark实现,对于简单的统计或聚合计算时,可能会因为 ...

  5. Sqoop导入mysql数据到Hbase

    sqoop import --driver com.mysql.jdbc.Driver --connect "jdbc:mysql://11.143.18.29:3306/db_1" ...

  6. Sqoop将mysql数据导入hbase的血与泪

    Sqoop将mysql数据导入hbase的血与泪(整整搞了大半天)  版权声明:本文为yunshuxueyuan原创文章.如需转载请标明出处: https://my.oschina.net/yunsh ...

  7. sqoop将mysql数据导入hbase、hive的常见异常处理

    原创不易,如需转载,请注明出处https://www.cnblogs.com/baixianlong/p/10700700.html,否则将追究法律责任!!! 一.需求: 1.将以下这张表(test_ ...

  8. 使用Observer实现HBase到Elasticsearch的数据同步

    最近在公司做统一日志收集处理平台,技术选型肯定要选择elasticsearch,因为可以快速检索系统日志,日志问题排查及功业务链调用可以被快速检索,公司各个应用的日志有些字段比如说content是不需 ...

  9. Oracle数据导入Hbase操作步骤

    ——本文非本人原创,为公司同事整理,发布至此以便查阅 一.入库前数据准备 1.入hbase详细要求及rowkey生成规则,参考文档“_入HBase库要求 20190104.docx”. 2.根据标准库 ...

随机推荐

  1. Android学习之蓝牙操作

    BluetoothAdapter 用法 蓝牙运行原理:通过BluetoothAdapter 蓝牙适配器处理任务,如果蓝牙被启动之后,系统会自动去搜索其它设备,如果匹配到附近的设备就发送一个广播,Bro ...

  2. 《转载》Eclipse项目上传码云

    本文转载自http://blog.csdn.net/izzyliao/article/details/53074452 把Eclipse项目上传到码云的步骤: 1.登录码云:新建项目 2.输入项目名: ...

  3. 推荐系统之基于图的推荐:基于随机游走的PersonalRank算法

    转自http://blog.csdn.net/sinat_33741547/article/details/53002524 一 基本概念 基于图的模型是推荐系统中相当重要的一种方法,以下内容的基本思 ...

  4. pace.js简介

    Pace.js – 超赞的页面加载进度自动指示和 Ajax 导航效果 在页面中引入 Pace.js 和您所选择主题的 CSS 文件,就可以让你的页面拥有漂亮的加载进度和 Ajax 导航效果.不需要挂接 ...

  5. springbatch---->springbatch的使用(二)

    这里我们对springbatch做一个比较深入的学习例子,解压文件,读取文件内容过滤写入到数据库中.如果你掉进了黑暗里,你能做的,不过是静心等待,直到你的双眼适应黑暗. springbatch的使用案 ...

  6. photobeamer

    NOKIA出品的photobeamer https://www.photobeamer.com/你打开这个网站,会生成的二维码手机上打开photobeamer这个软件,选择要显示的相片,再扫描刚才网页 ...

  7. Linux下重启mysql的时候出现 start: Job failed to start

    mysql进程自己退出了,使用如下指令确认mysql进程不在了. ps -ef | grep mysql 看不到mysql进程 mysql进程不在,尽快回复服务的想法,就是重启服务 /etc/init ...

  8. 8.21 js

    2018-8-21 20:05:43 2018-8-21 20:56:30 明天再看!!!! 今天空闲多看了书 <百年孤独> <苏东坡传> 打印结果  shanghai js的 ...

  9. 利用 :first-child 和 :nth-last-child 确定子元素数目

    读<css揭秘>时,发现选择器的神奇作用,可以确定子元素数目,比如: li:first-child:nth-last-child(2),li:first-child:nth-last-ch ...

  10. mysql的启动脚本mysql.server及示例配置文件

    以MySQL-server-4.0.14-0.i3862881064151.rpm为例,放在/data目录下 cd /data rpm -ivh MySQL-server-4.0.14-0.i386. ...