java用jdbc連接impala

本文介紹一種使用使用mybatis + dbcp2操作impala的方法玩般。

第一步,創(chuàng)建一個maven工程淤井,目錄結(jié)構(gòu)如下
image.png
第二步史简,引入pom坐標(biāo)
 <dependency>
            <groupId>impala</groupId>
            <artifactId>impala-jdbc41</artifactId>
            <version>2.6.17.1020</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.28</version>
        </dependency>

如果impala-jdbc41的包maven不能自動下載到本地,就到官網(wǎng)下載顽频,然后上傳到maven私服藤肢。官網(wǎng)連接:https://www.cloudera.com/downloads/connectors/impala/jdbc/2-6-17.html

image.png

本文創(chuàng)建的是springboot項目,還需要引入坐標(biāo)

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
    </parent>
<dependencies>
<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
</dependencies>
第三步糯景,創(chuàng)建配置文件

在resources下面創(chuàng)建application.yml文件嘁圈,配置如下

server:
  port: 8190
spring:
  application:
    name: impala-server
  impala:
    url: jdbc:impala://110.110.110.110:21050/
    driver-class-name: com.cloudera.impala.jdbc41.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      max-active: 200
      initial-size: 1
      min-idle: 3
      max-wait: 60000
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      testWhileIdle: true
      validationQuery: select '1'
      poolPreparedStatements: true
      maxPoolPreparedStatementPerConnectionSize: 200

mybatis:
  mapper-locations:  classpath*:mapping/*.xml
  impala-mapper-locations: classpath*:impalaMapping/*.xml
  type-aliases-package: com.bigdata.bean
  configuration:
    call-setters-on-nulls: true
第四步,創(chuàng)建Java文件
  1. 在config目錄下創(chuàng)建BigDataSourceConfig
package com.bigdata.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.sql.SQLException;

@Configuration
@EnableTransactionManagement
@MapperScan(basePackages = {"com.bigdata.dao"},sqlSessionFactoryRef = "impalaSqlSessionFactory")
public class BigDataSourceConfig implements EnvironmentAware {
    private RelaxedPropertyResolver propertyResolver;

    public void setEnvironment(Environment environment) {
        this.propertyResolver = new RelaxedPropertyResolver(environment);
    }

    @Bean
    public DataSource impalaDataSource() {
        BasicDataSource datasource = new BasicDataSource();
        datasource.setUrl(this.propertyResolver.getProperty("spring.impala.url"));
        datasource.setDriverClassName(this.propertyResolver.getProperty("spring.impala.driver-class-name"));
        datasource.setInitialSize(Integer.valueOf(this.propertyResolver.getProperty("spring.impala.druid.initial-size")));
        datasource.setMinIdle(Integer.valueOf(this.propertyResolver.getProperty("spring.impala.druid.min-idle")));
        datasource.setMaxWaitMillis(Long.valueOf(this.propertyResolver.getProperty("spring.impala.druid.max-wait")));
        datasource.setMaxTotal(Integer.valueOf(this.propertyResolver.getProperty("spring.impala.druid.max-active")));
        datasource.setMinEvictableIdleTimeMillis(Long.valueOf(this.propertyResolver.getProperty("spring.impala.druid.min-evictable-idle-time-millis")));
        datasource.setValidationQuery(String.valueOf(this.propertyResolver.getProperty("spring.impala.druid.validationQuery")));
        return datasource;
    }

    @Bean
    public SqlSessionFactory impalaSqlSessionFactory() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(this.impalaDataSource());
        sqlSessionFactoryBean.setTypeAliasesPackage(this.propertyResolver.getProperty("mybatis.type-aliases-package"));
        sqlSessionFactoryBean.setMapperLocations((new PathMatchingResourcePatternResolver()).getResources(this.propertyResolver.getProperty("mybatis.impala-mapper-locations")));
        org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
        configuration.setCallSettersOnNulls(true);
        sqlSessionFactoryBean.setConfiguration(configuration);
        return sqlSessionFactoryBean.getObject();
    }

    @Bean
    public PlatformTransactionManager impalaTransactionManager() throws SQLException {
        return new DataSourceTransactionManager(this.impalaDataSource());
    }
}
  1. 在dao目錄下創(chuàng)建ImpalaDao類
import org.springframework.stereotype.Repository;

import java.util.LinkedHashMap;
import java.util.List;

@Repository
public interface ImpalaDao {
    List<LinkedHashMap> executeSql(String sql);
}
  1. 在resources目錄下創(chuàng)建impalaMapping文件夾莺奸,然后在下面創(chuàng)建ImpalaMapper.xml配置文件
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.bigdata.dao.ImpalaDao">

    <select id="executeSql" parameterType="String" resultType="java.util.LinkedHashMap">
        ${_parameter}
    </select>
</mapper>

4, 在service目錄下創(chuàng)建ImpalaJdbc.java文件

package com.bigdata.service;

import com.bigdata.dao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Component
public class ImpalaJdbc {
    @Resource
    private ImpalaDao impalaDao;
    public static final Logger logger = LoggerFactory.getLogger(ImpalaJdbc.class);
    public boolean executeSQL(String sql) {
        try {
            impalaDao.executeSql(sql);
            logger.info("executeSQL...." + sql);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public List executeQueryForList(String execSql) {
        List list = impalaDao.executeSql(execSql);
        return list;
    }

    public long getCounte(String tabName) {
        String sql = "select count(*) c from " + tabName;
        try {
            List<LinkedHashMap> list = impalaDao.executeSql(sql);
            long num = Long.parseLong(list != null && list.size() > 0 ? ((LinkedHashMap)list.get(0)).get("c").toString() : "0");
            return num;
        } catch (Exception e) {
            e.printStackTrace();
            return 0L;
        }
    }
}
  1. 在controller目錄下創(chuàng)建BigDataController.java文件
package com.bigdata.controller;

import com.bigdata.service.ImpalaJdbc;

import javax.annotation.Resource;

@Slf4j
@RestController
@Api(value = "impala測試")
public class BigDataController {
    @Resource
    ImpalaJdbc impalaJdbc;

    @ApiOperation("sql測試")
    @RequestMapping(value = {"/executeSQL"}, method = {RequestMethod.POST})
    public boolean executeSQL(@RequestParam @ApiParam(value = "sql語句", required = true) String sql) {
        return impalaJdbc.executeSQL(sql);
    }

}

6.在com.bigdata目錄下創(chuàng)建BigDataApplication.java啟動類

package com.bigdata;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
@MapperScan("com.bigdata.dao")
public class BigDataApplication {

    public static void main(String[] args) {
        SpringApplication.run(BigDataApplication.class, args);
    }
}
  1. 為了方便演示引入swagger丑孩,在config目錄下創(chuàng)建SwaggerConfig.java
    先引入maven坐標(biāo)
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.8.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.8.0</version>
        </dependency>
package com.bigdata.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket api() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                // 選擇那些路徑和api會生成document
                .select()
                // 對所有api進(jìn)行監(jiān)控
//                .apis(RequestHandlerSelectors.any())
                .apis(RequestHandlerSelectors.basePackage("com.bigdata.controller"))
                // 對所有路徑進(jìn)行監(jiān)控
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("impala測試")
                .description("測試API")
                .termsOfServiceUrl("")
                //程序猿ID
                .contact(new Contact("空塵AI","",""))
                .version("1.0")
                .build();
    }
}

8.運行啟動類BigDataApplication冀宴,啟動后通過瀏覽器訪問swagger頁面
http://localhost:8190/swagger-ui.html#!
在接口參數(shù)中輸入SQL語句即可測試

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末灭贷,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子略贮,更是在濱河造成了極大的恐慌甚疟,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,826評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件逃延,死亡現(xiàn)場離奇詭異览妖,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)揽祥,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,968評論 3 395
  • 文/潘曉璐 我一進(jìn)店門讽膏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人拄丰,你說我怎么就攤上這事府树±” “怎么了?”我有些...
    開封第一講書人閱讀 164,234評論 0 354
  • 文/不壞的土叔 我叫張陵奄侠,是天一觀的道長卓箫。 經(jīng)常有香客問我,道長垄潮,這世上最難降的妖魔是什么烹卒? 我笑而不...
    開封第一講書人閱讀 58,562評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮弯洗,結(jié)果婚禮上旅急,老公的妹妹穿的比我還像新娘。我一直安慰自己涂召,他們只是感情好坠非,可當(dāng)我...
    茶點故事閱讀 67,611評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著果正,像睡著了一般炎码。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上秋泳,一...
    開封第一講書人閱讀 51,482評論 1 302
  • 那天潦闲,我揣著相機(jī)與錄音,去河邊找鬼迫皱。 笑死歉闰,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的卓起。 我是一名探鬼主播和敬,決...
    沈念sama閱讀 40,271評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼戏阅!你這毒婦竟也來了昼弟?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,166評論 0 276
  • 序言:老撾萬榮一對情侶失蹤奕筐,失蹤者是張志新(化名)和其女友劉穎舱痘,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體离赫,經(jīng)...
    沈念sama閱讀 45,608評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡芭逝,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,814評論 3 336
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了渊胸。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片旬盯。...
    茶點故事閱讀 39,926評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出胖翰,到底是詐尸還是另有隱情频丘,我是刑警寧澤,帶...
    沈念sama閱讀 35,644評論 5 346
  • 正文 年R本政府宣布泡态,位于F島的核電站搂漠,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏某弦。R本人自食惡果不足惜桐汤,卻給世界環(huán)境...
    茶點故事閱讀 41,249評論 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望靶壮。 院中可真熱鬧怔毛,春花似錦、人聲如沸腾降。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,866評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽螃壤。三九已至抗果,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間奸晴,已是汗流浹背冤馏。 一陣腳步聲響...
    開封第一講書人閱讀 32,991評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留寄啼,地道東北人逮光。 一個月前我還...
    沈念sama閱讀 48,063評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像墩划,于是被迫代替她去往敵國和親涕刚。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,871評論 2 354