用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
    评论
### 回答1: 要使用 Java 编写 Flume 采集数据MySQL,需要按照以下步骤进行: 1. 配置 Flume 的 agent 在 Flume 的 agent 配置文件中,需要指定 source、channel 和 sink,具体如下: ``` #定义 agent 名称和监听端口 agent1.sources = r1 agent1.channels = c1 agent1.sinks = k1 #配置 source agent1.sources.r1.type = netcat agent1.sources.r1.bind = localhost agent1.sources.r1.port = 44444 #配置 channel agent1.channels.c1.type = memory #配置 sink agent1.sinks.k1.type = org.apache.flume.sink.jdbc.JDBCSink agent1.sinks.k1.channel = c1 agent1.sinks.k1.driver = com.mysql.jdbc.Driver agent1.sinks.k1.url = jdbc:mysql://localhost:3306/testdb agent1.sinks.k1.username = root agent1.sinks.k1.password = root agent1.sinks.k1.batchSize = 100 agent1.sinks.k1.sqlDialect = MYSQL agent1.sinks.k1.table = test_table agent1.sinks.k1.channel = c1 ``` 其中,source 部分的配置需要根据具体情况进行修改,channel 部分使用 memory 类型即可,sink 部分的配置需要指定 MySQL 数据库的连接信息和表名。 2. 编写 Java 程序 编写 Java 程序,用于启动 Flume agent,代码如下: ``` import org.apache.flume.node.Application; public class FlumeApp { public static void main(String[] args) { //指定 Flume 配置文件路径 String confPath = "/path/to/flume/conf/flume-conf.properties"; //启动 Flume agent Application.main(new String[]{"agent", "-f", confPath, "-n", "agent1"}); } } ``` 其中,需要将 `confPath` 修改为实际的 Flume 配置文件路径。 3. 运行程序 运行 Java 程序即可启动 Flume agent,开始采集数据并写入 MySQL 数据库。 以上就是使用 Java 编写 Flume 采集数据MySQL 的基本步骤,希望能对你有所帮助。 ### 回答2: 要使用Java编写Flume来采集数据MySQL,你可以按照以下步骤进行操作: 1. 首先,确保你已经在系统中安装了Java和Flume。如果没有安装,你可以在官方网站上下载并按照给定的说明进行安装。 2. 在你的Java代码中,导入Flume的相关包以便使用Flume的功能。这些包可以在Flume的安装目录中找到。 3. 创建Flume的配置文件,例如名为`flume.conf`。在配置文件中,你需要指定Flume的源和目的地。源可以是你要采集数据的来源,比如一个文件或者一个网络源。目的地则是MySQL数据库。你需要提供MySQL的连接信息,包括主机地址、端口号、数据库名、用户名和密码。 4. 在Java代码中,使用Flume的`FlumeConfiguration`类来读取并解析你的配置文件。 5. 创建一个Flume的`Event`对象,它用于包装你要采集的数据。将数据添加到`Event`对象中。 6. 使用`FlumeAgent`对象将`Event`对象发送到Flume代理。Flume会根据你的配置文件将数据传送到MySQL数据库。 7. 在MySQL数据库中验证是否成功采集数据。 以下是一个简单的示例代码,用于将采集的数据发送到MySQL数据库: ```java import org.apache.flume.Event; import org.apache.flume.FlumeAgent; import org.apache.flume.FlumeConfiguration; public class FlumeToMySQL { public static void main(String[] args) { // 读取并解析配置文件 FlumeConfiguration configuration = new FlumeConfiguration("flume.conf"); // 创建Event对象,并添加数据 Event event = new Event(); event.addData("data", "Some data to be collected"); // 创建FlumeAgent对象,并发送Event对象 FlumeAgent agent = new FlumeAgent(configuration); agent.sendEvent(event); // 验证数据是否成功采集到MySQL数据库 // TODO: 添加验证数据库的代码 } } ``` 请注意,以上示例只是一个简单的框架,具体的实现可能需要根据你的需求进行调整。你需要根据实际情况修改配置文件和验证数据库的代码。同时,还需要确保你已经正确配置了Flume的相关参数,以确保Flume能够正确连接到MySQL数据库并将数据插入到正确的表中。 ### 回答3: 要用Java编写Flume来采集数据MySQL,您可以按照以下步骤进行操作: 1. 首先,您需要在Java项目中引入Flume的依赖。您可以在项目的pom.xml文件中添加Flume的依赖项,以使其能够在您的项目中使用Flume的相关功能。 2. 接下来,您需要编写一个自定义的Flume拦截器。拦截器是用于过滤和处理采集到的数据的关键组件。您可以根据自己的需求编写一个扩展自Flume的AbstractInterceptor类的自定义拦截器,以实现数据处理的逻辑。 3. 在您的代码中,创建一个Flume的配置文件。这个配置文件将指定Flume从哪个源获取数据,并将数据发送到MySQL数据库中的哪个表。配置文件将包含必要的信息,如源类型、Flume Agent名称、自定义拦截器等。 4. 创建一个Flume Agent并启动它。在Java代码中,您可以通过Flume的Agent对象来实现这一步骤。通过Agent对象,您可以读取Flume配置文件并启动Flume Agent来通过拦截器将数据从源发送到目标。 5. 编写代码来连接到MySQL数据库并将数据插入到数据库表中。您可以使用Java的JDBC API与MySQL数据库建立连接,并使用SQL语句将采集到的数据插入到指定的表中。 6. 最后,您需要编译并执行您的Java代码。当代码执行时,Flume将从源获取数据并通过自定义拦截器将其发送到MySQL数据库中的指定表中。 需要注意的是,以上步骤是一个简单的指导,您可能会根据实际情况进行相应的调整和扩展。此外,Java编写Flume采集数据MySQL还涉及到Flume的其他概念和组件,您可以通过官方文档或其他相关资源深入了解并应用。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值