使用应用程序(Java/Python)访问MaxCompute Lightning进行数据开发

简介: 很多开发者希望利用Lightning的特性开发数据应用,本文将结合示例介绍Java和Python如何连接访问Lightning进行应用开发。内容包括通过Java的JDBC、druid方式连接访问Lightning,Python通过pyscopg2、pyodbc访问Lightning。

MaxCompute Lightning是MaxCompute产品的交互式查询服务,支持以PostgreSQL协议及语法连接访问Maxcompute项目,让您使用熟悉的工具以标准 SQL查询分析MaxCompute项目中的数据,快速获取查询结果。
很多开发者希望利用Lightning的特性来开发数据应用,本文将结合示例来介绍Java和Python如何连接访问Lightning进行应用开发(参考时需要替换为您项目所在region的Endpoint及用户认证信息)。
一、Java使用JDBC访问Lightning
示例如下:

import java.sql.*;

public class Main {

    private static Connection connection;

    public static void main(String[] args) throws SQLException {

        String url = "jdbc:postgresql://lightning.cn-shanghai.maxcompute.aliyun.com:443/your_project_name?prepareThreshold=0&sslmode=require";
        String accessId = "<your_maxcompute_access_id>";
        String accessKey = "<your_maxcompute_access_key>";
        String sql = "select * from dual";

        try {
            Connection conn = getCon(url, accessId, accessKey);
            Statement st = conn.createStatement();
            System.out.println("Send Lightning query");
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                System.out.println(rs.getString(1)+ "\t");
            }
            System.out.println("End Lightning query");
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static Connection getCon(String lightningsHost, String lightningUser, String lightningPwd) {
        try {
            if (connection == null || connection.isClosed()) {
                try {
                    Class.forName("org.postgresql.Driver").newInstance();
                    DriverManager.setLoginTimeout(1);
                    connection = DriverManager.getConnection(lightningsHost, lightningUser, lightningPwd);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return connection;
    }
}

二、Java使用druid访问Lightning
1.pom依赖

<dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.23</version>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.3-1101-jdbc4</version>
        </dependency>

2.spring配置

    <bean id="LightningDataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
        <property name="url" value="jdbc:postgresql://lightning.cn-shanghai.maxcompute.aliyun.com:443/project_name?prepareThreshold=0&sslmode=require”/> <!--替换成自己project所在region的Endpoint—>
        <property name="username" value=“访问用户的Access Key ID"/>
        <property name="password" value="访问用户的Access Key Secret"/>
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="dbType" value="postgresql"/>
        <property name="initialSize" value="1" />  
        <property name="minIdle" value="1" />
        <property name="maxActive" value="5" />  <!—Lightning服务每个project的连接数限制20,所以不要配置过大,按需配置,否则容易出现query_wait_timeout错误 -->
 
        <!--以下两个配置,检测连接有效性,修复偶尔出现create connection holder error错误 -->
        <property name="testWhileIdle" value="true" />
        <property name="validationQuery" value="SELECT 1" />
    </bean>

  <bean class="com.xxx.xxx.LightningProvider">
    <property name="druidDataSource" ref="LightningDataSource"/>
  </bean>

3.代码访问

public class LightningProvider {

    DruidDataSource druidDataSource;
    /**
     * 执行sql
     * @param sql
     * @return
     * @throws Exception
     */
    public void execute(String sql) throws SQLException {
        DruidPooledConnection connection = null ;
        Statement st = null;
        try{
            connection = druidDataSource.getConnection();
            st = connection.createStatement();

            ResultSet resultSet = st.executeQuery(sql);
            //对返回值的解析和处理的代码
            //按行处理,每行的数据放到一个map中
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            List<LinkedHashMap> rows = Lists.newArrayList();
            while(resultSet.next()){
            LinkedHashMap map = Maps.newLinkedHashMap();
            for(int i=1;i<=columnCount;i++){
                String label = resultSet.getMetaData().getColumnLabel(i);
                map.put(label,resultSet.getString(i));
            }
            rows.add(map);
        }   
        }catch (Exception e){
             e.printStackTrace();
        }finally {
            try {
                if(st!=null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if(connection!=null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

三、Python使用pyscopg2访问Lightning
示例如下:

#!/usr/bin/env python
# coding=utf-8

import psycopg2
import sys

def query_lightning(lightning_conf, sql):
    """Query data through Lightning by sql

    Args:
        lightning_conf: a map contains settings of 'dbname', 'user', 'password', 'host', 'port'
        sql:  query submit to Lightning

    Returns:
        result: the query result in format of list of rows
    """
    result = None
    conn = None
    conn_str = None
    try:
        conn_str = ("dbname={dbname} "
                    "user={user} "
                    "password={password} "
                    "host={host} "
                    "port={port}").format(**lightning_conf)
    except Exception, e:
        print >> sys.stderr, ("Invalid Lightning' configuration "
                       "{}".format(e))
        sys.exit(1)

    try:
        conn = psycopg2.connect(conn_str)
        conn.set_session(autocommit=True) # This will disable transaction
                                   # started with keyword BEGIN,
                                   # which is currently not
                                   # supported by Lightning’ public service

        cur = conn.cursor()
        # execute Lightning' query
        cur.execute(sql)
        # get result
        result = cur.fetchall()
    except Exception, e:
        print >> sys.stderr, ("Failed to query data through "
                       "Lightning: {}".format(e))
    finally:
        if conn:
            conn.close()

    return result

if __name__ == "__main__":
    # step1. setup configuration
    lightning_conf = {
        "dbname": “your_project_name”,
        "user": "<your_maxcompute_access_id>", 
        "password": "<your_maxcompute_access_key>", 
        "host": "lightning.cn-shanghai.maxcompute.aliyun.com",  #your region lightning endpoint
        "port": 443
    }

    # step2. issue a query
    result = query_lightning(lightning_conf, "select * from test”)
    # step3. print result
    if result:
        for i in xrange(0, len(result)):
            print "Got %d row from Lightning:%s" % (i + 1, result[i])

四、Python使用ODBC访问Lightning
您需要现在电脑上安装并和配置odbc驱动。代码示例如下:

import pyodbc
conn_str = (
    "DRIVER={PostgreSQL Unicode};"
    "DATABASE=your_project_name;"
    "UID=your_maxcompute_access_id;"
    "PWD=your_maxcompute_access_key;"
    "SERVER=lightning.cn-shanghai.maxcompute.aliyun.com;" #your region lightning endpoint
    "PORT=443;"
    )
conn = pyodbc.connect(conn_str)
crsr = conn.execute("SELECT * from test”)
row = crsr.fetchone()
print(row)
crsr.close()
conn.close()

由于Lightning提供了PostgreSQL兼容的接口,您可以像开发PostgreSQL的应用一样开发Lightning应用程序。

MaxCompute产品官方地址:https://www.aliyun.com/product/odps
注:想了解更多阿里巴巴大数据计算服务MaxCompute,可以加入社群一起交流。
image

相关实践学习
使用PolarDB和ECS搭建门户网站
本场景主要介绍如何基于PolarDB和ECS实现搭建门户网站。
阿里云数据库产品家族及特性
阿里云智能数据库产品团队一直致力于不断健全产品体系,提升产品性能,打磨产品功能,从而帮助客户实现更加极致的弹性能力、具备更强的扩展能力、并利用云设施进一步降低企业成本。以云原生+分布式为核心技术抓手,打造以自研的在线事务型(OLTP)数据库Polar DB和在线分析型(OLAP)数据库Analytic DB为代表的新一代企业级云原生数据库产品体系, 结合NoSQL数据库、数据库生态工具、云原生智能化数据库管控平台,为阿里巴巴经济体以及各个行业的企业客户和开发者提供从公共云到混合云再到私有云的完整解决方案,提供基于云基础设施进行数据从处理、到存储、再到计算与分析的一体化解决方案。本节课带你了解阿里云数据库产品家族及特性。
目录
相关文章
|
7月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
513 6
|
7月前
|
Java 数据处理 索引
(Pandas)Python做数据处理必选框架之一!(二):附带案例分析;刨析DataFrame结构和其属性;学会访问具体元素;判断元素是否存在;元素求和、求标准值、方差、去重、删除、排序...
DataFrame结构 每一列都属于Series类型,不同列之间数据类型可以不一样,但同一列的值类型必须一致。 DataFrame拥有一个总的 idx记录列,该列记录了每一行的索引 在DataFrame中,若列之间的元素个数不匹配,且使用Series填充时,在DataFrame里空值会显示为NaN;当列之间元素个数不匹配,并且不使用Series填充,会报错。在指定了index 属性显示情况下,会按照index的位置进行排序,默认是 [0,1,2,3,...] 从0索引开始正序排序行。
542 0
|
8月前
|
监控 数据可视化 数据挖掘
Python Rich库使用指南:打造更美观的命令行应用
Rich库是Python的终端美化利器,支持彩色文本、智能表格、动态进度条和语法高亮,大幅提升命令行应用的可视化效果与用户体验。
783 0
|
8月前
|
机器学习/深度学习 算法 安全
【强化学习应用(八)】基于Q-learning的无人机物流路径规划研究(Python代码实现)
【强化学习应用(八)】基于Q-learning的无人机物流路径规划研究(Python代码实现)
629 6
存储 jenkins 持续交付
911 2
|
8月前
|
Java API 开发工具
【Azure Developer】Java代码实现获取Azure 资源的指标数据却报错 "invalid time interval input"
在使用 Java 调用虚拟机 API 获取指标数据时,因本地时区设置非 UTC,导致时间格式解析错误。解决方法是在代码中手动指定时区为 UTC,使用 `ZoneOffset.ofHours(0)` 并结合 `withOffsetSameInstant` 方法进行时区转换,从而避免因时区差异引发的时间格式问题。
384 4
|
8月前
|
算法 Java
Java多线程编程:实现线程间数据共享机制
以上就是Java中几种主要处理多线程序列化资源以及协调各自独立运行但需相互配合以完成任务threads 的技术手段与策略。正确应用上述技术将大大增强你程序稳定性与效率同时也降低bug出现率因此深刻理解每项技术背后理论至关重要.
534 16
|
8月前
|
设计模式 缓存 运维
Python装饰器实战场景解析:从原理到应用的10个经典案例
Python装饰器是函数式编程的精华,通过10个实战场景,从日志记录、权限验证到插件系统,全面解析其应用。掌握装饰器,让代码更优雅、灵活,提升开发效率。
594 0
|
9月前
|
数据采集 存储 数据可视化
Python网络爬虫在环境保护中的应用:污染源监测数据抓取与分析
在环保领域,数据是决策基础,但分散在多个平台,获取困难。Python网络爬虫技术灵活高效,可自动化抓取空气质量、水质、污染源等数据,实现多平台整合、实时更新、结构化存储与异常预警。本文详解爬虫实战应用,涵盖技术选型、代码实现、反爬策略与数据分析,助力环保数据高效利用。
477 0
|
9月前
|
数据采集 JSON Java
Java爬虫获取1688店铺所有商品接口数据实战指南
本文介绍如何使用Java爬虫技术高效获取1688店铺商品信息,涵盖环境搭建、API调用、签名生成及数据抓取全流程,并附完整代码示例,助力市场分析与选品决策。

热门文章

最新文章

相关产品

  • 云原生大数据计算服务 MaxCompute
  • 推荐镜像

    更多