用flume 导入数据到mysql

转:http://blog.csdn.net/poisions/article/details/51695372

  1. 代码如下:  
  1. /** 
  2.  * Licensed to the Apache Software Foundation (ASF) under one 
  3.  * or more contributor license agreements.  See the NOTICE file 
  4.  * distributed with this work for additional information 
  5.  * regarding copyright ownership.  The ASF licenses this file 
  6.  * to you under the Apache License, Version 2.0 (the 
  7.  * "License"); you may not use this file except in compliance 
  8.  * with the License.  You may obtain a copy of the License at 
  9.  * 
  10.  *     http://www.apache.org/licenses/LICENSE-2.0 
  11.  * 
  12.  * Unless required by applicable law or agreed to in writing, software 
  13.  * distributed under the License is distributed on an "AS IS" BASIS, 
  14.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  15.  * See the License for the specific language governing permissions and 
  16.  * limitations under the License. 
  17.  */  
  18. package org.flume.mysql.sink;  
  19. /** 
  20.  * create by yong 2016-6-16 
  21.  */  
  22. import com.google.common.base.Preconditions;  
  23. import com.google.common.base.Throwables;  
  24. import com.google.common.collect.Lists;  
  25. import org.apache.flume.*;  
  26. import org.apache.flume.conf.Configurable;  
  27. import org.apache.flume.sink.AbstractSink;  
  28. import org.slf4j.Logger;  
  29. import org.slf4j.LoggerFactory;  
  30.    
  31. import java.sql.Connection;  
  32. import java.sql.DriverManager;  
  33. import java.sql.PreparedStatement;  
  34. import java.sql.SQLException;  
  35. import java.util.List;  
  36.    
  37. public class MysqlSink extends AbstractSink implements Configurable {  
  38.    
  39.     private Logger LOG = LoggerFactory.getLogger(MysqlSink.class);  
  40.     private String hostname;  
  41.     private String port;  
  42.     private String databaseName;  
  43.     private String tableName;  
  44.     private String user;  
  45.     private String password;  
  46.     private PreparedStatement preparedStatement;  
  47.     private Connection conn;  
  48.     private int batchSize;  
  49.    
  50.     public MysqlSink() {  
  51.         LOG.info("MysqlSink start...");  
  52.     }  
  53.    
  54.     public void configure(Context context) {  
  55.         hostname = context.getString("hostname");  
  56.         Preconditions.checkNotNull(hostname, "hostname must be set!!");  
  57.         port = context.getString("port");  
  58.         Preconditions.checkNotNull(port, "port must be set!!");  
  59.         databaseName = context.getString("databaseName");  
  60.         Preconditions.checkNotNull(databaseName, "databaseName must be set!!");  
  61.         tableName = context.getString("tableName");  
  62.         Preconditions.checkNotNull(tableName, "tableName must be set!!");  
  63.         user = context.getString("user");  
  64.         Preconditions.checkNotNull(user, "user must be set!!");  
  65.         password = context.getString("password");  
  66.         Preconditions.checkNotNull(password, "password must be set!!");  
  67.         batchSize = context.getInteger("batchSize"100);  
  68.         Preconditions.checkNotNull(batchSize > 0"batchSize must be a positive number!!");  
  69.     }  
  70.    
  71.     @Override  
  72.     public void start() {  
  73.         super.start();  
  74.         try {  
  75.             //调用Class.forName()方法加载驱动程序  
  76.             Class.forName("com.mysql.jdbc.Driver");  
  77.         } catch (ClassNotFoundException e) {  
  78.             e.printStackTrace();  
  79.         }  
  80.    
  81.         String url = "jdbc:mysql://" + hostname + ":" + port + "/" + databaseName;   
  82.         //调用DriverManager对象的getConnection()方法,获得一个Connection对象  
  83.    
  84.         try {  
  85.             conn = DriverManager.getConnection(url, user, password);  
  86.             conn.setAutoCommit(false);  
  87.             //创建一个Statement对象  
  88.             preparedStatement = conn.prepareStatement("insert into " + tableName +   
  89.                                                " (content) values (?)");  
  90.    
  91.         } catch (SQLException e) {  
  92.             e.printStackTrace();  
  93.             System.exit(1);  
  94.         }  
  95.    
  96.     }  
  97.    
  98.     @Override  
  99.     public void stop() {  
  100.         super.stop();  
  101.         if (preparedStatement != null) {  
  102.             try {  
  103.                 preparedStatement.close();  
  104.             } catch (SQLException e) {  
  105.                 e.printStackTrace();  
  106.             }  
  107.         }  
  108.    
  109.         if (conn != null) {  
  110.             try {  
  111.                 conn.close();  
  112.             } catch (SQLException e) {  
  113.                 e.printStackTrace();  
  114.             }  
  115.         }  
  116.     }  
  117.    
  118.     public Status process() throws EventDeliveryException {  
  119.         Status result = Status.READY;  
  120.         Channel channel = getChannel();  
  121.         Transaction transaction = channel.getTransaction();  
  122.         Event event;  
  123.         String content;  
  124.    
  125.         List<String> actions = Lists.newArrayList();  
  126.         transaction.begin();  
  127.         try {  
  128.             for (int i = 0; i < batchSize; i++) {  
  129.                 event = channel.take();  
  130.                 if (event != null) {  
  131.                     content = new String(event.getBody());  
  132.                     actions.add(content);  
  133.                 } else {  
  134.                     result = Status.BACKOFF;  
  135.                     break;  
  136.                 }  
  137.             }  
  138.    
  139.             if (actions.size() > 0) {  
  140.                 preparedStatement.clearBatch();  
  141.                 for (String temp : actions) {  
  142.                     preparedStatement.setString(1, temp);  
  143.                     preparedStatement.addBatch();  
  144.                 }  
  145.                 preparedStatement.executeBatch();  
  146.    
  147.                 conn.commit();  
  148.             }  
  149.             transaction.commit();  
  150.         } catch (Throwable e) {  
  151.             try {  
  152.                 transaction.rollback();  
  153.             } catch (Exception e2) {  
  154.                 LOG.error("Exception in rollback. Rollback might not have been" +  
  155.                         "successful.", e2);  
  156.             }  
  157.             LOG.error("Failed to commit transaction." +  
  158.                     "Transaction rolled back.", e);  
  159.             Throwables.propagate(e);  
  160.         } finally {  
  161.             transaction.close();  
  162.         }  
  163.    
  164.         return result;  
  165.     }  
  166. }  


pom依赖如下:

  1. <?xml version="1.0"?>  
  2. <!--  
  3. Licensed to the Apache Software Foundation (ASF) under one or more  
  4. contributor license agreements.  See the NOTICE file distributed with  
  5. this work for additional information regarding copyright ownership.  
  6. The ASF licenses this file to You under the Apache License, Version 2.0  
  7. (the "License"); you may not use this file except in compliance with  
  8. the License.  You may obtain a copy of the License at  
  9.    
  10.      http://www.apache.org/licenses/LICENSE-2.0  
  11.    
  12. Unless required by applicable law or agreed to in writing, software  
  13. distributed under the License is distributed on an "AS IS" BASIS,  
  14. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  15. See the License for the specific language governing permissions and  
  16. limitations under the License.  
  17. -->  
  18. <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"  
  19.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">  
  20.   <modelVersion>4.0.0</modelVersion>  
  21.   <parent>  
  22.     <groupId>org.apache.flume</groupId>  
  23.     <artifactId>flume-parent</artifactId>  
  24.     <version>1.4.0</version>  
  25.   </parent>  
  26.   <groupId>org.apache.flume</groupId>  
  27.   <artifactId>flume-mysql-sink</artifactId>  
  28.   <version>1.4.0</version>  
  29.   <name>flume-mysql-sink</name>  
  30.   <url>http://maven.apache.org</url>  
  31.   <properties>  
  32.     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
  33.   </properties>  
  34. <dependencies>  
  35.         <dependency>  
  36.             <groupId>org.apache.flume</groupId>  
  37.             <artifactId>flume-ng-core</artifactId>  
  38.         </dependency>  
  39.    
  40.         <dependency>  
  41.             <groupId>org.apache.flume</groupId>  
  42.             <artifactId>flume-ng-configuration</artifactId>  
  43.         </dependency>  
  44.    
  45.         <dependency>  
  46.             <groupId>mysql</groupId>  
  47.             <artifactId>mysql-connector-java</artifactId>  
  48.             <version>5.1.25</version>  
  49.         </dependency>  
  50.    
  51.         <dependency>  
  52.             <groupId>org.slf4j</groupId>  
  53.             <artifactId>slf4j-api</artifactId>  
  54.         </dependency>  
  55.    
  56.         <dependency>  
  57.             <groupId>org.slf4j</groupId>  
  58.             <artifactId>slf4j-log4j12</artifactId>  
  59.             <scope>test</scope>  
  60.         </dependency>  
  61. </dependencies>  
  62. </project>  

讲代码打成jar包后,上传到flume安装目录下的lib文件夹中,同时需要上传MySQL的驱动jar包


=====================================================================================================================

给flume添加mysqlSink.conf文件:

agent1.sources = source1
agent1.sinks = mysqlSink
agent1.channels = channel1
 
 
 
# Describe/configure source1
agent1.sources.source1. type  exec
agent1.sources.source1. command  = tail -F /home/yong/Work/flum-1.6/tail_log_exec
agent1.sources.source1.channels = channel1
 
 
# Describe mysqlSink
agent1.sinks.mysqlSink. type  = org.flume.mysql.sink.MysqlSink
agent1.sinks.mysqlSink. hostname =localhost
agent1.sinks.mysqlSink.port=3306
agent1.sinks.mysqlSink.databaseName=sinktest
agent1.sinks.mysqlSink.tableName=mysqltest
agent1.sinks.mysqlSink.user=root
agent1.sinks.mysqlSink.password=root
agent1.sinks.mysqlSink.channel = channel1
  
# Use a channel which buffers events in memory
agent1.channels.channel1. type  memory
agent1.channels.channel1.capacity = 1000
agent1.channels.channel1.transactionCapactiy = 100
 
===============================================================================================================================
启动flume命令:

/home/yong/Work/flume-1.6/bin/flume-ng agent -c/home/yong/Work/flume-1.6/conf/ -f /home/yong/Work/flume-1.6/conf/mysqlSink.conf -n agent1 -Dflume.root.logger=INFO,console

============================================================================

运行程序时,先在Mysql中创建一个表:

mysql> create table mysqltest(
-> id int(11) NOT NULL AUTO_INCREMENT,
-> content varchar(50000) NOT NULL,
-> PRIMARY KEY (`id`)

-> ) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; 

========================================================================================================================

生成数据到目标日志文件中:

for i in {1..1000};do echo "exec tail$i" >> /home/yong/Work/flume-1.6/tail_log_exec;done;


完成后,数据和预想中的一样,写入了数据库中。



  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值