flink 流式处理中如何集成mybatis框架

本文详细介绍了如何在Flink 1.9版本的流式处理项目中集成MyBatis框架,通过引入MyBatis依赖,配置mybatis-config.xml,定义数据源和Mapper,实现对数据库的灵活控制。示例中展示了如何使用Druid连接池,并给出了SQL示例和实际的数据库操作示例,使得在大数据场景下也能充分利用MyBatis的优点。
摘要由CSDN通过智能技术生成

flink 中自身虽然实现了大量的connectors,如下图所示,也实现了jdbc的connector,可以通过jdbc 去操作数据库,但是flink-jdbc包中对数据库的操作是以ROW来操作并且对数据库事务的控制比较死板,有时候操作关系型数据库我们会非常怀念在java web应用开发中的非常优秀的mybatis框架,那么其实flink中是可以自己集成mybatis进来的。 我们这里以flink 1.9版本为例来进行集成。

如下图为flink内部自带的flink-jdbc:

 

创建一个flink的流式处理项目,引入flink的maven依赖和mybatis依赖(注意这里引入的是非spring版本,也就是mybatis的单机版):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

<properties>

 

<flink.version>1.9.0</flink.version>

</properties>

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->

<dependency>

    <groupId>org.mybatis</groupId>

    <artifactId>mybatis</artifactId>

    <version>3.5.2</version>

</dependency>

<!-- flink java 包 -->

<dependency>

    <groupId>org.apache.flink</groupId>

    <artifactId>flink-streaming-java_2.11</artifactId>

    <version>${flink.version}</version>

</dependency>

maven依赖引入以后,那么需要在resources下面定义mybatis-config.xml 配置:

mybatis-config.xml 需要定义如下配置:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeAliases>

        <typeAlias alias="BankBillPublic" type="xxxx.xx.xx.BankBillPublic" />

    </typeAliases>

    <environments default="development">

        <environment id="development">

            <transactionManager type="JDBC" />

            <dataSource type="POOLED">

                <property name="driver" value="com.mysql.jdbc.Driver" />

                <property name="url" value="jdbc:mysql://xx.xx.xx.xx:3306/hue?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&autoReconnect=true" />

                <property name="username" value="xxxx" />

                <property name="password" value="xxxx*123%" />

            </dataSource>

        </environment>

    </environments>

    <mappers>

        <mapper resource="mapper/xxxxxMapper.xml" />

    </mappers>

</configuration>

typeAlias 标签中为自定义的数据类型,然后在xxxxxMapper.xml 中parameterType或者resultType就可以直接用这种定义的数据类型。

dataSource type="POOLED" 我们使用的是mybatis中的POOLED 类型,也就是连接池的方式去使用。默认支持如下这三种类型。

 我们也可以使用阿里巴巴开源的druid连接池,那么就需要引入对应的maven依赖,如下所示:

1

2

3

4

5

<dependency>

    <groupId>com.alibaba</groupId>

    <artifactId>druid</artifactId>

    <version>1.0.14</version>

</dependency>  

 然后定义一个对应的druid的DataSource,如下所示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

import java.sql.SQLException;

import java.util.Properties;

import javax.sql.DataSource;

import org.apache.ibatis.datasource.DataSourceFactory;

import com.alibaba.druid.pool.DruidDataSource;

 

public class DruidDataSourceFactory implements DataSourceFactory {

    private Properties props;

 

    @Override

    public DataSource getDataSource() {

        DruidDataSource dds = new DruidDataSource();

        dds.setDriverClassName(this.props.getProperty("driver"));

        dds.setUrl(this.props.getProperty("url"));

        dds.setUsername(this.props.getProperty("username"));

        dds.setPassword(this.props.getProperty("password"));

        // 其他配置可以根据MyBatis主配置文件进行配置

        try {

            dds.init();

        catch (SQLException e) {

            e.printStackTrace();

        }

        return dds;

    }

 

    @Override

    public void setProperties(Properties props) {

        this.props = props;

    }

}

之后就可以mybatis的配置中使用了,如下所示:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <typeAliases>

        <typeAlias alias="BankBillPublic" type="xxxx.xx.xx.BankBillPublic" />

        <typeAlias alias="DRUID"

 type="com.xx.mybatis.druid.utils.DruidDataSourceFactory" />

    </typeAliases>

    <environments default="development">

        <environment id="development">

            <transactionManager type="JDBC" />

            <dataSource type="DRUID">

                <property name="driver" value="com.mysql.jdbc.Driver" />

                <property name="url" value="jdbc:mysql://xx.xx.xx.xx:3306/hue?characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&autoReconnect=true" />

                <property name="username" value="xxxx" />

                <property name="password" value="xxxx*123%" />

            </dataSource>

        </environment>

    </environments>

    <mappers>

        <mapper resource="mapper/xxxxxMapper.xml" />

    </mappers>

</configuration>

<mappers> 下面为定义的mybatis 的xxxxxMapper文件。里面放置的都是sql语句。

本文作者张永清,转载请注明出处:flink 流式处理中如何集成mybatis框架

xxxxxMapper.xml 中的sql示例:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<?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="xx.xx.bigdata.flink.xx.xx.mapper.UserRelaInfoMapper">

    <!--查询关键字匹配 -->

    <select id="queryUserRelaInfo" parameterType="String" resultType="UserRelaInfo">

        SELECT id AS id,

        USER_NAME AS userName,

        APPL_IDCARD AS applIdCard,

        PEER_USER AS peerUser,

        RELA_TYPE AS relaType,

        CREATE_USER AS createUser,

        CREATE_TIME AS createTime

        FROM USER_RELA_INFO

        <where>

            <if test="applIdCard != null">

                APPL_IDCARD=#{applIdCard}

            </if>

            <if test="peerUser != null">

            AND PEER_USER=#{peerUser}

            </if>

        </where>

    </select>

</mapper>

 定义Mapper,一般可以定义一个interface ,和xxxxxMapper.xml中的namespace保持一致

注意传入的参数一般加上@Param 注解,传入的参数和xxxxxMapper.xml中需要的参数保持一致

1

2

3

public interface UserRelaInfoMapper {

    List<UserRelaInfo> queryUserRelaInfo(@Param("applIdCard")String applIdCard,@Param("peerUser") String peerUser);

}

定义SessionFactory工厂(单例模式):

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

/**

 *

 *  sqlsession factory 单例  事务设置为手动提交

 */

public class MybatisSessionFactory {

    private static final Logger LOG = LoggerFactory.getLogger(MybatisSessionFactory.class);

    private static SqlSessionFactory sqlSessionFactory;

    private MybatisSessionFactory(){

        super();

    }

    public synchronized static SqlSessionFactory getSqlSessionFactory(){

        if(null==sqlSessionFactory){

            InputStream inputStream=null;

            try{

                inputStream = MybatisSessionFactory.class.getClassLoader().getResourceAsStream("mybatis-config.xml");

                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            }

            catch (Exception e){

                LOG.error("create MybatisSessionFactory read mybatis-config.xml cause Exception",e);

            }

            if(null!=sqlSessionFactory){

                LOG.info("get Mybatis sqlsession sucessed....");

            }

            else {

                LOG.info("get Mybatis sqlsession failed....");

            }

        }

        return sqlSessionFactory;

    }

}

  

使用mybatis 对数据库进行操作:

1

2

3

4

5

6

7

8

9

10

11

SqlSession sqlSession = MybatisSessionFactory.getSqlSessionFactory().openSession();

UserRelaInfoMapper  userRelaInfoMapper  = sqlSession.getMapper(UserRelaInfoMapper .class);

//调用对应的方法

userRelaInfoMapper.xxxx();

//提交事务

sqlSession.commit();

//回滚事务,一般可以捕获异常,在发生Exception的时候,事务进行回滚

sqlSession.rollback();

这里以mysql为示例,写一个flink下mysql的sink示例,可以自己来灵活控制事务的提交:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

public class MysqlSinkFunction<IN> extends RichSinkFunction {

    private static final Logger LOG = LoggerFactory.getLogger(MysqlSinkFunction.class);

    @Override

    public void invoke(Object value, Context context) throws Exception{

        SqlSession sqlSession = MybatisSessionFactory.getSqlSessionFactory().openSession();

        try{

                            //插入

                            LOG.info("MysqlSinkFunction start to do insert data...");

                            xxx.xxx();

                            //更新

                            LOG.info("MysqlSinkFunction start to do update data...");

                            xxx.xxx();

                            //删除

                            LOG.info("MysqlSinkFunction start to do delete data...");

                            xxx.xxx();

 

                     

                 

                sqlSession.commit();

                LOG.info("MysqlSinkFunction commit transaction success...");

        }

        catch (Throwable e){

            sqlSession.rollback();

            LOG.error("MysqlSinkFunction cause Exception,sqlSession transaction rollback...",e);

        }

    }

}  

相信您如果以前在spring中用过mybatis的话,对上面的这些操作一定不会陌生。由此你也可以发现,在大数据中可以完美的集成mybatis,这样可以发挥mybatis框架对数据库操作的优势,使用起来也非常简单方便。
一旦集成了mybaitis后,在flink中就可以方便的对各种各样的关系型数据库进行操作了。
本文作者张永清,转载请注明出处:flink 流式处理中如何集成mybatis框架
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Flink 是一个流式处理框架,可用于构建和运行高性能、可靠且可伸缩的流式应用程序。它提供了一种以事件时间处理数据的方式,支持低延迟和高吞吐量的处理能力。 Flink流式处理模型基于无界数据流,在输入数据不断到达的过程进行实时计算和处理。它能够处理无限量的数据,并且能够以低延迟的方式对数据进行处理Flink 通过流处理 API 和数据流图的概念来描述流式处理应用程序。数据流图是由一个或多个算子组成的有向无环图,通过这些算子对数据进行转换和处理。数据以事件的形式进行处理,每个事件都会被传递给相应的算子,然后根据指定的逻辑进行处理,最终输出结果。 Flink 提供了丰富的算子库,包括各种转换、聚合和窗口操作,以满足不同场景下的需求。它还支持事件时间处理,可以处理乱序的事件,并根据事件时间进行窗口操作,保证数据处理的准确性。 除了流处理Flink 还支持批处理,可以将批处理和流处理无缝集成在一个应用程序。这使得开发人员可以在同一个框架下进行各种类型的数据处理,极大地简化了应用程序的开发和维护。 总之,Flink 是一个功能强大而灵活的流式处理框架,能够满足各种实时数据处理的需求,并且具有良好的可扩展性和容错性。它是构建实时大数据应用程序的理想选择。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值