Java抽取Hive、HDFS元数据信息

文章目录

  • 一、技术
  • 二、构建SpringBoot工程
    • 2.1 创建maven工程并配置 pom.xml文件
    • 2.2 编写配置文件 application.yml
    • 2.3 编写配置文件 application.propertites
    • 2.4 开发主启动类
    • 2.5 开发配置类
  • 三、测试抽取Hive、HDFS元数据
  • 四、将抽取的元数据存储到MySQL
    • 4.1 引入依赖
    • 4.2 配置application.yml
    • 4.3 创建元数据信息Bean
    • 4.4 定义Service
    • 4.5 创建Mapper
    • 4.6 测试

一、技术

SpringBoot + Mybatis Plus

二、构建SpringBoot工程

2.1 创建maven工程并配置 pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.7.17</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.songshuang</groupId><artifactId>dwmeta</artifactId><version>1.0-SNAPSHOT</version><properties><maven.compiler.source>8</maven.compiler.source><maven.compiler.target>8</maven.compiler.target><project.build.sourceEncoding>UTF-8</project.build.sourceEncoding></properties><dependencies><!-- 必须 ,用于开发一个web项目--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><!-- 测试必须加 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- 连接hive的元数据服务 --><dependency><groupId>org.apache.hive</groupId><artifactId>hive-metastore</artifactId><version>3.1.2</version></dependency><!-- json处理 --><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.72</version></dependency></dependencies></project>

2.2 编写配置文件 application.yml

null

2.3 编写配置文件 application.propertites

hive.client.uri:hive元数据服务metastore地址
hdfs.admin.user:hdfs用户
hdfs.uri:hdfs NameNode RPC端口

hive.client.uri=thrift://hadoop102:9083
hdfs.admin.user=hadoop
hdfs.uri=hdfs://hadoop102:9820

2.4 开发主启动类

package com.songshuang.dga;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;//当前这个类是App的主启动类
@SpringBootApplication
public class MainApp {public static void main(String[] args) {//启动appSpringApplication.run(MainApp.class, args);}
}

2.5 开发配置类

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;import java.net.URI;/*所有的客户端,都应该随用随建,用完就关。*/
@Configuration
public class DgaConfig {@Value("${hive.client.uri}")private String hiveUri;@Bean@Scope("prototype")public HiveMetaStoreClient createHiveMetastoreClient(){org.apache.hadoop.conf.Configuration conf = new org.apache.hadoop.conf.Configuration();//客户端连接服务端,配置地址和端口conf.set("hive.metastore.uris",hiveUri);try {HiveMetaStoreClient client = new HiveMetaStoreClient(conf);return client;} catch (MetaException e) {throw new RuntimeException(e);}}@Value("${hdfs.admin.user}")private String hdfsAdmin;@Value("${hdfs.uri}")private String hdfsUri;@Bean@Scope("prototype")public FileSystem createHDFSClient(){try {FileSystem hdfsClient = FileSystem.get(new URI(hdfsUri), new org.apache.hadoop.conf.Configuration(), hdfsAdmin);return hdfsClient;} catch (Exception e) {throw new RuntimeException(e);}}
}

三、测试抽取Hive、HDFS元数据

连接Metastore服务抽取Hive元数据;连接NameNode抽取HDFS元数据;

import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsStatus;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.thrift.TException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ApplicationContext;import java.io.IOException;/*** @date 2024/1/29 16:27*/@SpringBootTest
public class MetaTest {@Autowiredprivate ApplicationContext context;@Testpublic void testHiveClient() throws TException {HiveMetaStoreClient client = context.getBean(HiveMetaStoreClient.class);//获取库下所有的表System.out.println(client.getAllTables("dw_ods"));//获取某张表的元数据信息System.out.println(client.getTable("dw_ods", "ods_activity_info_full"));client.close();}@Testpublic void testHDFSClient() throws IOException {//1.获取hdfs客户端FileSystem hdfsClient = context.getBean(FileSystem.class);//2.遍历tableMetaInfos,为每一个TableMetaInfo补充hdfs的元数据信息FsStatus status = hdfsClient.getStatus();long capacity = status.getCapacity();long remaining = status.getRemaining();long used = status.getUsed();System.out.println("capacity:" + capacity + "remaining:" + remaining + "used:" + used );}
}

四、将抽取的元数据存储到MySQL

4.1 引入依赖

        <!-- 使用springboot插件,不会和springboot的其他插件冲突了 --><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring-boot-starter</artifactId><version>1.2.15</version></dependency><!-- 驱动 --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency><!-- 动态数据源切换,允许使用一个注解,可以切换Dao查询的数据源内置了数据库连接池,会和之前配置的Druid冲突--><dependency><groupId>com.baomidou</groupId><artifactId>dynamic-datasource-spring-boot-starter</artifactId><version>2.5.8</version></dependency><!-- 注释掉mybatis,否则会冲突 --><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-boot-starter</artifactId><version>3.4.1</version></dependency><dependency><groupId>com.baomidou</groupId><artifactId>mybatis-plus-generator</artifactId><version>3.5.3.1</version></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-engine-core</artifactId><version>2.3</version></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-freemarker</artifactId></dependency>

4.2 配置application.yml

spring:datasource:dynamic:primary: dga #设置默认的数据源或者数据源组strict: false #严格匹配数据源,默认false. true未匹配到指定数据源时抛异常,false使用默认数据源datasource:dga:url: jdbc:mysql://mall:3306/dga?useSSL=false&useUnicode=true&characterEncoding=UTF-8username: rootpassword: "123456"driver-class-name: com.mysql.cj.jdbc.Driverdruid:initial-size: 5max-active: 20max-wait: 60000min-idle: 5test-on-borrow: truetest-on-return: falsetest-while-idle: trueautoconfigure:exclude: com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceAutoConfiguremybatis-plus:mapper-locations: classpath*:/sqls/*Mapper.xmlconfiguration:mapUnderscoreToCamelCase: truelogging:level:com:songshuang:dga:meta:mapper: debugserver:port: 80

4.3 创建元数据信息Bean

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.io.Serializable;
import java.sql.Timestamp;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;/*** <p>* 元数据表附加信息* </p>** @since 2024-01-29*/
@Data
@NoArgsConstructor
@AllArgsConstructor
@TableName("table_meta_info_extra")
public class TableMetaInfoExtra implements Serializable {private static final long serialVersionUID = 1L;/*** id*/@TableId(value = "id", type = IdType.AUTO)private Long id;/*** 表名*/private String tableName;/*** 库名*/private String schemaName;/*** 技术负责人*/private String tecOwnerUserName;/*** 业务负责人*/private String busiOwnerUserName;/*** 存储周期类型*/private String lifecycleType;/*** 生命周期(天)*/private Long lifecycleDays;/*** 安全级别*/private String securityLevel;/*** 数仓所在层级*/private String dwLevel;/*** 创建时间 (自动生成)*/private Timestamp createTime;/*** 更新时间  (自动生成)*/private Timestamp updateTime;
}

4.4 定义Service

import com.baomidou.mybatisplus.extension.service.IService;
import com.songshuang.dga.meta.bean.TableMetaInfoExtra;
import org.apache.hadoop.hive.metastore.api.MetaException;public interface TableMetaInfoExtraService extends IService<TableMetaInfoExtra> {//生成所有表的辅助信息。void initMetaInfoExtra(String db) throws MetaException;}
import com.songshuang.dga.config.MetaConstant;
import com.songshuang.dga.meta.bean.TableMetaInfoExtra;
import com.songshuang.dga.meta.mapper.TableMetaInfoExtraMapper;
import com.songshuang.dga.meta.service.TableMetaInfoExtraService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.RandomUtils;
import org.apache.hadoop.hive.metastore.HiveMetaStoreClient;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;import java.sql.Timestamp;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;/*** <p>* 元数据表附加信息 服务实现类* </p>** @since 2024-01-29*/
@Service
public class TableMetaInfoExtraServiceImpl extends ServiceImpl<TableMetaInfoExtraMapper, TableMetaInfoExtra> implements TableMetaInfoExtraService {@Autowiredprivate ApplicationContext context;/*辅助信息不经常变动。只有当你去创建新表的时候,才需要想数据库中写入新表的辅助信息。如果一张表已经有了辅助信息,无需写入调用initMetaInfoExtra(),只需要写入新表(今天刚创建表的元数据信息)*/@Overridepublic void initMetaInfoExtra(String db) throws MetaException {//查询当前db中的新表//第一步: 先查询table_meta_info_extra中当前db已经有信息的表。 老表Set<String> existsTableNames = list(new QueryWrapper<TableMetaInfoExtra>().eq("schema_name", db)).stream().map(info -> info.getTableName()).collect(Collectors.toSet());//第二步: 查询db下所有的表,根据老表,过滤得到新表HiveMetaStoreClient client = context.getBean(HiveMetaStoreClient.class);List<String> allTables = client.getAllTables(db);List<String> newTables = allTables.stream().filter(name -> !existsTableNames.contains(name)).collect(Collectors.toList());//为新表生成辅助信息,存入到数据库中List<TableMetaInfoExtra> infos = newTables.stream().map(name -> {TableMetaInfoExtra extra = new TableMetaInfoExtra();extra.setSchemaName(db);extra.setTableName(name);//其他的信息应该由员工手动录入,这里为了后续方便,初始化一些默认值,假设员工已经录入了initExtraInfo(extra);extra.setCreateTime(new Timestamp(System.currentTimeMillis()));return extra;}).collect(Collectors.toList());saveBatch(infos);}private void initExtraInfo(TableMetaInfoExtra extra) {String [] bon = {"张三","李四","王五","赵六"};String [] ton = {"张小三","李中四","王大五","赵老六"};extra.setBusiOwnerUserName(bon[RandomUtils.nextInt(0,bon.length)]);extra.setTecOwnerUserName(ton[RandomUtils.nextInt(0,ton.length)]);extra.setLifecycleType(MetaConstant.LIFECYCLE_TYPE_UNSET);extra.setLifecycleDays(-1l);extra.setSecurityLevel(MetaConstant.SECURITY_LEVEL_UNSET);extra.setDwLevel(extra.getTableName().substring(0,3).toUpperCase());}
}

4.5 创建Mapper

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.songshuang.dga.meta.bean.TableMetaInfoExtra;
import org.apache.ibatis.annotations.Mapper;/*** @date 2024/1/29 19:44*/
@Mapper
public interface TableMetaInfoExtraMapper extends BaseMapper<TableMetaInfoExtra> {
}

4.6 测试

    @Autowiredprivate TableMetaInfoExtraService extraService;@Testpublic void testExtraInfo() throws Exception {extraService.initMetaInfoExtra("dw_ods");}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/657376.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

防火墙综合拓扑(NAT、双机热备)

实验需求 拓扑 实验注意点&#xff1a; 先配置双机热备&#xff0c;再来配置安全策略和NAT两台双机热备的防火墙的接口号必须一致如果其中一台防火墙有过配置&#xff0c;最好清空或重启&#xff0c;不然配置会同步失败两台防火墙同步完成后&#xff0c;可以直接在主状态防火墙…

浅谈WPF之UniformGrid和ItemsControl

在日常开发中&#xff0c;有些布局非常具有规律性&#xff0c;比如相同的列宽&#xff0c;行高&#xff0c;均匀的排列等&#xff0c;为了简化开发&#xff0c;WPF提供了UniformGrid布局和ItemsControl容器&#xff0c;本文以一个简单的小例子&#xff0c;简述&#xff0c;如何…

TSINGSEE青犀智能分析网关V4—让加油站迈入AI智能检测时代

一、背景与需求 中国目前建设加油站超过10万个&#xff0c;作为高危场所对于烟火&#xff0c;危险区域管控、消防器材等管理要求严格&#xff0c;稍有不慎即酿成大祸。由于春节临近&#xff0c;加油站各类人员进出频繁&#xff0c;安全意识较低&#xff0c;依靠普通监控人力的…

java常量和kotlin常量

在java中使用final声明常量在kotlin中使用const val声明常量 常量在编译为字节码后会直接把调用常量的地方直接替换为常量值&#xff0c;示例如下&#xff1a; public class ConstDemo {public static final String NAME "Even";private static final int ID 100…

海外云手机开辟企业跨境电商新道路

近几年&#xff0c;海外云手机为跨境电商、海外媒体引流、游戏行业等互联网领域注入了蓬勃活力。对于国内跨境电商而言&#xff0c;在亚马逊及其他平台上&#xff0c;短视频引流和社交电商营销成为最为有效的流量来源。如何通过海外云手机的助力&#xff0c;在新兴社交平台为企…

python二维高斯热力图绘制简单的思路代码

import numpy as np import matplotlib.pyplot as plt from scipy.ndimage import gaussian_filter import cv2# 生成一个示例图像 image_size 100 image np.zeros((image_size, image_size))# 在图像中心创建一个高亮区域 center_x, center_y image_size // 2, image_size …

【遥感专题系列】遥感影像信息提取之——人工目视解译

​遥感影像通过亮度值或像元值的高低差异&#xff08;反映地物的光谱信息&#xff09;及空间变化&#xff08;反映地物的空间信息&#xff09;来表示不同地物的差异&#xff0c;这是区分不同影像地物的物理基础。 ​人工解译是目前国内使用最多的一种影像提取方法&#xff0c;如…

力扣hot100 单词搜索 深度优先搜索 特殊字符判重

Problem: 79. 单词搜索 Code class Solution{int n, m;char[][] b;String word;int[] dx { 1, 0, -1, 0 };int[] dy { 0, 1, 0, -1 };public boolean exist(char[][] board, String word){b board;this.word word;n b.length;m b[0].length; // 以所有点作为起点来进行…

oracle rman duplicate创建测试库

1.在目标端建立参数文件&#xff0c;并启动到nomount&#xff0c;如果测试库的文件存放路径和生产不一致&#xff0c;配置db_file_name_convert和log_file_name_convert 2.拷贝生产的密码文件到目标端&#xff0c;配置生产到目标端的tnsnames 3.配置目标端的监听为静态监听&a…

生词本----Python实例练习

题目描述 背单词是英语学习中最基础的一环&#xff0c;不少学生在背诵单词的过程中会整理自己的生词本&#xff0c;以不断拓展自己的词汇量。本实例要求编写生词本程序&#xff0c;该程序需具备以下功能。 &#xff08;1&#xff09;查看生词列表功能&#xff1a;输出生词本中…

系统分析师-22年-下午题目

系统分析师-22年-下午题目 更多软考知识请访问 https://ruankao.blog.csdn.net/ 试题一必答&#xff0c;二、三、四、五题中任选其中两题作答 试题一 (25分) 说明 某软件公司拟开发一套博客系统&#xff0c;要求能够向用户提供一个便捷发布自已心得&#xff0c;及时有效的…

腾讯云SDK并发调用优化方案

目录 一、概述 二、 网关的使用 2.1 核心代码 三、腾讯云SDK依赖包的改造 一、概述 此网关主要用于协调腾讯云SDK调用的QPS消耗&#xff0c;使得多个腾讯云用户资源能得到最大限度的利用。避免直接使用腾讯云SDK 时&#xff0c;在较大并发情况下导致接口调用异常。网关的工…

Python与CAD系列高级篇(二十五)分类提取坐标到excel(补充圆半径、线长度、圆弧)

目录 0 简述1 分类提取坐标到excel2 结果展示0 简述 上一篇中介绍了:对点、直线、多段线、圆、样条曲线分类读取坐标并提取到excel。考虑到进一步提取图形信息,此篇补充对圆半径、线长度以及圆弧几何信息的提取。 1 分类提取坐标到excel 代码实现: import math import nump…

linux -- per-CPU变量

per-CPU变量 per-CPU变量是一种存在与每个CPU本地的变量&#xff0c;对于每一种per-CPU变量&#xff0c;每个CPU在本地都有一份它的副本。 per-CPU变量的优点 多处理器系统(smp)中无需考虑与其他处理器的竞争问题(并非绝对的)可以利用处理器本地的cache硬件&#xff0c;提高…

ClickHouse(24)ClickHouse集成mongodb表引擎详细解析

文章目录 MongoDB创建一张表用法示例 资料分享系列文章clickhouse系列文章 MongoDB MongoDB 引擎是只读表引擎&#xff0c;允许从远程 MongoDB 集合中读取数据(SELECT查询)。引擎只支持非嵌套的数据类型。不支持 INSERT 查询。 创建一张表 CREATE TABLE [IF NOT EXISTS] [db…

知识点积累系列(三)golang框架篇【持续更新】

云原生学习路线导航页&#xff08;持续更新中&#xff09; 本文是 知识点积累 系列文章的第三篇&#xff0c;记录日常学习中遇到的golang框架相关的知识点 1、gin框架相关 1.1.在gin中间件中直接return&#xff0c;相当于什么 在 Gin 中间件中直接使用 return 语句&#xff0…

Yolo v8 入门学习之采用 coco128 数据集进行图片检测测试

示例入门代码 from ultralytics import YOLO import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimgdef test():# Create a new YOLO model from scratchmodel YOLO(yolov8n.yaml)# Load a pretrained YOLO model (recommended for training)model …

Redis -- 开篇热身,常用的全局命令

目录 Redis重要文件 启动停止脚本 配置文件 持久化文件存储目录 核心命令 set get 全局命令 keys exists del expire ttl 过期策略是如何实现的 定时器 type 小结 Redis重要文件 启动停止脚本 /usr/bin/redis-benchmark &#xff1a; 用于对Redis做性能基准…

Python 因果推断(下)

六、2007-2009 年大衰退期间加拿大就业市场上白人女性名字的溢价 原文&#xff1a;causal-methods.github.io/Book/6%29_The_Premium_of_Having_a_White_Female_Name_in_the_Canadian_Job_Market_During_the_Great_Recession_2007_2009.html 译者&#xff1a;飞龙 协议&#xf…

AppSrv-DHCP(23国赛真题)

2023全国职业院校技能大赛网络系统管理赛项–模块B:服务部署(WindowServer2022) 文章目录 题目配置步骤安装和配置dhcp服务,为办公区域网络提供地址上网。创建地址池名为inside_pool,地址池范围:192.168.0.1-192.168.0.100。根据题目要求正确配置网关和dns信息。启动作用…