使用RichMapFunction关联维度数据

package org.myorg.quickstart;

public class OrderBean {
    public String province;
    public String city;
    public double money;

    public OrderBean() {
    }

    public OrderBean(String province, String city, double money) {
        this.province = province;
        this.city = city;
        this.money = money;
    }

    public static OrderBean of(String province,String city,double money){
        return new OrderBean(province,city,money);
    }

    @Override
    public String toString() {
        return "OrderBean{" +
                "province='" + province + '\'' +
                ", city='" + city + '\'' +
                ", money=" + money +
                '}';
    }
}
package org.myorg.quickstart.stream;

import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.configuration.Configuration;
import org.myorg.quickstart.OrderBean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;


public class TestRichMap extends RichMapFunction{

    //数据格式: 江西,a,20
    private Connection conn = null;
    @Override
    public void open(Configuration parameters) throws Exception {
        super.open(parameters);
        //创建Mysql连接
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bigdata?characterEncoding=UTF-8", "pgxl", "123456");
    }

    @Override
    public OrderBean map(String line) throws Exception {
        String[] fileds = line.split(",");
        String provinceName = fileds[0];
        String cityId = fileds[1];
        double money = Double.parseDouble(fileds[2]);
        //根据cityId查询Mysql中的维表,获取cityName
        PreparedStatement pst = conn.prepareStatement("select city_name from city_info where cityId = ?");
        pst.setString(1,cityId);
        ResultSet resultSet = pst.executeQuery();
        String cityName = null;
        while (resultSet.next()){
            cityName = resultSet.getString(1);
        }

        pst.close();

        return new OrderBean(provinceName,cityName,money);
    }

    @Override
    public void close() throws Exception {
        super.close();
        conn.close();
    }
}

 

你可能感兴趣的:(Flink)