SpringBoot连接Hive实现自助取数的示例

公司运营免不了让我们数据做一些临时取数,这些取数有时候是重复的,或者可以做成可配置的。需要开发成界面,供他们选择,自然想到SpringBoot连接Hive,可以把取数做成一键生成,或者让他们自己写sql,通常大多人是不会sql的。

1. 需要的依赖配置

为了节省篇幅,这里给出hiveserver2方式连接hive主要的maven依赖,父工程springboot依赖省略。

<!-- 版本信息 -->
<properties>
 <hadoop.version>2.6.5</hadoop.version>
 <mybatis.version>3.2.7</mybatis.version>
 <scopeType>compile</scopeType>
</properties>
<dependency>
 <groupId>org.mybatis</groupId>
 <artifactId>mybatis</artifactId>
 <version>${mybatis.version}</version>
</dependency>

<!-- hadoop依赖 -->
<dependency>
 <groupId>org.apache.hadoop</groupId>
 <artifactId>hadoop-common</artifactId>
 <version>${hadoop.version}</version>
 <scope>${scopeType}</scope>
</dependency>

<!-- hive-jdbc -->
<!-- https://mvnrepository.com/artifact/org.apache.hive/hive-jdbc -->
<dependency>
 <groupId>org.apache.hive</groupId>
 <artifactId>hive-jdbc</artifactId>
 <exclusions>
  <exclusion>
   <groupId>org.slf4j</groupId>
   <artifactId>slf4j-api</artifactId>
  </exclusion>
  <exclusion>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-core</artifactId>
  </exclusion>
  <exclusion>
   <groupId>ch.qos.logback</groupId>
   <artifactId>logback-classic</artifactId>
  </exclusion>
 </exclusions>
 <version>1.2.1</version>
 <scope>${scopeType}</scope>
</dependency>

<!-- 解析html -->
<dependency>
 <groupId>org.jsoup</groupId>
 <artifactId>jsoup</artifactId>
 <version>1.8.3</version>
</dependency>

application-test.yml配置数据库连接,这里用的是druid连接池管理hiveserver2连接,也是没有问题的。

# Spring配置
spring:
 datasource:
 type: com.alibaba.druid.pool.DruidDataSource
 driverClassName: com.mysql.cj.jdbc.Driver
 druid:
  # 多数据源**省略若干***
  # hive数据源
  slave3:
  # 从数据源开关/默认关闭
  enabled: true
  driverClassName: org.apache.hive.jdbc.HiveDriver
  url: jdbc:hive2://cdh:10000/default
  username: bigdata
  password: bigdata

2. 代码实现

代码实现跟其它程序一样,都是mapper、service、controller层,套路一模一样。一共设置了实时和离线两个yarn资源队列,由于其它部门人使用可能存在队列压力过大的情况,需要对数据量按照每次查询的数据范围不超过60天来限制,和此时集群使用资源不能大于55%,这里重点说明一下controller层对数据量的预防。

实体类UserModel:

@NoArgsConstructor
@AllArgsConstructor
@Data
@ToString
public class UserModel extends BaseEntity{

 private String userId;
 private Integer count;
}

2.1 集群资源使用率不大于55%

因为很多业务查询逻辑controller都要用到数据量防御过大的问题,这里使用了被Spring切面关联的注解来标识controller。

定义切面YarnResourceAspect,并且关联注解@YarnResource

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface YarnResource {

}

@Aspect
@Component
public class YarnResourceAspect {

 private static final Logger log = LoggerFactory.getLogger(YarnResourceAspect.class);

 /**
  * 配置切入点
  */
 @Pointcut("@annotation(com.ruoyi.common.annotation.YarnResource)")
 public void yarnResourcdPointCut(){
 }

 /**
  * 检查yarn的资源是否可用
  */
 @Before("yarnResourcdPointCut()")
 public void before(){
  log.info("************************************检查yarn的资源是否可用*******************************");
  // yarn资源紧张
  if(!YarnClient.yarnResourceOk()){
   throw new InvalidStatusException();
  }
 }

}

获取yarn的资源使用数据:

@Slf4j
public class YarnClient {

 /**
  * yarn资源不能超过多少
  */
 private static final int YARN_RESOURCE = 55;

 /**
  *
  * @return true : 表示资源正常, false: 资源紧张
  */
 public static boolean yarnResourceOk() {
  try {
   URL url = new URL("http://master:8088/cluster/scheduler");
   HttpURLConnection conn = null;
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setUseCaches(false);
   // 请求超时5秒
   conn.setConnectTimeout(5000);
   // 设置HTTP头:
   conn.setRequestProperty("Accept", "*/*");
   conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
   // 连接并发送HTTP请求:
   conn.connect();

   // 判断HTTP响应是否200:
   if (conn.getResponseCode() != 200) {
    throw new RuntimeException("bad response");
   }
   // 获取所有响应Header:
   Map<String, List<String>> map = conn.getHeaderFields();
   for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
   }
   // 获取响应内容:
   InputStream input = conn.getInputStream();
   byte[] datas = null;

   try {
    // 从输入流中读取数据
    datas = readInputStream(input);
   } catch (Exception e) {
    e.printStackTrace();
   }
   String result = new String(datas, "UTF-8");// 将二进制流转为String

   Document document = Jsoup.parse(result);

   Elements elements = document.getElementsByClass("qstats");

   String[] ratios = elements.text().split("used");

   return Double.valueOf(ratios[3].replace("%", "")) < YARN_RESOURCE;
  } catch (IOException e) {
   log.error("yarn资源获取失败");
  }

  return false;

 }

 private static byte[] readInputStream(InputStream inStream) throws Exception {
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while ((len = inStream.read(buffer)) != -1) {
   outStream.write(buffer, 0, len);
  }
  byte[] data = outStream.toByteArray();
  outStream.close();
  inStream.close();
  return data;
 }
}@Slf4j
public class YarnClient {

 /**
  * yarn资源不能超过多少
  */
 private static final int YARN_RESOURCE = 55;

 /**
  *
  * @return true : 表示资源正常, false: 资源紧张
  */
 public static boolean yarnResourceOk() {
  try {
   URL url = new URL("http://master:8088/cluster/scheduler");
   HttpURLConnection conn = null;
   conn = (HttpURLConnection) url.openConnection();
   conn.setRequestMethod("GET");
   conn.setUseCaches(false);
   // 请求超时5秒
   conn.setConnectTimeout(5000);
   // 设置HTTP头:
   conn.setRequestProperty("Accept", "*/*");
   conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
   // 连接并发送HTTP请求:
   conn.connect();

   // 判断HTTP响应是否200:
   if (conn.getResponseCode() != 200) {
    throw new RuntimeException("bad response");
   }
   // 获取所有响应Header:
   Map<String, List<String>> map = conn.getHeaderFields();
   for (String key : map.keySet()) {
    System.out.println(key + ": " + map.get(key));
   }
   // 获取响应内容:
   InputStream input = conn.getInputStream();
   byte[] datas = null;

   try {
    // 从输入流中读取数据
    datas = readInputStream(input);
   } catch (Exception e) {
    e.printStackTrace();
   }
   String result = new String(datas, "UTF-8");// 将二进制流转为String

   Document document = Jsoup.parse(result);

   Elements elements = document.getElementsByClass("qstats");

   String[] ratios = elements.text().split("used");

   return Double.valueOf(ratios[3].replace("%", "")) < YARN_RESOURCE;
  } catch (IOException e) {
   log.error("yarn资源获取失败");
  }

  return false;

 }

 private static byte[] readInputStream(InputStream inStream) throws Exception {
  ByteArrayOutputStream outStream = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024];
  int len = 0;
  while ((len = inStream.read(buffer)) != -1) {
   outStream.write(buffer, 0, len);
  }
  byte[] data = outStream.toByteArray();
  outStream.close();
  inStream.close();
  return data;
 }
}

在controller上通过注解@YarnResource标识:

@Controller
@RequestMapping("/hero/hive")
public class HiveController {

 /**
  * html 文件地址前缀
  */
 private String prefix = "hero";

 @Autowired
 IUserService iUserService;

 @RequestMapping("")
 @RequiresPermissions("hero:hive:view")
 public String heroHive(){
  return prefix + "/hive";
 }

 @YarnResource
 @RequestMapping("/user")
 @RequiresPermissions("hero:hive:user")
 @ResponseBody
 public TableDataInfo user(UserModel userModel){
  DateCheckUtils.checkInputDate(userModel);

  PageInfo pageInfo = iUserService.queryUser(userModel);
  TableDataInfo tableDataInfo = new TableDataInfo();

  tableDataInfo.setTotal(pageInfo.getTotal());
  tableDataInfo.setRows(pageInfo.getList());

  return tableDataInfo;
 }
}

2.2 查询数据跨度不超过60天检查

这样每次请求进入controller的时候就会自动检查查询的日期是否超过60天了,防止载入数据过多,引发其它任务资源不够。

public class DateCheckUtils {

 /**
  * 对前台传入过来的日期进行判断,防止查询大量数据,造成集群负载过大
  * @param o
  */
 public static void checkInputDate(BaseEntity o){
  if("".equals(o.getParams().get("beginTime")) && "".equals(o.getParams().get("endTime"))){
   throw new InvalidTaskException();
  }

  String beginTime = "2019-01-01";
  String endTime = DateUtils.getDate();

  if(!"".equals(o.getParams().get("beginTime"))){
   beginTime = String.valueOf(o.getParams().get("beginTime"));
  }

  if(!"".equals(o.getParams().get("endTime"))){
   endTime = String.valueOf(o.getParams().get("endTime"));
  }

  // 查询数据时间跨度大于两个月
  if(DateUtils.getDayBetween(beginTime, endTime) > 60){
   throw new InvalidTaskException();
  }
 }
}

这里访问hive肯定需要切换数据源的,因为其它页面还有对mysql的数据访问,需要注意一下。

目前功能看起来很简单,没有用到什么高大上的东西,后面慢慢完善。



最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:11604713672

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容