配置文件
<?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.xsd">
<context:property-placeholder location="classpath:properties/test.properties" />
<!-- 定义producer的参数 -->
<bean id="producerProperties" class="java.util.HashMap">
<constructor-arg>
<map>
<entry key="bootstrap.servers" value="172.0.0.1" />
<!-- 发送应答(0:收到后直接响应成功,1:leader保存则响应成功,-1/all:leader和isr列表保存后才响应成功)-->
<entry key="acks" value="-1" />
<!-- 失败重试次数-->
<entry key="retries" value="1" />
<!-- 请求超时时间-->
<entry key="request.timeout.ms" value="2000" />
<!-- K如果发送方buffer满或者获取不到元数据时最大阻塞时间,规范2000-->
<entry key="max.block.ms" value="2000" />
<!-- 发送每批消息大小,建议65536,单位bytes -->
<entry key="batch.size" value="65536" />
<!-- 批量发送等待时间,建议5,单位ms -->
<entry key="linger.ms" value="5" />
<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 bean="producerProperties" />
</constructor-arg>
</bean>
<!-- 自定义监听,实现org.springframework.kafka.support.ProducerListenerAdapter -->
<bean id="myProducerListener" class="com.xiao.zhen.SynchronizeProducerMessageListener" />
<!-- 创建kafkatemplate发送模版 -->
<bean id="myKafkaTemplate" class="org.springframework.kafka.core.KafkaTemplate">
<constructor-arg ref="producerFactory" />
<!-- utoFlush=false,异步发送kafka,防止kafka故障时阻塞业务线程 -->
<constructor-arg name="autoFlush" value="false" />
<!-- 队列名 -->
<property name="defaultTopic" value="topicname" />
<!-- 发送结果监听器 -->
<property name="producerListener" ref="myProducerListener" />
</bean>
java代码
/**
* kafkaTemplate
*/
@Autowired
private KafkaTemplate myKafkaTemplate;
try {
// 代码逻辑处理
......
// 发送kafka
myKafkaTemplate.setDefault(gson.toJson(msg));
} catch (Exception e) {
// 异常处理,可以把错误消息入表,后续重新发送
}
发送结果的监听器
@Service
public class SynchronizeProducerMessageListener extends ProducerListenerAdapter {
@Override
public void onSuccess(String topic, Integer partition, K key, V value, RecordMetadata recordMetadata) {
// 发送成功后处理
}
@Override
public void onError(String topic, Integer partition, K key, V value, Exception exception) {
// 发送失败后处理
}
@Override
public boolean isInterestedInSuccess() {
// true 开启监听,false 关闭监听
return false;
}
}