这里使用的是zookeeper和kafka3台机器的集群,这样能保证如过有一台机器炸了还能运行,在集群环境中,要在kafka的 server.properties中配置zookeeper集群地址等信息,消息设置三个分区,这样一个分区由一个机器管,所以当kafka发消息的时候就会发送到每个机器上。
如果是一个机器的话,就算多个分区数,那么日志文件还是会存放到一台机器上,还是能让消息实现分区保存。
虽然说这样依旧能实现多消费者的负载均衡(那所有消费者都是从收到消息的这台机器上拉取消息),但是集群设置有一个特点:容错性;这种情况在这台机器炸了之后就没办法运行了,更别说负载均衡了。
中央配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:config.properties</value>
</list>
</property>
</bean>
<import resource="kafka/consumer1.xml"/>
<import resource="kafka/consumer2.xml"/>
<import resource="kafka/producer.xml"/>
</beans>
消费者1:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 定义consumer的参数 -->
<bean id="consumerFactory1" class="org.springframework.kafka.core.Default