SpringBoot連線Hive實現自助取數的示例
原文連結: http://www.ikeguang.com/?p=815
公司運營免不了讓我們資料做一些臨時取數,這些取數有時候是重複的,或者可以做成可配置的。需要開發成介面,供他們選擇,自然想到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,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的資料訪問,需要注意一下。
目前功能看起來很簡單,沒有用到什麼高大上的東西,後面慢慢完善。
以上就是SpringBoot連線Hive實現自助取數的示例的詳細內容,更多關於SpringBoot連線Hive的資料請關注我們其它相關文章!