记一次springboot和kafka的整合(kafka demo)
项目需要用到,所以今天试着整合一下,参考了许多资料做个demo。
注意:我的kafka和zookeeper都不是集群。
环境准备:
安装kafka前需要先装zookeeper。
zookeeper:
zookeeper修改 1 处:zookeeper下 conf/zoo-sample.cfg 需要修改为zoo.cfg 不然启动不了。
kafka:
kafka修改 1 处: kafka下 conf/server.properties 里将listeners=PLAINTEXT://192.168.132.131:9092 中ip部分修改为本机ip
/**
*注意:不要修改为127.0.0.1或是localhost,一定要是本机的ip 不然程序报错
*/
主要pom依赖:
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<!-- 继承父包 -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.10.RELEASE</version>
<relativePath></relativePath>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
</dependencies>
<!--maven的插件 -->
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
yml:
server:
port: 8080
spring:
kafka:
bootstrap-servers: 192.168.132.131:9092 #kafka config 集群用逗号隔开
producer: #生产者配置
acks: 1
retries: 0
batch-size: 16384 #每次批量发送消息的数量
buffer-memory: 33554432 #每次批量发送消息的数量
key-serializer: org.apache.kafka.common.serialization.StringSerializer #指定消息key和消息体的编解码方式
value-serializer: org.apache.kafka.common.serialization.StringSerializer
consumer: #消费者配置
group-id: helloDemo #组的id
auto-offset-reset: earliest
enable-auto-commit: true
auto-commit-interval: 100
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer #指定消息key和消息体的编解码方式
value-serializer: org.apache.kafka.common.serialization.StringDeserializer
producer:
@RestController
public class SendController {
private Logger logger = LoggerFactory.getLogger(SendController.class);
@Autowired
private KafkaTemplate<String, String> template;
@RequestMapping("/send")
public String sendMessage() {
logger.info("准备开始发送了哦!");
try {
//send(topic,message);
template.send("kafka-boot-topic","foo-woshimessage");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
}
consumer:
这里采用KafkaListener注解,监听topic
@Component
public class ConsumerListener {
private Logger logger = LoggerFactory.getLogger(ConsumerListener.class);
@KafkaListener(topics="kafka-boot-topic")
public void listen1(String foo) {
System.out.println(foo);
}
}
启动类:
@SpringBootApplication
public class KafkaApplication {
public static void main(String[] args) {
SpringApplication.run(KafkaApplication.class, args);
}
}
访问:
http://localhost:8080/send
控制台输出: