在web工程中发送kafka消息的时候,采用容器管理kafka的producer对象。
1.在web.xml中配置:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:forum/spring/mqproducer-service-impl.xml</param-value>
</context-param>
2.web.xml配置中mqproducer-service-impl.xml中的配置(bean):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- producer beans -->
<bean id="kafkaProducer"
class="com.huawei.jaguar.commons.mqclient.producer.impl.MQProducerImpl"
init-method="start" destroy-method="shutdown">
<property name="config"
value="classpath:/forum/common/kafka-producer.properties" />
</bean>
<bean id="kafkaMQEventPublisher" class="com.huawei.iread.forum.kafka.KafkaMQEventPublisher">
<property name="producer" ref="kafkaProducer"></property>
</bean>
</beans>
3.kafka-producer.properties的配置:
metadata.broker.list=10.211.95.9:9092
request.required.acks=0
serializer.class=kafka.serializer.StringEncoder
producer.type=async
metadata.fetch.timeout.ms=200
4.在java程序中获取bean对象:采用单例模式
KafkaMQEventPublisher kafkaMQEventPublisher =
(KafkaMQEventPublisher)ContextLoader.getCurrentWebApplicationContext().getBean("kafkaMQEventPublisher");