Flink系列 - 實時數(shù)倉之?dāng)?shù)據(jù)入ElasticSearch實戰(zhàn)(九)

??我們實時的流處理入 ElasticSearch 中還是比較麻煩的琼懊,雖然說 flink 提供了相關(guān)的 sink 接口捂掰,但是一般來說僅僅是簡單的將數(shù)據(jù)插入而已,對于優(yōu)化以及使用用戶名和密碼登錄操作的話,不管官網(wǎng)還是網(wǎng)上票腰,寫得零零碎碎的,對于大佬來說可以拼接起來再用,但是對于像我這種菜鳥來說,那簡直是看天書一樣射富,一愣一愣的。今天寫這個案例主要是項目中涉及了這個需求粥帚,廢了半條命終于整理出來了胰耗,現(xiàn)在做個總結(jié),以便避免初學(xué)者再掉坑芒涡。
??廢話不多說柴灯,接下來我們開搞。费尽。赠群。

一、啟動服務(wù)器
[syy@nfdw elasticsearch-7.6.1]$ pwd
/opt/modules/elasticsearch-7.6.1
[syy@nfdw elasticsearch-7.6.1]$ bin/elasticsearch

[syy@nfdw kibana-7.6.1-linux-x86_64]$ pwd
/opt/modules/kibana-7.6.1-linux-x86_64
[syy@nfdw kibana-7.6.1-linux-x86_64]$ bin/kibana

登錄 kibana 控制臺:http://IP:5601/app/kibana#/dev_tools/console ,登錄成功如下:

image.png

二旱幼、代碼實現(xiàn)

2.1 添加依賴

        <!-- https://mvnrepository.com/artifact/org.apache.flink/flink-connector-elasticsearch7 -->
        <dependency>
            <groupId>org.apache.flink</groupId>
            <artifactId>flink-connector-elasticsearch7_2.11</artifactId>
            <version>${flink.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

2.2 主體代碼

public class App {

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

        //  獲取環(huán)境對象
        StreamExecutionEnvironment env = GetStreamExecutionEnvironment.getEnv();
        //請求kafka數(shù)據(jù)
        Properties prop = new Properties();
        prop.setProperty("bootstrap.servers","cdh101:9092");
        prop.setProperty("group.id","cloudera_mirrormaker");
        prop.put("value.serializer","org.apache.kafka.common.serialization.StringSerializer");
        FlinkKafkaConsumer011<String> myConsumer = new FlinkKafkaConsumer011("luchangyin", new SimpleStringSchema() ,prop);
        myConsumer.setStartFromLatest();  //最近的

        //請求kafka數(shù)據(jù)
        DataStreamSource<String> dataStream = env.addSource(myConsumer);
        //dataStream.print();   // {"id":"226","name":"tang tang - 226","sal":280751,"dept":"美女部","ts":1615191802523}

        SingleOutputStreamOperator<Employees> result = dataStream.map(new MapFunction<String, Employees>() {

            @Override
            public Employees map(String s) throws Exception {
                Employees emp = MyJsonUtils.str2JsonObj(s);
                emp.setEmpStartTime(new Date(emp.getTs()));
                emp.setDt(MyDateUtils.getDate2Second(emp.getEmpStartTime()));
                return emp;
            }
        });

        //result.print();
        // Employees(eId=257, eName=fei fei - 257, eSal=97674.0, eDept=美女部, ts=1615251002894, empStartTime=Tue Mar 09 08:50:02 GMT+08:00 2021, dt=2021-03-09)

        // 設(shè)置ES的服務(wù)器地址
        List<HttpHost> esAddresses = null;
        try {
            esAddresses = ESSinkUtil.getEsAddresses("10.122.1.115:9200");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }

        // 我們可以通過調(diào)試此方法的三個數(shù)值參數(shù)進(jìn)行優(yōu)化
        ESSinkUtil.addSink(esAddresses, "elastic", "123456", 100,100, 1,
                5, result, new ElasticsearchSinkFunction<Employees>() {
                    @Override
                    public void process(Employees emp, RuntimeContext runtimeContext, RequestIndexer requestIndexer) {
                        String indexStr = "employee_"+ MyDateUtils.getTime2Day(emp.getEmpStartTime()).replaceAll("-","");
                        System.out.println("索引為-> "+ indexStr);
                        requestIndexer.add(Requests.indexRequest()
                                .index(indexStr)
                                .source(GsonUtil.toJSONBytes(emp), XContentType.JSON));
                    }
                });


        env.execute("wo xi huan ni");

    }

}

2.3 實現(xiàn)SinkEs的工具類:

package com.nfdw.utils;

import org.apache.commons.lang.StringUtils;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.connectors.elasticsearch.ElasticsearchSinkFunction;
import org.apache.flink.streaming.connectors.elasticsearch7.ElasticsearchSink;
import org.apache.http.HttpHost;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class ESSinkUtil {

    /**
     * es sink
     *
     * @param hosts               es hosts
     * @param bulkFlushMaxActions bulk flush size
     * @param parallelism         并行數(shù)
     * @param data                數(shù)據(jù)
     * @param func
     * @param <T>
     */
    public static <T> void addSink(List<HttpHost> esAddresses, String userName, String passwd, int bulkFlushMaxActions,
                                   int bulkFlushMaxSizeMb, long bulkFlushInterval, int parallelism,
                                   SingleOutputStreamOperator<T> data, ElasticsearchSinkFunction<T> func) {
        //todo:xpack security
        ElasticsearchSink.Builder<T> esSinkBuilder = new ElasticsearchSink.Builder<>(esAddresses, func);

        // 鑒權(quán)查描,正對寫 es 需要密碼的場景
        if(StringUtils.isNotEmpty(userName) && StringUtils.isNotEmpty(passwd)){
            esSinkBuilder.setRestClientFactory(new HDRestClientFactory(userName,passwd));
        }

        //失敗處理策略
        esSinkBuilder.setFailureHandler(new RetryRequestFailureHandler());

        //bulk
        esSinkBuilder.setBulkFlushMaxActions(bulkFlushMaxActions);
        esSinkBuilder.setBulkFlushMaxSizeMb(bulkFlushMaxSizeMb);
        esSinkBuilder.setBulkFlushInterval(bulkFlushInterval);

        //-----------------------------------
        data.addSink(esSinkBuilder.build()).setParallelism(parallelism);
    }

    /**
     * 解析配置文件的 es hosts
     *
     * @param hosts
     * @return
     * @throws MalformedURLException
     */
    public static List<HttpHost> getEsAddresses(String hosts) throws MalformedURLException {
        String[] hostList = hosts.split(",");
        List<HttpHost> addresses = new ArrayList<>();
        for (String host : hostList) {
            if (host.startsWith("http")) {
                URL url = new URL(host);
                addresses.add(new HttpHost(url.getHost(), url.getPort()));
            } else {
                String[] parts = host.split(":", 2);
                if (parts.length > 1) {
                    addresses.add(new HttpHost(parts[0], Integer.parseInt(parts[1])));
                } else {
                    throw new MalformedURLException("invalid elasticsearch hosts format");
                }
            }
        }
        return addresses;
    }

}

2.4 設(shè)置密碼操作類 HDRestClientFactory:

package com.nfdw.utils;

import org.apache.flink.streaming.connectors.elasticsearch7.RestClientFactory;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClientBuilder;

public class HDRestClientFactory implements RestClientFactory {

    private String userName;
    private String password;
    transient CredentialsProvider credentialsProvider;

    public HDRestClientFactory(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    @Override
    public void configureRestClientBuilder(RestClientBuilder restClientBuilder) {
        if (credentialsProvider == null) {
            credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));
        }
        restClientBuilder.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
            @Override
            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpAsyncClientBuilder) {
                return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
            }
        }).setRequestConfigCallback(new RestClientBuilder.RequestConfigCallback() {
            @Override
            public RequestConfig.Builder customizeRequestConfig(RequestConfig.Builder builder) {
                builder.setConnectTimeout(5000);
                builder.setSocketTimeout(60000);
                builder.setConnectionRequestTimeout(2000);
                return builder;
            }
        });
    }
}

2.5 創(chuàng)建失敗策列處理類 RetryRequestFailureHandler :

package com.nfdw.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.flink.streaming.connectors.elasticsearch.ActionRequestFailureHandler;
import org.apache.flink.streaming.connectors.elasticsearch.RequestIndexer;
import org.apache.flink.util.ExceptionUtils;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.common.util.concurrent.EsRejectedExecutionException;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.Optional;

@Slf4j
public class RetryRequestFailureHandler implements ActionRequestFailureHandler {

    public RetryRequestFailureHandler() {
    }

    @Override
    public void onFailure(ActionRequest actionRequest, Throwable throwable, int i, RequestIndexer requestIndexer) throws Throwable {
        if (ExceptionUtils.findThrowable(throwable, EsRejectedExecutionException.class).isPresent()) {
            requestIndexer.add(new ActionRequest[]{actionRequest});
        } else {
            if (ExceptionUtils.findThrowable(throwable, SocketTimeoutException.class).isPresent()) {
                return;
            } else {
                Optional<IOException> exp = ExceptionUtils.findThrowable(throwable, IOException.class);
                if (exp.isPresent()) {
                    IOException ioExp = exp.get();
                    if (ioExp != null && ioExp.getMessage() != null && ioExp.getMessage().contains("max retry timeout")) {
                        log.error(ioExp.getMessage());
                        return;
                    }
                }
            }
            throw throwable;
        }
    }
}

2.6 創(chuàng)建一個 gson 解析類:

package com.nfdw.utils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.lang.reflect.Type;
import java.nio.charset.Charset;

public class GsonUtil {

    private final static Gson gson = new Gson();

    private final static Gson disableHtmlEscapingGson = new GsonBuilder().disableHtmlEscaping().create();

    public static <T> T fromJson(String value, Class<T> type) {
        return gson.fromJson(value, type);
    }

    public static <T> T fromJson(String value, Type type) {
        return gson.fromJson(value, type);
    }

    public static String toJson(Object value) {
        return gson.toJson(value);
    }

    public static String toJsonDisableHtmlEscaping(Object value) {
        return disableHtmlEscapingGson.toJson(value);
    }

    public static byte[] toJSONBytes(Object value) {
        return gson.toJson(value).getBytes(Charset.forName("UTF-8"));
    }

}

三、運行程序結(jié)果查詢?nèi)缦?/h6>
image.png

??這里需要注意的一點是:sinkEs 的流必須是 SingleOutputStreamOperator 的對象速警,至于優(yōu)化就是調(diào)節(jié)工具類中的那幾個數(shù)值參數(shù)即可叹誉,好了,F(xiàn)link 對 ES 的操作到此為止闷旧,希望能夠幫助到你哦长豁。。忙灼。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末匠襟,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子该园,更是在濱河造成了極大的恐慌酸舍,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,104評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件里初,死亡現(xiàn)場離奇詭異啃勉,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)双妨,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,816評論 3 399
  • 文/潘曉璐 我一進(jìn)店門淮阐,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人刁品,你說我怎么就攤上這事泣特。” “怎么了挑随?”我有些...
    開封第一講書人閱讀 168,697評論 0 360
  • 文/不壞的土叔 我叫張陵状您,是天一觀的道長。 經(jīng)常有香客問我,道長膏孟,這世上最難降的妖魔是什么眯分? 我笑而不...
    開封第一講書人閱讀 59,836評論 1 298
  • 正文 為了忘掉前任,我火速辦了婚禮骆莹,結(jié)果婚禮上颗搂,老公的妹妹穿的比我還像新娘。我一直安慰自己幕垦,他們只是感情好丢氢,可當(dāng)我...
    茶點故事閱讀 68,851評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著先改,像睡著了一般疚察。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上仇奶,一...
    開封第一講書人閱讀 52,441評論 1 310
  • 那天貌嫡,我揣著相機(jī)與錄音,去河邊找鬼该溯。 笑死岛抄,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的狈茉。 我是一名探鬼主播夫椭,決...
    沈念sama閱讀 40,992評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼氯庆!你這毒婦竟也來了蹭秋?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,899評論 0 276
  • 序言:老撾萬榮一對情侶失蹤堤撵,失蹤者是張志新(化名)和其女友劉穎仁讨,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體实昨,經(jīng)...
    沈念sama閱讀 46,457評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡洞豁,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,529評論 3 341
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了荒给。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片族跛。...
    茶點故事閱讀 40,664評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖锐墙,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情长酗,我是刑警寧澤溪北,帶...
    沈念sama閱讀 36,346評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響之拨,放射性物質(zhì)發(fā)生泄漏茉继。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,025評論 3 334
  • 文/蒙蒙 一蚀乔、第九天 我趴在偏房一處隱蔽的房頂上張望烁竭。 院中可真熱鬧,春花似錦吉挣、人聲如沸派撕。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,511評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽终吼。三九已至,卻和暖如春氯哮,著一層夾襖步出監(jiān)牢的瞬間际跪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,611評論 1 272
  • 我被黑心中介騙來泰國打工喉钢, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留姆打,地道東北人。 一個月前我還...
    沈念sama閱讀 49,081評論 3 377
  • 正文 我出身青樓肠虽,卻偏偏與公主長得像幔戏,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子舔痕,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,675評論 2 359

推薦閱讀更多精彩內(nèi)容