最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringCloud3.x集成BigQuery的代碼實(shí)現(xiàn)

 更新時(shí)間:2025年01月14日 08:30:50   作者:HBLOG  
Google BigQuery 是一種高性能、可應(yīng)用于大數(shù)據(jù)分析的公主云數(shù)據(jù)庫(kù)服務(wù),Spring Cloud 提供了完善的工具和核心功能,可以進(jìn)行泛動(dòng)分布應(yīng)用構(gòu)建,本文給大家介紹了SpringCloud3.x集成BigQuery的代碼實(shí)現(xiàn),需要的朋友可以參考下

1.原理

Google BigQuery 是一種高性能、可應(yīng)用于大數(shù)據(jù)分析的公主云數(shù)據(jù)庫(kù)服務(wù)。Spring Cloud 提供了完善的工具和核心功能,可以進(jìn)行泛動(dòng)分布應(yīng)用構(gòu)建。通過(guò)集成 Spring Cloud GCP,應(yīng)用可以便捷地使用 Google 云服務(wù),如 BigQuery。 運(yùn)行原理如下:

  • Spring Cloud GCP 提供對(duì) Google Cloud SDK 和 REST API 的封裝,通過(guò)自定義配置簡(jiǎn)化了通信流程。
  • 通過(guò) BigQueryTemplate,應(yīng)用可以實(shí)現(xiàn)數(shù)據(jù)提交、查詢(xún)和分析。
  • 使用 Spring 框架的常規(guī)構(gòu)件,如信息通道和任務(wù)調(diào)度,應(yīng)用可以進(jìn)行規(guī)?;瘮?shù)據(jù)處理。

2.應(yīng)用場(chǎng)景

  • 大數(shù)據(jù)分析: 選擇 BigQuery 進(jìn)行大量數(shù)據(jù)的高性能分析,完善商業(yè)準(zhǔn)備和內(nèi)容提報(bào)。
  • ETL 操作: 連接多種數(shù)據(jù)源,通過(guò)規(guī)則創(chuàng)建云數(shù)據(jù)分析的數(shù)據(jù)統(tǒng)一。
  • BI 圖表: 使用 BigQuery 提供的高速查詢(xún)功能,支持 BI 平臺(tái)實(shí)現(xiàn)動(dòng)態(tài)繪圖和數(shù)據(jù)分析。
  • 可視化報(bào)表: 在進(jìn)行精簡(jiǎn)數(shù)據(jù)計(jì)算后,展示對(duì)外分析結(jié)果。

3.環(huán)境創(chuàng)建

BigQuery 信息中心,為自己創(chuàng)建一個(gè) BigQuery 數(shù)據(jù)集。在資源面板下,點(diǎn)擊您的項(xiàng)目 ID,然后點(diǎn)擊項(xiàng)目下的創(chuàng)建數(shù)據(jù)集。

4.代碼實(shí)現(xiàn)

1. 配置環(huán)境

1.1 創(chuàng)建項(xiàng)目

使用 Spring Initializr 創(chuàng)建 Spring Boot 項(xiàng)目,選擇以下依賴(lài):

  • Spring Web
  • Spring Boot Actuator
  • Spring Cloud GCP

1.2 加入依賴(lài)

pom.xml 中添加以下依賴(lài):

<?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">
    <parent>
        <artifactId>spring-cloud-gcp</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-cloud-gcp-bigquery-sample</artifactId>

    <properties>
        <maven.compiler.source>17</maven.compiler.source>
        <maven.compiler.target>17</maven.compiler.target>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.google.cloud</groupId>
            <artifactId>spring-cloud-gcp-starter-bigquery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!-- Test-related dependencies. -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

2. 配置文件

2.1 application.properties

spring.cloud.gcp.bigquery.dataset-name=test_dataset
spring.cloud.gcp.bigquery.project-id=feisty-truth-447013-m7
spring.cloud.gcp.bigquery.credentials.location=file:/path-to-key/keyfile.json

舉例:請(qǐng)將 path-to-key/keyfile.json 替換為你的服務(wù)賬戶(hù)私鑰文件路徑。

2.2 IAM 訪問(wèn)權(quán)限

確保對(duì)應(yīng)的服務(wù)賬戶(hù)具備以下角色:

  • BigQuery Data Viewer
  • BigQuery Job User

使用以下指令加入 IAM 訪問(wèn)權(quán)限:

gcloud projects add-iam-policy-binding PROJECT_ID \
    --member="serviceAccount:YOUR_SERVICE_ACCOUNT_EMAIL" \
    --role="roles/bigquery.jobUser"

替換 PROJECT_ID 和 YOUR_SERVICE_ACCOUNT_EMAIL 為你實(shí)際的項(xiàng)目 ID 和服務(wù)賬戶(hù)郵箱地址。

3. 實(shí)現(xiàn)邏輯

3.1 創(chuàng)建接口

將文件上傳至 BigQuery

/*
 * Copyright 2017-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.et;

import com.et.BigQuerySampleConfiguration.BigQueryFileGateway;
import com.google.cloud.bigquery.*;
import com.google.cloud.spring.bigquery.core.BigQueryTemplate;
import com.google.cloud.spring.bigquery.core.WriteApiResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.concurrent.CompletableFuture;

/** Provides REST endpoint allowing you to load data files to BigQuery using Spring Integration. */
@Controller
public class WebController {

  private final BigQueryFileGateway bigQueryFileGateway;

  private final BigQueryTemplate bigQueryTemplate;

  private static final String DATASET_NAME = "datasetName";

  @Value("${spring.cloud.gcp.bigquery.datasetName}")
  private String datasetName;

  public WebController(BigQueryFileGateway bigQueryFileGateway,
      BigQueryTemplate bigQueryTemplate) {
    this.bigQueryFileGateway = bigQueryFileGateway;
    this.bigQueryTemplate = bigQueryTemplate;
  }

  @GetMapping("/")
  public ModelAndView renderIndex(ModelMap map) {
    map.put(DATASET_NAME, this.datasetName);
    return new ModelAndView("index.html", map);
  }

  @GetMapping("/write-api-json-upload")
  public ModelAndView renderUploadJson(ModelMap map) {
    map.put(DATASET_NAME, this.datasetName);
    return new ModelAndView("upload-json.html", map);
  }

  /**
   * Handles a file upload using {@link BigQueryTemplate}.
   *
   * @param file the JSON file to upload to BigQuery
   * @param tableName name of the table to load data into
   * @return ModelAndView of the response the send back to users
   * @throws IOException if the file is unable to be loaded.
   */
  @PostMapping("/uploadJsonFile")
  public ModelAndView handleJsonFileUpload(
      @RequestParam("file") MultipartFile file,
      @RequestParam("tableName") String tableName,
      @RequestParam(name = "createTable", required = false) String createDefaultTable)
      throws IOException {
    CompletableFuture<WriteApiResponse> writeApiRes;
    if (createDefaultTable != null
        && createDefaultTable.equals("createTable")) { // create the default table
      writeApiRes =
          this.bigQueryTemplate.writeJsonStream(
              tableName, file.getInputStream(), getDefaultSchema());
    } else { // we are expecting the table to be already existing
      writeApiRes = this.bigQueryTemplate.writeJsonStream(tableName, file.getInputStream());
    }
    return getWriteApiResponse(writeApiRes, tableName);
  }

  private Schema getDefaultSchema() {
    return Schema.of(
        Field.of("CompanyName", StandardSQLTypeName.STRING),
        Field.of("Description", StandardSQLTypeName.STRING),
        Field.of("SerialNumber", StandardSQLTypeName.NUMERIC),
        Field.of("Leave", StandardSQLTypeName.NUMERIC),
        Field.of("EmpName", StandardSQLTypeName.STRING));
  }

  /**
   * Handles JSON data upload using using {@link BigQueryTemplate}.
   *
   * @param jsonRows the String JSON data to upload to BigQuery
   * @param tableName name of the table to load data into
   * @return ModelAndView of the response the send back to users
   */
  @PostMapping("/uploadJsonText")
  public ModelAndView handleJsonTextUpload(
      @RequestParam("jsonRows") String jsonRows,
      @RequestParam("tableName") String tableName,
      @RequestParam(name = "createTable", required = false) String createDefaultTable) {
    CompletableFuture<WriteApiResponse> writeApiRes;
    if (createDefaultTable != null
        && createDefaultTable.equals("createTable")) { // create the default table

      writeApiRes =
          this.bigQueryTemplate.writeJsonStream(
              tableName, new ByteArrayInputStream(jsonRows.getBytes()), getDefaultSchema());
    } else { // we are expecting the table to be already existing
      writeApiRes =
          this.bigQueryTemplate.writeJsonStream(
              tableName, new ByteArrayInputStream(jsonRows.getBytes()));
    }
    return getWriteApiResponse(writeApiRes, tableName);
  }

  private ModelAndView getWriteApiResponse(
      CompletableFuture<WriteApiResponse> writeApiFuture, String tableName) {
    String message = null;
    try {
      WriteApiResponse apiResponse = writeApiFuture.get();
      if (apiResponse.isSuccessful()) {
        message = "Successfully loaded data to " + tableName;
      } else if (apiResponse.getErrors() != null && !apiResponse.getErrors().isEmpty()) {
        message =
            String.format(
                "Error occurred while loading the file, printing first error %s. Use WriteApiResponse.getErrors() to get the complete list of errors",
                apiResponse.getErrors().get(0).getErrorMessage());
      }

    } catch (Exception e) {
      e.printStackTrace();
      message = "Error: " + e.getMessage();
    }
    return new ModelAndView("upload-json.html")
        .addObject(DATASET_NAME, this.datasetName)
        .addObject("message", message);
  }

  /**
   * Handles a file upload using {@link BigQueryTemplate}.
   *
   * @param file the CSV file to upload to BigQuery
   * @param tableName name of the table to load data into
   * @return ModelAndView of the response to send back to users
   * @throws IOException if the file is unable to be loaded.
   */
  @PostMapping("/uploadFile")
  public ModelAndView handleFileUpload(
      @RequestParam("file") MultipartFile file, @RequestParam("tableName") String tableName)
      throws IOException {

    CompletableFuture<Job> loadJob =
        this.bigQueryTemplate.writeDataToTable(
            tableName, file.getInputStream(), FormatOptions.csv());

    return getResponse(loadJob, tableName);
  }

  /**
   * Handles CSV data upload using Spring Integration {@link BigQueryFileGateway}.
   *
   * @param csvData the String CSV data to upload to BigQuery
   * @param tableName name of the table to load data into
   * @return ModelAndView of the response the send back to users
   */
  @PostMapping("/uploadCsvText")
  public ModelAndView handleCsvTextUpload(
      @RequestParam("csvText") String csvData, @RequestParam("tableName") String tableName) {

    CompletableFuture<Job> loadJob =
        this.bigQueryFileGateway.writeToBigQueryTable(csvData.getBytes(), tableName);

    return getResponse(loadJob, tableName);
  }

  private ModelAndView getResponse(CompletableFuture<Job> loadJob, String tableName) {
    String message;
    try {
      Job job = loadJob.get();
      message = "Successfully loaded data file to " + tableName;
    } catch (Exception e) {
      e.printStackTrace();
      message = "Error: " + e.getMessage();
    }

    return new ModelAndView("index")
        .addObject(DATASET_NAME, this.datasetName)
        .addObject("message", message);
  }
}

以上只是一些關(guān)鍵代碼。

5.測(cè)試

在google cloud shell里面運(yùn)行代碼 運(yùn)行 $ mvn spring-boot:run 命令。

單擊 Cloud Shell 中的 Web Preview 按鈕以在端口 8080 上預(yù)覽應(yīng)用,并嘗試將一些數(shù)據(jù)加載到數(shù)據(jù)集下的 BigQuery 表中。該應(yīng)用程序接受 CSV 文件上傳或輸入到文本區(qū)域的 CSV 數(shù)據(jù)。如果 BigQuery 數(shù)據(jù)集下尚不存在該表,則會(huì)為您創(chuàng)建該表。

查看導(dǎo)入結(jié)果

以上就是SpringCloud3.x集成BigQuery的代碼實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于SpringCloud3.x集成BigQuery的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Java-Redis-Redisson分布式鎖的功能使用及實(shí)現(xiàn)

    Java-Redis-Redisson分布式鎖的功能使用及實(shí)現(xiàn)

    這篇文章主要介紹了Java-Redis-Redisson-分布式鎖的功能使用及實(shí)現(xiàn),本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-08-08
  • 如何自動(dòng)生成Mybatis的Mapper文件詳解

    如何自動(dòng)生成Mybatis的Mapper文件詳解

    這篇文章主要給大家介紹了關(guān)于如何自動(dòng)生成Mybatis的Mapper文件的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Mybatis具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • Java SpringBoot開(kāi)發(fā)小技巧詳解

    Java SpringBoot開(kāi)發(fā)小技巧詳解

    這篇文章主要介紹了淺談SpringBoot項(xiàng)目如何讓前端開(kāi)發(fā)提高效率(小技巧),主要介紹了Swagger和Nginx提高效率的方法,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Spring框架AOP面向切面編程原理全面分析

    Spring框架AOP面向切面編程原理全面分析

    這篇文章主要介紹了Spring框架AOP面向切面編程的全面分析,文中附含詳細(xì)的示例代碼分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助
    2021-09-09
  • springboot+springmvc+mybatis項(xiàng)目整合

    springboot+springmvc+mybatis項(xiàng)目整合

    這篇文章主要為大家詳細(xì)介紹了springboot+springmvc+mybatis項(xiàng)目的整合,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2018-04-04
  • 淺析IDEA如何正確配置Gradle? GRADLE_USER_HOME 和 Gradle user home的區(qū)別

    淺析IDEA如何正確配置Gradle? GRADLE_USER_HOME 和 Gradle user home的區(qū)別

    這篇文章主要介紹了IDEA如何正確配置Gradle? GRADLE_USER_HOME 和 Gradle user home的區(qū)別,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • jdk環(huán)境配置Maven環(huán)境配置實(shí)踐

    jdk環(huán)境配置Maven環(huán)境配置實(shí)踐

    文章介紹了如何配置JDK和Maven環(huán)境變量,并通過(guò)命令驗(yàn)證配置是否成功,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2026-02-02
  • java代理實(shí)現(xiàn)爬取代理IP的示例

    java代理實(shí)現(xiàn)爬取代理IP的示例

    今天小編就為大家分享一篇java代理實(shí)現(xiàn)爬取代理IP的示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2018-05-05
  • Java生成隨機(jī)姓名、性別和年齡的實(shí)現(xiàn)示例

    Java生成隨機(jī)姓名、性別和年齡的實(shí)現(xiàn)示例

    這篇文章主要介紹了Java生成隨機(jī)姓名、性別和年齡的實(shí)現(xiàn)示例,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • shiro實(shí)現(xiàn)單點(diǎn)登錄(一個(gè)用戶(hù)同一時(shí)刻只能在一個(gè)地方登錄)

    shiro實(shí)現(xiàn)單點(diǎn)登錄(一個(gè)用戶(hù)同一時(shí)刻只能在一個(gè)地方登錄)

    這篇文章主要介紹了shiro實(shí)現(xiàn)單點(diǎn)登錄(一個(gè)用戶(hù)同一時(shí)刻只能在一個(gè)地方登錄)的相關(guān)資料,非常不錯(cuò),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧
    2016-08-08

最新評(píng)論

平凉市| 台山市| 长沙县| 韶山市| 特克斯县| 南召县| 嘉黎县| 黄大仙区| 波密县| 富川| 武冈市| 柳江县| 吴江市| 博兴县| 内江市| 光山县| 闽侯县| 靖安县| 眉山市| 汝城县| 江津市| 大余县| 论坛| 文化| 嵩明县| 诏安县| 崇文区| 德钦县| 平原县| 中阳县| 遵义市| 虎林市| 合水县| 平昌县| 榆树市| 金堂县| 太谷县| 南宁市| 三门峡市| 瓦房店市| 汉阴县|