spring整合kafka

來源:互聯網
上載者:User

標籤:pid   cto   stream   pack   AC   文檔   contain   回調   儲存   

主要參考spring開源項目: Spring for Apache Kafka

此處主要介紹consumer和peoducer的使用,其他如connector、stream等,可查閱官網文檔,開發時需注意個主鍵版本相容性,此處我spring版本為

<spring.version>4.3.13.RELEASE</spring.version>

 

首先pom檔案添加kafka相關jar:

<!--spring for kafka--><dependency>    <groupId>org.springframework.kafka</groupId>    <artifactId>spring-kafka</artifactId>    <version>2.1.6.RELEASE</version></dependency>

 

接下來示範如何消費kafka中的訊息:

首先編寫消費者監聽器類KafkaConsumerListen.java(回調方法無consumer執行個體):

package com.yinz.kafka;import org.apache.kafka.clients.consumer.ConsumerRecord;import org.springframework.kafka.listener.MessageListener;public class KafkaConsumerListen implements MessageListener<String, String>{    @Override    public void onMessage(ConsumerRecord<String, String> data) {        System.out.println("--------------" + data.value());    }}

KafkaConcurConsumerListen.java(回調方法有consumer執行個體):

package com.yinz.kafka;import org.apache.kafka.clients.consumer.Consumer;import org.apache.kafka.clients.consumer.ConsumerRecord;import org.springframework.kafka.listener.ConsumerAwareMessageListener;public class KafkaConcurConsumerListen implements ConsumerAwareMessageListener<String, String>{    @Override    public void onMessage(ConsumerRecord<String, String> data, Consumer<?, ?> consumer) {        System.out.println(consumer.hashCode() +">>>>>>" + data.partition() +">>>>>>>>>>" + data.value());    }}

 

接下來配置相關bean,此處我kafka相關配置均在kafka.xml中:

kafka.xml檔案內容如下(包含了單個消費者和並發消費者兩種情況,實際使用時配置一種即可):

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">    <!-- 定義生產者類 -->     <!-- 定義producer的參數 -->    <bean id="producerProperties" class="java.util.HashMap">        <constructor-arg>            <map>                <entry key="bootstrap.servers" value="47.98.131.199:9092" />                <entry key="retries" value="1" />              <!-- 訊息發送失敗,重試次數 -->                <entry key="batch.size" value="16384" />       <!-- 訊息打包發送,大小不能超過該值 -->                <entry key="linger.ms" value="1" />            <!-- 訊息發送前,延遲該毫秒,當負載較重是,可減少發送請求的次數,即打包一次發送多條訊息 -->                <entry key="buffer.memory" value="33554432" />  <!-- 生產者緩衝區大小,用於儲存還未發送到broker中的訊息,超過該值會等待,再後面會拋一次 -->                <entry key="key.serializer" value="org.apache.kafka.common.serialization.StringSerializer" />                <entry key="value.serializer"  value="org.apache.kafka.common.serialization.StringSerializer" />            </map>        </constructor-arg>    </bean>        <!-- 建立kafkatemplate需要使用的producerfactory bean -->    <bean id="producerFactory" class="org.springframework.kafka.core.DefaultKafkaProducerFactory">        <constructor-arg ref="producerProperties"></constructor-arg>    </bean>    <bean id="kafkaTemplate" class="org.springframework.kafka.core.KafkaTemplate">        <constructor-arg ref="producerFactory" />        <constructor-arg name="autoFlush" value="false" />  <!-- true 會顯著降低效能 -->        <property name="defaultTopic" value="test" />    <!-- 預設topic -->    </bean>        <!-- 定義consumer的參數 -->    <bean id="consumerProperties" class="java.util.HashMap">        <constructor-arg>            <map>                <entry key="bootstrap.servers" value="47.98.131.199:9092" />                <entry key="group.id" value="0" />        <!-- consumer group id -->                <entry key="enable.auto.commit" value="false" />  <!-- 不自動認可offset -->                <entry key="auto.commit.interval.ms" value="1000" />  <!-- 定期提交offset時間間隔 -->                <entry key="session.timeout.ms" value="15000" />  <!-- 15秒沒發生心跳意味著改consumer失效 -->                <entry key="key.deserializer"                    value="org.apache.kafka.common.serialization.StringDeserializer" />                <entry key="value.deserializer"                    value="org.apache.kafka.common.serialization.StringDeserializer" />            </map>        </constructor-arg>    </bean>        <!-- 建立consumerFactory bean -->    <bean id="consumerFactory"        class="org.springframework.kafka.core.DefaultKafkaConsumerFactory">        <constructor-arg>            <ref bean="consumerProperties" />        </constructor-arg>    </bean>    <!-- 實際執行訊息消費的類,回調方法中無consumer執行個體  -->    <!-- 
<bean id="messageListernerConsumerService" class="com.yinz.kafka.KafkaConsumerListen" /> <!-- 消費者容器配置資訊 --> <bean id="containerProperties" class="org.springframework.kafka.listener.config.ContainerProperties"> <constructor-arg value="test"/> <property name="messageListener" ref="messageListernerConsumerService"/> </bean> <!-- 同一group中配置單個消費者,消費者只有一個,不能達到負載均攤和容災 --> <bean id="messageListenerContainer" class="org.springframework.kafka.listener.KafkaMessageListenerContainer" init-method="doStart"> <constructor-arg ref="consumerFactory"/> <constructor-arg ref="containerProperties"/> </bean>
--> <!-- 實際執行訊息消費的類, 回調方法中有consumer執行個體 --> <bean id="messageConcurListernerConsumerService" class="com.yinz.kafka.KafkaConcurConsumerListen" /> <bean id="containerConcurProperties" class="org.springframework.kafka.listener.config.ContainerProperties"> <constructor-arg value="test-par"/> <property name="messageListener" ref="messageConcurListernerConsumerService"/> </bean> <!-- 同一group中配置concurrency個消費者, 可達到負載均攤和容災, 若concurrency 大於top分區數,會自動降級 --> <bean id="messageConcurListenerContainer" class="org.springframework.kafka.listener.ConcurrentMessageListenerContainer" init-method="doStart"> <constructor-arg ref="consumerFactory"/> <constructor-arg ref="containerConcurProperties"/> <property name="concurrency" value="3"></property> </bean></beans>

 

生產者比較簡單,只需注入kafkaTemplate bean,調用他的send方法發送訊息即可。

 

spring整合kafka

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.