最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot整合Kafka工具類的詳細代碼

 更新時間:2022年09月26日 16:29:47   作者:鍵盤命  
Kafka是一種高吞吐量的分布式發(fā)布訂閱消息系統(tǒng),它可以處理消費者在網站中的所有動作流數(shù)據(jù),這篇文章主要介紹了SpringBoot整合Kafka工具類的代碼詳解,需要的朋友可以參考下

kafka是什么?

Kafka是由Apache軟件基金會開發(fā)的一個開源流處理平臺,由Scala和Java編寫。Kafka是一種高吞吐量的分布式發(fā)布訂閱消息系統(tǒng),它可以處理消費者在網站中的所有動作流數(shù)據(jù)。 這種動作(網頁瀏覽,搜索和其他用戶的行動)是在現(xiàn)代網絡上的許多社會功能的一個關鍵因素。 這些數(shù)據(jù)通常是由于吞吐量的要求而通過處理日志和日志聚合來解決。 對于像Hadoop一樣的日志數(shù)據(jù)和離線分析系統(tǒng),但又要求實時處理的限制,這是一個可行的解決方案。Kafka的目的是通過Hadoop的并行加載機制來統(tǒng)一線上和離線的消息處理,也是為了通過集群來提供實時的消息。

應用場景

  • 消息系統(tǒng): Kafka 和傳統(tǒng)的消息系統(tǒng)(也稱作消息中間件)都具備系統(tǒng)解耦、冗余存儲、流量削峰、緩沖、異步通信、擴展性、可恢復性等功能。與此同時,Kafka 還提供了大多數(shù)消息系統(tǒng)難以實現(xiàn)的消息順序性保障及回溯消費的功能。
  • 存儲系統(tǒng): Kafka 把消息持久化到磁盤,相比于其他基于內存存儲的系統(tǒng)而言,有效地降低了數(shù)據(jù)丟失的風險。也正是得益于 Kafka 的消息持久化功能和多副本機制,我們可以把 Kafka 作為長期的數(shù)據(jù)存儲系統(tǒng)來使用,只需要把對應的數(shù)據(jù)保留策略設置為“永久”或啟用主題的日志壓縮功能即可。
  • 流式處理平臺: Kafka 不僅為每個流行的流式處理框架提供了可靠的數(shù)據(jù)來源,還提供了一個完整的流式處理類庫,比如窗口、連接、變換和聚合等各類操作。

下面看下SpringBoot整合Kafka工具類的詳細代碼。

pom.xml

 <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.kafka</groupId>
            <artifactId>kafka-clients</artifactId>
            <version>2.6.3</version>
        </dependency>
        <dependency>
            <groupId>fastjson</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.83</version>
        </dependency>    

工具類

package com.bbl.demo.utils;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.kafka.clients.admin.*;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.KafkaFuture;
import org.apache.kafka.common.errors.TopicExistsException;
import org.apache.kafka.common.errors.UnknownTopicOrPartitionException;
import com.alibaba.fastjson.JSONObject;

import java.time.Duration;
import java.util.*;
import java.util.concurrent.ExecutionException;


public class KafkaUtils {
    private static AdminClient admin;
    /**
     * 私有靜態(tài)方法,創(chuàng)建Kafka生產者
     * @author o
     * @return KafkaProducer
     */
    private static KafkaProducer<String, String> createProducer() {
        Properties props = new Properties();
        //聲明kafka的地址
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"node01:9092,node02:9092,node03:9092");
        //0、1 和 all:0表示只要把消息發(fā)送出去就返回成功;1表示只要Leader收到消息就返回成功;all表示所有副本都寫入數(shù)據(jù)成功才算成功
        props.put("acks", "all");
        //重試次數(shù)
        props.put("retries", Integer.MAX_VALUE);
        //批處理的字節(jié)數(shù)
        props.put("batch.size", 16384);
        //批處理的延遲時間,當批次數(shù)據(jù)未滿之時等待的時間
        props.put("linger.ms", 1);
        //用來約束KafkaProducer能夠使用的內存緩沖的大小的,默認值32MB
        props.put("buffer.memory", 33554432);
        // properties.put("value.serializer",
        // "org.apache.kafka.common.serialization.ByteArraySerializer");
        // properties.put("key.serializer",
        // "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
        return new KafkaProducer<String, String>(props);
    }

    /**
     * 私有靜態(tài)方法,創(chuàng)建Kafka消費者
     * @author o
     * @return KafkaConsumer
     */
    private static KafkaConsumer<String, String> createConsumer() {
        Properties props = new Properties();
        //聲明kafka的地址
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG,"node01:9092,node02:9092,node03:9092");
        //每個消費者分配獨立的消費者組編號
        props.put("group.id", "111");
        //如果value合法,則自動提交偏移量
        props.put("enable.auto.commit", "true");
        //設置多久一次更新被消費消息的偏移量
        props.put("auto.commit.interval.ms", "1000");
        //設置會話響應的時間,超過這個時間kafka可以選擇放棄消費或者消費下一條消息
        props.put("session.timeout.ms", "30000");
        //自動重置offset
        props.put("auto.offset.reset","earliest");
        // properties.put("value.serializer",
        // "org.apache.kafka.common.serialization.ByteArraySerializer");
        // properties.put("key.serializer",
        // "org.apache.kafka.common.serialization.ByteArraySerializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        return new KafkaConsumer<String, String>(props);
    }
    /**
     * 私有靜態(tài)方法,創(chuàng)建Kafka集群管理員對象
     * @author o
     */
    public static void createAdmin(String servers){
        Properties props = new Properties();
        props.put(AdminClientConfig.BOOTSTRAP_SERVERS_CONFIG,servers);
        admin = AdminClient.create(props);
    }

    /**
     * 私有靜態(tài)方法,創(chuàng)建Kafka集群管理員對象
     * @author o
     * @return AdminClient
     */
    private static void createAdmin(){
        createAdmin("node01:9092,node02:9092,node03:9092");
    }

    /**
     * 傳入kafka約定的topic,json格式字符串,發(fā)送給kafka集群
     * @author o
     * @param topic
     * @param jsonMessage
     */
    public static void sendMessage(String topic, String jsonMessage) {
        KafkaProducer<String, String> producer = createProducer();
        producer.send(new ProducerRecord<String, String>(topic, jsonMessage));
        producer.close();
    }

    /**
     * 傳入kafka約定的topic消費數(shù)據(jù),用于測試,數(shù)據(jù)最終會輸出到控制臺上
     * @author o
     * @param topic
     */
    public static void consume(String topic) {
        KafkaConsumer<String, String> consumer = createConsumer();
        consumer.subscribe(Arrays.asList(topic));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(100));
            for (ConsumerRecord<String, String> record : records){
                System.out.printf("offset = %d, key = %s, value = %s",record.offset(), record.key(), record.value());
                System.out.println();
            }
        }
    }
    /**
     * 傳入kafka約定的topic數(shù)組,消費數(shù)據(jù)
     * @author o
     * @param topics
     */
    public static void consume(String ... topics) {
        KafkaConsumer<String, String> consumer = createConsumer();
        consumer.subscribe(Arrays.asList(topics));
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofSeconds(100));
            for (ConsumerRecord<String, String> record : records){
                System.out.printf("offset = %d, key = %s, value = %s",record.offset(), record.key(), record.value());
                System.out.println();
            }
        }
    }
    /**
     * 傳入kafka約定的topic,json格式字符串數(shù)組,發(fā)送給kafka集群
     * 用于批量發(fā)送消息,性能較高。
     * @author o
     * @param topic
     * @param jsonMessages
     * @throws InterruptedException
     */
    public static void sendMessage(String topic, String... jsonMessages) throws InterruptedException {
        KafkaProducer<String, String> producer = createProducer();
        for (String jsonMessage : jsonMessages) {
            producer.send(new ProducerRecord<String, String>(topic, jsonMessage));
        }
        producer.close();
    }

    /**
     * 傳入kafka約定的topic,Map集合,內部轉為json發(fā)送給kafka集群 <br>
     * 用于批量發(fā)送消息,性能較高。
     * @author o
     * @param topic
     * @param mapMessageToJSONForArray
     */
    public static void sendMessage(String topic, List<Map<Object, Object>> mapMessageToJSONForArray) {
        KafkaProducer<String, String> producer = createProducer();
        for (Map<Object, Object> mapMessageToJSON : mapMessageToJSONForArray) {
            String array = JSONObject.toJSON(mapMessageToJSON).toString();
            producer.send(new ProducerRecord<String, String>(topic, array));
        }
        producer.close();
    }

    /**
     * 傳入kafka約定的topic,Map,內部轉為json發(fā)送給kafka集群
     * @author o
     * @param topic
     * @param mapMessageToJSON
     */
    public static void sendMessage(String topic, Map<Object, Object> mapMessageToJSON) {
        KafkaProducer<String, String> producer = createProducer();
        String array = JSONObject.toJSON(mapMessageToJSON).toString();
        producer.send(new ProducerRecord<String, String>(topic, array));
        producer.close();
    }

    /**
     * 創(chuàng)建主題
     * @author o
     * @param name 主題的名稱
     * @param numPartitions 主題的分區(qū)數(shù)
     * @param replicationFactor 主題的每個分區(qū)的副本因子
     */
    public static void createTopic(String name,int numPartitions,int replicationFactor){
        if(admin == null) {
            createAdmin();
        }
        Map<String, String> configs = new HashMap<>();
        CreateTopicsResult result = admin.createTopics(Arrays.asList(new NewTopic(name, numPartitions, (short) replicationFactor).configs(configs)));
        //以下內容用于判斷創(chuàng)建主題的結果
        for (Map.Entry<String, KafkaFuture<Void>> entry : result.values().entrySet()) {
            try {
                entry.getValue().get();
                System.out.println("topic "+entry.getKey()+" created");
            } catch (InterruptedException | ExecutionException e) {
                if (ExceptionUtils.getRootCause(e) instanceof TopicExistsException) {
                    System.out.println("topic "+entry.getKey()+" existed");
                }
            }
        }
    }

    /**
     * 刪除主題
     * @author o
     * @param names 主題的名稱
     */
    public static void deleteTopic(String name,String ... names){
        if(admin == null) {
            createAdmin();
        }
        Map<String, String> configs = new HashMap<>();
        Collection<String> topics = Arrays.asList(names);
        topics.add(name);
        DeleteTopicsResult result = admin.deleteTopics(topics);
        //以下內容用于判斷刪除主題的結果
        for (Map.Entry<String, KafkaFuture<Void>> entry : result.values().entrySet()) {
            try {
                entry.getValue().get();
                System.out.println("topic "+entry.getKey()+" deleted");
            } catch (InterruptedException | ExecutionException e) {
                if (ExceptionUtils.getRootCause(e) instanceof UnknownTopicOrPartitionException) {
                    System.out.println("topic "+entry.getKey()+" not exist");
                }
            }
        }
    }
    /**
     * 查看主題詳情
     * @author o
     * @param names 主題的名稱
     */
    public static void describeTopic(String name,String ... names){
        if(admin == null) {
            createAdmin();
        }
        Map<String, String> configs = new HashMap<>();
        Collection<String> topics = Arrays.asList(names);
        topics.add(name);
        DescribeTopicsResult result = admin.describeTopics(topics);
        //以下內容用于顯示主題詳情的結果
        for (Map.Entry<String, KafkaFuture<TopicDescription>> entry : result.values().entrySet()) {
            try {
                entry.getValue().get();
                System.out.println("topic "+entry.getKey()+" describe");
                System.out.println("\t name: "+entry.getValue().get().name());
                System.out.println("\t partitions: ");
                entry.getValue().get().partitions().stream().forEach(p-> {
                    System.out.println("\t\t index: "+p.partition());
                    System.out.println("\t\t\t leader: "+p.leader());
                    System.out.println("\t\t\t replicas: "+p.replicas());
                    System.out.println("\t\t\t isr: "+p.isr());
                });
                System.out.println("\t internal: "+entry.getValue().get().isInternal());
            } catch (InterruptedException | ExecutionException e) {
                if (ExceptionUtils.getRootCause(e) instanceof UnknownTopicOrPartitionException) {
                    System.out.println("topic "+entry.getKey()+" not exist");
                }
            }
        }
    }

    /**
     * 查看主題列表
     * @author o
     * @return Set<String> TopicList
     */
    public static Set<String> listTopic(){
        if(admin == null) {
            createAdmin();
        }
        ListTopicsResult result = admin.listTopics();
        try {
            result.names().get().stream().map(x->x+"\t").forEach(System.out::print);
            return result.names().get();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        System.out.println(listTopic());
    }
}

到此這篇關于SpringBoot整合Kafka工具類的文章就介紹到這了,更多相關SpringBoot整合Kafka工具類內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • java字符串的大寫字母右移實現(xiàn)方法

    java字符串的大寫字母右移實現(xiàn)方法

    下面小編就為大家?guī)硪黄猨ava字符串的大寫字母右移實現(xiàn)方法。小編覺得聽不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-04-04
  • spring?boot如何配置靜態(tài)路徑詳解(404出現(xiàn)的坑)

    spring?boot如何配置靜態(tài)路徑詳解(404出現(xiàn)的坑)

    這篇文章主要給大家介紹了關于spring?boot如何配置靜態(tài)路徑的相關資料,文中通過實例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2022-02-02
  • Java自定義實現(xiàn)equals()方法過程解析

    Java自定義實現(xiàn)equals()方法過程解析

    這篇文章主要介紹了Java自定義實現(xiàn)equals()方法過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-02-02
  • SpringBoot使用Feign調用其他服務接口

    SpringBoot使用Feign調用其他服務接口

    這篇文章主要介紹了SpringBoot使用Feign調用其他服務接口,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-03-03
  • SpringCloud中Eureka的配置及使用講解

    SpringCloud中Eureka的配置及使用講解

    Eureka?服務注冊中心,主要用于提供服務注冊功能,當微服務啟動時,會將自己的服務注冊到?Eureka?Server,這篇文章主要介紹了SpringCloud中Eureka的配置及詳細使用,需要的朋友可以參考下
    2023-01-01
  • Spring cloud gateway設置context-path服務路由404排查過程

    Spring cloud gateway設置context-path服務路由404排查過程

    這篇文章主要介紹了Spring cloud gateway設置context-path服務路由404排查過程,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-08-08
  • Java Swing JProgressBar進度條的實現(xiàn)示例

    Java Swing JProgressBar進度條的實現(xiàn)示例

    這篇文章主要介紹了Java Swing JProgressBar進度條的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2019-12-12
  • 淺談Springboot下引入mybatis遇到的坑點

    淺談Springboot下引入mybatis遇到的坑點

    這篇文章主要介紹了Springboot下引入mybatis遇到的坑點,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • 三種SpringBoot中實現(xiàn)異步調用的方法總結

    三種SpringBoot中實現(xiàn)異步調用的方法總結

    Spring Boot 提供了多種方式來實現(xiàn)異步任務,這篇文章主要為大家介紹了常用的三種實現(xiàn)方式,文中的示例代碼講解詳細,需要的可以參考一下
    2023-05-05
  • java swing實現(xiàn)QQ賬號密碼輸入框

    java swing實現(xiàn)QQ賬號密碼輸入框

    這篇文章主要為大家詳細介紹了Java swing實現(xiàn)QQ賬號密碼輸入框,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-06-06

最新評論

集贤县| 阳春市| 台南市| 县级市| 云南省| 子长县| 合江县| 开封县| 南安市| 宜州市| 山西省| 西乌珠穆沁旗| 陇川县| 郁南县| 山阳县| 阜阳市| 孟津县| 宜章县| 博罗县| 常德市| 海阳市| 桂林市| 十堰市| 聊城市| 集贤县| 梅河口市| 宁国市| 三门峡市| 扬州市| 佳木斯市| 清河县| 达州市| 思茅市| 霍城县| 禄丰县| 东乡县| 凉城县| 康马县| 古田县| 拜城县| 钟祥市|