应用Flume+HBase采集和存储日志数据

1. 在本方案中,我们要将数据存储到HBase中,所以使用flume中提供的hbase sink,同时,为了清洗转换日志数据,我们实现自己的AsyncHbaseEventSerializer

package com.ncc.dlut;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.conf.ComponentConfiguration;
import org.apache.flume.sink.hbase.AsyncHbaseEventSerializer;
import org.apache.flume.sink.hbase.SimpleRowKeyGenerator;
import org.hbase.async.AtomicIncrementRequest;
import org.hbase.async.PutRequest;

public class AsyncHbaseLTEEventSerializer implements AsyncHbaseEventSerializer {
    //表名
    private byte[] table;
    //列族
    private byte[] colFam;
    //当前事件
    private Event currentEvent;
    //列名
    private byte[][] columnNames;
    //用于向HBase批量存储数据
    private final List<PutRequest> puts = new ArrayList<PutRequest>();
    private final List<AtomicIncrementRequest> incs = new ArrayList<AtomicIncrementRequest>();
    //当前行键
    private byte[] currentRowKey;
    private final byte[] eventCountCol = "eventCount".getBytes();
    
    @Override
    public void configure(Context context) {
        //从配置文件中获取列名
        String cols = new String(context.getString("columns"));
        String[] names = cols.split(",");
        columnNames = new byte[names.length][];
        int i = 0;
        for(String name:names){
            columnNames[i++] = name.getBytes();
        }
        
    }

    @Override
    public void configure(ComponentConfiguration conf) {
        // TODO Auto-generated method stub
        
    }

    @Override
    public void cleanUp() {
        // TODO Auto-generated method stub
        table = null;
        colFam = null;
        currentEvent = null;
        columnNames = null;
        currentRowKey = null;
        
    }

    @Override
    public List<PutRequest> getActions() {
        // 分割事件体获取各列的值
        String eventStr = new String(currentEvent.getBody());
        String[] cols = logTokenize(eventStr);
        puts.clear();
        //数据中的时间
        String time=cols[1];
        int n1 = 13-time.length();
        StringBuilder sb = new StringBuilder(time);
        for(int i=0;i<n1;i++){
            sb.insert(0, '0');
        }
        try {
            //使用自带的行键生成器生成行键
            currentRowKey = SimpleRowKeyGenerator.getUUIDKey(cols[0]+"-"+sb.toString());
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
//        currentRowKey = (cols[0]+"-"+System.currentTimeMillis()).getBytes(); 
        int n = cols.length;
        // 添加每列数据
        for(int i=0;i<n;i++){
            PutRequest putReq = new PutRequest(table, currentRowKey,colFam,columnNames[i],cols[i].getBytes());
            puts.add(putReq);
        }        
        return puts;
    }

    @Override
    public List<AtomicIncrementRequest> getIncrements() {
        // 增加接收到的事件数量
        incs.clear();
        incs.add(new AtomicIncrementRequest(table, "totalEvents".getBytes(), colFam, eventCountCol));
        return incs;
    }

    @Override
    //初始化表名和列名
    public void initialize(byte[] table, byte[] cf) {
        
        this.table = table;
        this.colFam = cf;
        
    }

    @Override
    public void setEvent(Event event) {
        // TODO Auto-generated method stub
        this.currentEvent = event;
    }
    
    //从日志中获取列值信息
    public String[] logTokenize(String eventStr) {

//      String logEntryPattern = "^([\\d.]+) (\\S+) (\\S+) \\[([\\w:/]+\\s[+\\-]\\d{4})\\] \"(.+?)\" (\\d{3}) (\\d+|-) \"([^\"]+)\" \"([^\"]+)\"";
//        Pattern p = Pattern.compile(logEntryPattern);
//        Matcher matcher = p.matcher(eventStr); 

/*        if (!matcher.matches()){
            System.err.println("Bad log entry (or problem with RE?):");
            System.err.println(eventStr);
            return null;
        }
*/
        
/*        String[] columns = new String[matcher.groupCount()];       
        for (int i = 0; i < matcher.groupCount(); i++){
            columns[i] = matcher.group(i+1);
        }*/
        
        String[] s = eventStr.split("[:,]");
        int n = s.length;
        String[] columns = new String[n/2];
        for(int i=0;2*i+1<n;i++){
            columns[i] = s[2*i+1];
        }
        
        return columns;

    } 

}

 

所需jar包如下:

这些jar包都可以在flume的lib文件夹中找到。

2. 将上面的程序打包,放入flume的lib文件夹中

3. 配置Flume,实现采集和存储

配置文件flume-hbase.properties如下:

 

############################################
#  flume-src-agent config
###########################################

#agent section
agent.sources = s
agent.channels = c
agent.sinks = r

#source section
#agent.sources.s.type = exec
#agent.sources.s.command = tail -f -n+1 /usr/local/test.log

agent.sources.s.type = spooldir
agent.sources.s.spoolDir = /usr/local/flume-hbase
agent.sources.s.fileHeader = true
agent.sources.s.batchSize = 100
agent.sources.s.channels = c


# Each sink's type must be defined
agent.sinks.r.type = asynchbase
agent.sinks.r.table = car_table
agent.sinks.r.columnFamily = lte
agent.sinks.r.batchSize = 100
agent.sinks.r.serializer = com.ncc.dlut.AsyncHbaseLTEEventSerializer
agent.sinks.r.serializer.columns = cid,time,pci,st,ed,ta,lng,lat

#Specify the channel the sink should use
agent.sinks.r.channel = c

# Each channel's type is defined.
agent.channels.c.type = memory
agent.channels.c.capacity = 1000

 

参考链接:

大数据技术应用(一) 应用Flume+HBase采集和存储日志数据

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flume、Kafka和HBase都是大数据领域常用的组件,它们可以很好地协同工作来实现数据的实时采集、传输和存储。下面是它们的集成配置。 1. 安装Flume Flume是Apache基金会下的分布式、可靠、高可用的海量日志采集、聚合和传输系统。它支持多种数据源和数据目的地,可以将多种数据源的数据采集到Hadoop平台中进行处理和分析。 安装Flume的步骤如下: - 下载Flume并解压缩 - 配置Flume环境变量 - 配置Flume代理 2. 安装Kafka Kafka是由Apache软件基金会开发的一个开源流处理平台,它是一种高吞吐量的分布式发布-订阅消息系统,适用于大规模的数据流处理。 安装Kafka的步骤如下: - 下载Kafka并解压缩 - 配置Kafka环境变量 - 配置Kafka服务端 3. 安装HBase HBase是一个分布式、可扩展、高可用的NoSQL数据库,它是Hadoop生态圈中的一员,可以处理大规模的结构化和半结构化数据。 安装HBase的步骤如下: - 下载HBase并解压缩 - 配置HBase环境变量 - 配置HBase服务端 4. 配置Flume采集数据 Flume支持多种数据源和数据目的地,可以根据不同的需求进行配置。在此我们以采集日志为例,配置Flume采集到的日志数据发送到Kafka。 Flume的配置文件如下: ```properties # Name the components on this agent agent.sources = r1 agent.sinks = k1 agent.channels = c1 # Describe/configure the source agent.sources.r1.type = exec agent.sources.r1.command = tail -F /data/logs/access.log agent.sources.r1.batchSize = 1000 agent.sources.r1.batchDurationMillis = 2000 # Describe the sink agent.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink agent.sinks.k1.brokerList = localhost:9092 agent.sinks.k1.topic = access_log # Use a channel which buffers events in memory agent.channels.c1.type = memory agent.channels.c1.capacity = 10000 agent.channels.c1.transactionCapacity = 1000 # Bind the source and sink to the channel agent.sources.r1.channels = c1 agent.sinks.k1.channel = c1 ``` 5. 配置Kafka接收数据 Kafka支持多个topic,多个partition,可以根据需求进行配置。在此我们以接收Flume发送的数据为例,创建一个名为access_log的topic,并将接收到的数据存储HBase中。 Kafka的配置文件如下: ```properties # Broker configuration broker.id=0 listeners=PLAINTEXT://localhost:9092 num.network.threads=3 num.io.threads=8 socket.send.buffer.bytes=102400 socket.receive.buffer.bytes=102400 socket.request.max.bytes=104857600 # Topic configuration num.partitions=1 offsets.topic.replication.factor=1 transaction.state.log.replication.factor=1 transaction.state.log.min.isr=1 # Zookeeper configuration zookeeper.connect=localhost:2181 zookeeper.connection.timeout.ms=6000 # HBase configuration hbase.zookeeper.quorum=localhost hbase.zookeeper.property.clientPort=2181 hbase.cluster.distributed=true hbase.rootdir=hdfs://localhost:9000/hbase ``` 6. 配置HBase存储数据 HBase支持多个表,多个列族,可以根据需求进行配置。在此我们以存储access_log为例,创建一个名为access_log的表,并在其中创建一个名为cf的列族。 HBase的配置文件如下: ```xml <configuration> <property> <name>hbase.rootdir</name> <value>hdfs://localhost:9000/hbase</value> </property> <property> <name>hbase.zookeeper.quorum</name> <value>localhost</value> </property> <property> <name>hbase.zookeeper.property.clientPort</name> <value>2181</value> </property> </configuration> ``` 7. 启动服务 按照以下顺序启动服务: - 启动Zookeeper服务 - 启动Kafka服务 - 启动HBase服务 - 启动Flume服务 启动命令如下: ```bash # 启动Zookeeper服务 bin/zookeeper-server-start.sh config/zookeeper.properties # 启动Kafka服务 bin/kafka-server-start.sh config/server.properties # 启动HBase服务 bin/start-hbase.sh # 启动Flume服务 bin/flume-ng agent -n agent -c conf -f conf/flume.conf -Dflume.root.logger=INFO,console ``` 8. 验证数据 启动服务后,Flume将会采集到access.log的数据并发送到Kafka中,Kafka将会接收到数据并将其存储HBase中。可以通过HBase命令行或Web界面来查看数据是否已经存储HBase命令行: ```bash # 进入HBase shell bin/hbase shell # 创建表 create 'access_log', 'cf' # 查看表 list # 插入数据 put 'access_log', 'row1', 'cf:col1', 'value1' # 查看数据 scan 'access_log' ``` HBase Web界面: 在浏览器中输入http://localhost:16010,可以进入HBase Web界面,可以通过该界面来查看表、列族、数据等信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值