2021-04-09

mysql同步sqoop通用脚本

#!/bin/bash

# 要同步的表名 db.tbl
table_name=$1

# 表所在数据库url host:port
url=$2

#登录mysql的用户密码
username=$3
password=$4

# 同步昨天的数据
p_d=$(date -d "-1 days"  +%Y-%m-%d)

# 日志存放目录
log="/tmp/chVmibiSUcyaqvWY/$p_d"

# 数据同步base目录
base="/batch_data_sync/mysql"

# 执行sqoop任务的目录
sqoop_exec_dir="$base/sqoop_exec"

if [ ! -d $sqoop_exec_dir  ];then
    mkdir -p $sqoop_exec_dir
fi

cd $sqoop_exec_dir

    echo $table_name

    dt=(${table_name//./ })
    db=${dt[0]}
    tbl=${dt[1]}
    ts=$(date +%s%3N)
    task_dir="/tmp/chVmibiSUcyaqvWY/$sqoop_exec_dir/"$db"_"$tbl"_"$p_d"_"$ts

    mkdir -p $task_dir
    cd $task_dir
    echo "start $db $tbl $(pwd)" >> $log.log

    hive_db="ods_"$db
    hive_tbl=$tbl
    
    hive -e "CREATE DATABASE IF NOT EXISTS $hive_db;desc $hive_db.$hive_tbl;" 2>&1 | grep 'Table not found'
    rtstatus=$?
    echo $rtstatus

    if [ $rtstatus -ne 0 ]; then
        echo "$hive_db.$hive_tbl表已存在!"
        hive -e "alter table $hive_db.$hive_tbl drop if exists partition(p_d='$p_d')"
        sqoop import \
            --connect "jdbc:mysql://$url/$db?useSSL=false&tinyInt1isBit=false" \
            --username $username --password $password  \
            --table $tbl \
            --hcatalog-database $hive_db \
            --hcatalog-table $hive_tbl \
            --hcatalog-partition-keys p_d \
            --hcatalog-partition-values $p_d \
            --hcatalog-storage-stanza 'stored as orc tblproperties ("orc.compress"="SNAPPY")' \
            -m 1
    else
        echo "$hive_db.$hive_tbl表不存在!"
        sqoop import \
            --connect "jdbc:mysql://$url/$db?useSSL=false&tinyInt1isBit=false" \
            --username $username --password $password  \
            --table $tbl \
            --create-hcatalog-table \
            --hcatalog-database $hive_db \
            --hcatalog-table $hive_tbl \
            --hcatalog-partition-keys p_d \
            --hcatalog-partition-values $p_d \
            --hcatalog-storage-stanza 'stored as orc tblproperties ("orc.compress"="SNAPPY")' \
            -m 1
    fi

    cd $sqoop_exec_dir

    echo "finish $hive_db $hive_tbl $p_d" >> $log.log

    sleep 5
done
上一篇:sqoop学习


下一篇:大数据运维架构师培训(4):Oozie,Flume,Sqoop,Azkaban,Ranger