spring boot集成kafka,注意要先安装kafka和zookeeper
先导入spring-kafka的jar maven配置如下:
<!--kafka客户端需要和kafka的jar版本对应 这里使用的是0.9版本的客户端-->
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
<version>1.0.6.RELEASE</version>
</dependency>
application.properties配置如下:
spring.kafka.bootstrap-servers=127.0.0.1:9092
spring.kafka.producer.acks=all
spring.kafka.consumer.enable-auto-commit=false
spring.kafka.producer.key-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer=org.apache.kafka.common.serialization.StringSerializer
spring.kafka.consumer.key-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer=org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.group-id=test2
package com.zyc.zspringboot.kafka;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Component;
/**
* @author zyc-admin
* @data 2018-03-29 11:14
**/
@Component
public class MyKafkaConsumer {
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
@KafkaListener(topics = {"my-topic"})
public void consumer(String message){
System.out.printf("打印message消息{%s}",message);
System.out.println();
}
public void send(String message){
kafkaTemplate.send("my-topic",String.valueOf(1),message);
}
}
测试类如下:
package com.zyc.zspringboot.kafka;
import com.zyc.zspringboot.ProfilesResolver;
import com.zyc.zspringboot.ZspringbootApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @author zyc-admin
* @data 2018-03-29 11:26
**/
@RunWith(SpringRunner.class)
@SpringBootTest(classes = {ZspringbootApplication.class})
public class KafkaTest {
@Autowired
private MyKafkaConsumer myKafkaConsumer;
@Test
public void send() {
for (int i = 0; i < 10; i++) {
myKafkaConsumer.send("data" + i);
}
while (true) {
}
}
}