MapReduce保存計算結果到數據庫

------------- 創建數據庫和表 ---------------

  1. mysql -u root -p 登錄數據庫
  2. create database if not existsii; 創建數據庫
  3. useii; 使用數據庫
create table if not exists `ii` (
	`id` int primary key auto_increment,
	`word` varchar(100) not null,
	`file_name_count` varchar(1000) not null
	);

-------------- 把 MapReduce 的輸出保存到數據庫 ----------

  1. 上傳 mysql 的驅動到 hdfs

  2. 創建 ii 表的 model 類
    也是一個內部類,
    添加屬性和表字段一一對應,增加 setter 和 getter 方法

  3. 讓 model 類實現 Writable 和 DBWritable 兩個接口
    實現接口中的四個方法

  4. 在 main 中配置數據庫鏈接信息

String driverClass = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://master:3306/book";
String username = "root";
String password = "123456aA_";

DBConfiguration.configureDB(job.getConfiguration(), driverClass, url, username, password);
  1. 加載數據庫驅動
Path dbDriverPath = new Path("hdfs://master:9000/mysql-connector-java-5.1.46.jar");
job.addArchiveToClassPath(dbDriverPath);
  1. 配置輸出結果保存到數據庫
job.setOutputFormatClass(DBOutputFormat.class);
  1. 配置數據庫表相關信息
DBOutputFormat.setOutput(job, "ii", "word", "file_name_count");
  1. 修改 reduce 的輸出類型:
    key = model 類型
    vlaue = nullwritable 類型

    修改邏輯,修改 job 中配置的 reduce 輸出類型

    ------------- 如果不能在 windows 模擬執行,就打包放到 hadoop 執行 --------
    hadoop jar xxxx 命令執行 mapReduce 程序

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章