flink2_ source读取数据

在flink程序流程中属于第二步

从集合或文件中读取

// 从集合中读取
env.fromCollection(Arrays.asList(
                "hello java",
                "hello spark",
                "hello flink",
                "hello scala"));

// 从文件中读取
env.readTextFile("<filePath>");

从kafka中读取

添加第三方包

<dependency>
    <groupId>org.apache.flink</groupId>
    <artifactId>flink-connector-kafka-0.11_2.11</artifactId>
    <version>1.10.1</version>
 </dependency>

连接代码

// 定义链接kafka的对应配置,告诉程序如何连接kafka,即kafka地址,offset的机制等
Properties properties = new Properties();
properties.setProperty("bootstrap.servers","localhost:9092");
properties.setProperty("group_id","consumer-group");
properties.setProperty("key.deserializer","org.apache.kafka.common.serialization.StrinDeserializer");       
properties.setProperty("value.deserializer","org.apache.kafka.common.serialization.StrinDeserializer");
properties.setProperty("auto.offset.reset","latest");

DataStreamSource<String> = 
          env.addSource(new FlinkKafkaConsumer010<String>(
                // kafka的topic
                "test",
                new SimpleStringSchema(),
                properties));

自定义source 数据源

package com.flinkTest.source;

import com.flinkTest.POJO.SensorReading;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.source.SourceFunction;

import java.util.HashMap;
import java.util.Random;

public class ModifyMySource {
    public static void main(String[] args) throws Exception {

        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();

        DataStreamSource inputStream = env.addSource(new MySource()); // 从自定义数据源读取数据

        inputStream.print(); // 没有逻辑处理,直接打印

        env.execute();

    }
    
    /** 自定义数据源, 数据是 生产1组 10个温度传感器的对象
     *  
     * */
    public static class  MySource<i> implements SourceFunction<SensorReading> {
        private boolean running = true;
        
        @Override
        public void run(SourceContext sourceContext) throws Exception {

            Random random = new Random();
            //生成10个初始sensor温度
            // 设置初始温度值(10个)
            HashMap<String,Double> tempMap = new HashMap<>();

            for (int i =0; i<10 ; i++){
                tempMap.put("sensor_" + (i+1), 60+random.nextGaussian()*20);
            }
            
            while(running){
                for(String id: tempMap.keySet()){
                    Double newTemp = tempMap.get(id) + random.nextGaussian();
                    tempMap.put(id,newTemp);
                    sourceContext.collect(new SensorReading(id,System.currentTimeMillis(),newTemp));
                }

                Thread.sleep(1000);
            }
        }

        @Override
        public void cancel() {
            running = false;
        }
    }
    
    // 温度传感器 内部类
    public  static  class SensorReading {
        private String id;
        private Long timestamp;
        private Double temperature;

    public SensorReading() {
        }

    public SensorReading(String id, Long timestamp, Double temperature) {
            this.id = id;
            this.timestamp = timestamp;
            this.temperature = temperature;
        }

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public Long getTimestamp() {
            return timestamp;
        }

        public void setTimestamp(Long timestamp) {
            this.timestamp = timestamp;
        }

        public Double getTemperature() {
            return temperature;
        }

        public void setTemperature(Double temperature) {
            this.temperature = temperature;
        }

        @Override
        public String toString() {
            return "SensorReading{" +
                    "id='" + id + '\'' +
                    ", timestamp=" + timestamp +
                    ", temperature=" + temperature +
                    '}';
        }
    }
}

 

Flink是一个高性能流式处理引擎,可以读取各种各样的数据源,包括自定义的源。自定义源是使用Flink的一种方式,主要是为了读取一些非标准的数据源或者改善性能表现。 自定义source是一个接口,需要实现org.apache.flink.streaming.api.functions.source.SourceFunction接口。该接口只有两个方法,一个是run(),另一个是cancel()。在run()中实现数据读取的逻辑,cancel()用于取消读取。自定义source主要包括数据什么时候开始读取,如何读取数据及什么时候读取结束等。 实现自定义source需要在程序入口处调用StreamExecutionEnvironment对象中的addSource()方法,将自定义source添加到批处理中。示例如下: ```java DataStreamSource<String> dataSource = env.addSource(new MySource()); ``` 其中,MySource是自定义的数据源。 在自定义source中,可以采用文件缓存方式来提升读取性能。通过FileChannel打开文件,使用ByteBuffer读取文件,然后将ByteBuffer通过Flink的DataStream传递给后续算子处理。这种方式可以大大提升文件读取的性能,减少文件IO的次数。示例如下: ```java try { FileInputStream inputStream = new FileInputStream(filePath); FileChannel inChannel = inputStream.getChannel(); ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 5); while (inChannel.read(buffer) != -1) { buffer.flip(); sourceContext.collect(buffer); buffer.clear(); } } catch (IOException e) { e.printStackTrace(); } ``` 自定义source的实现需要根据具体的数据源进行,但总体来说,实现自定义源并不复杂,只需要理解Flink数据处理的机制,并编写封装好的代码即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值