spring集成kafka例子链接地址:http://download.csdn.net/detail/qinyanbin123/8959339
使用spring-integration-kafka发送消息
Outbound Channel Adapter用来发送消息到Kafka。 消息从Spring Integration Channel中读取。 你可以在Spring application context指定这个channel。
一旦配置好这个Channel,就可以利用这个Channel往Kafka发消息。 明显地,Spring Integration特定的消息发送给这个Adaptor,然后发送前在内部被转为Kafka消息。当前的版本要求你必须指定消息key和topic作为头部数据 (header),消息作为有载荷(payload)。
例如
|
|
实际代码如下:
|
|
Spring 配置文件:
|
|
int:channel
是配置Spring Integration Channel, 此channel基于queue。
int-kafka:outbound-channel-adapter
是outbound-channel-adapter对象, 内部使用一个线程池处理消息。关键是kafka-producer-context-ref
。
int-kafka:producer-context
配置producer列表,要处理的topic,这些Producer最终要转换成Kafka的Producer。
producer的配置参数如下:
|
|
value-encoder 和key-encoder可以是其它实现了Kafka Encoder接口的Bean。同样partitioner也是实现了Kafka的Partitioner接口的Bean。
一个Encoder的例子:
|
|
Spring Integration Kafka 也提供了个基于Avro的Encoder。 Avro也是Apache的一个项目, 在大数据处理时也是一个常用的序列化框架。
不指定Encoder将使用Kafka缺省的Encoder (kafka.serializer.DefaultEncoder, byte[] --> same byte[])。
producerProperties
可以用来设置配置属性进行调优。配置属性列表请参考http://kafka.apache.org/documentation.html#producerconfigs
使用spring-integration-kafka接收消息
同样的原理实现一个消费者:
|
|
Spring的配置文件如下:
|
|
如果运行有timeout错误 改成10000。
这个配置和Producer类似, 同样声明一个channel, 定义inbound-channel-adapter
, 它引用Bean kafka-consumer-context
,
kafka-consumer-context
定义了消费者的列表。 consumer-configuration
还提供了topic-filter
,使用正则表达式建立白名单或者黑名单(exclude属性)。
消费者上下文还需要zookeeper-connect
。
由于spring-integration-kafka只实现了high level Consumer API,这也就意味着你不可能回滚重新查看以前的消息, 因为high level API不提供offset管理。
注意Channel中得到的有效负载的类型是:
Map<String, Map<Integer, List<Object>>>
,
这个Map的key是topic, 值还是另外的Map对象。
这个值Map的key值是分区号,value值是消息列表。 在本例中由于消息是字符串, 转换成了byte[]数组。
这种复杂的结构是由于Kafka的设计造成的。 Kafka保证对于同一个topic的同一个分区的消息是严格有序的。所有这种数据结构可以提供有序的消息。