服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Springboot集成Kafka实现producer和consumer的示例代码

Springboot集成Kafka实现producer和consumer的示例代码

2021-05-05 10:47扎心了老铁 Java教程

这篇文章主要介绍了Springboot集成Kafka实现producer和consumer的示例代码,详细的介绍了什么是Kafka和安装Kafka以及在springboot项目中集成kafka收发message,感兴趣的小伙伴们可以参考一下

本文介绍如何在springboot项目中集成kafka收发message。

kafka是一种高吞吐量的分布式发布订阅消息系统,有如下特性: 通过o(1)的磁盘数据结构提供消息的持久化,这种结构对于即使数以tb的消息存储也能够保持长时间的稳定性能。高吞吐量:即使是非常普通的硬件kafka也可以支持每秒数百万的消息。支持通过kafka服务器和消费机集群来分区消息。支持hadoop并行数据加载。

安装kafka

因为安装kafka需要zookeeper的支持,所以windows安装时需要将zookeeper先安装上,然后将kafka安装好就可以了。 下面我给出mac安装的步骤以及需要注意的点吧,windows的配置除了所在位置不太一样其他几乎没什么不同。

?
1
brew install kafka

对,就是这么简单,mac上一个命令就可以搞定了,这个安装过程可能需要等一会儿,应该是和网络状况有关系。安装提示信息可能有错误消息,如"error: could not link: /usr/local/share/doc/homebrew" 这个没关系,自动忽略掉了。 最终我们看到下面的样子就成功咯。

==> summary 🍺/usr/local/cellar/kafka/1.1.0: 157 files, 47.8mb

安装的配置文件位置如下,根据自己的需要修改端口号什么的就可以了。

安装的zoopeeper和kafka的位置 /usr/local/cellar/

配置文件 /usr/local/etc/kafka/server.properties /usr/local/etc/kafka/zookeeper.properties

启动zookeeper

 

复制代码 代码如下:
./bin/zookeeper-server-start /usr/local/etc/kafka/zookeeper.properties &

启动kafka

 

./bin/kafka-server-start /usr/local/etc/kafka/server.properties &

为kafka创建topic,topic 名为test,可以配置成自己想要的名字,回头再代码中配置正确就可以了。

 

复制代码 代码如下:
./bin/kafka-topics --create --zookeeper localhost:2181 --replication-factor 1 --partitions 1 --topic test
 

 

1、先解决依赖

springboot相关的依赖我们就不提了,和kafka相关的只依赖一个spring-kafka集成包

?
1
2
3
4
5
<dependency>
   <groupid>org.springframework.kafka</groupid>
   <artifactid>spring-kafka</artifactid>
   <version>1.1.1.release</version>
  </dependency>

 这里我们先把配置文件展示一下

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#============== kafka ===================
kafka.consumer.zookeeper.connect=10.93.21.21:2181
kafka.consumer.servers=10.93.21.21:9092
kafka.consumer.enable.auto.commit=true
kafka.consumer.session.timeout=6000
kafka.consumer.auto.commit.interval=100
kafka.consumer.auto.offset.reset=latest
kafka.consumer.topic=test
kafka.consumer.group.id=test
kafka.consumer.concurrency=10
 
kafka.producer.servers=10.93.21.21:9092
kafka.producer.retries=0
kafka.producer.batch.size=4096
kafka.producer.linger=1
kafka.producer.buffer.memory=40960

2、configuration:kafka producer

1)通过@configuration、@enablekafka,声明config并且打开kafkatemplate能力。

2)通过@value注入application.properties配置文件中的kafka配置。

3)生成bean,@bean

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package com.kangaroo.sentinel.collect.configuration;
import java.util.hashmap;
import java.util.map;
import org.apache.kafka.clients.producer.producerconfig;
import org.apache.kafka.common.serialization.stringserializer;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.kafka.annotation.enablekafka;
import org.springframework.kafka.core.defaultkafkaproducerfactory;
import org.springframework.kafka.core.kafkatemplate;
import org.springframework.kafka.core.producerfactory;
 
@configuration
@enablekafka
public class kafkaproducerconfig {
 @value("${kafka.producer.servers}")
 private string servers;
 @value("${kafka.producer.retries}")
 private int retries;
 @value("${kafka.producer.batch.size}")
 private int batchsize;
 @value("${kafka.producer.linger}")
 private int linger;
 @value("${kafka.producer.buffer.memory}")
 private int buffermemory;
 
 public map<string, object> producerconfigs() {
  map<string, object> props = new hashmap<>();
  props.put(producerconfig.bootstrap_servers_config, servers);
  props.put(producerconfig.retries_config, retries);
  props.put(producerconfig.batch_size_config, batchsize);
  props.put(producerconfig.linger_ms_config, linger);
  props.put(producerconfig.buffer_memory_config, buffermemory);
  props.put(producerconfig.key_serializer_class_config, stringserializer.class);
  props.put(producerconfig.value_serializer_class_config, stringserializer.class);
  return props;
 }
 
 public producerfactory<string, string> producerfactory() {
  return new defaultkafkaproducerfactory<>(producerconfigs());
 }
 
 @bean
 public kafkatemplate<string, string> kafkatemplate() {
  return new kafkatemplate<string, string>(producerfactory());
 }
}

实验我们的producer,写一个controller。想topic=test,key=key,发送消息message

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
package com.kangaroo.sentinel.collect.controller;
import com.kangaroo.sentinel.common.response.response;
import com.kangaroo.sentinel.common.response.resultcode;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.beans.factory.annotation.autowired;
import org.springframework.kafka.core.kafkatemplate;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.httpservletrequest;
import javax.servlet.http.httpservletresponse;
 
@restcontroller
@requestmapping("/kafka")
public class collectcontroller {
 protected final logger logger = loggerfactory.getlogger(this.getclass());
 @autowired
 private kafkatemplate kafkatemplate;
 
 @requestmapping(value = "/send", method = requestmethod.get)
 public response sendkafka(httpservletrequest request, httpservletresponse response) {
  try {
   string message = request.getparameter("message");
   logger.info("kafka的消息={}", message);
   kafkatemplate.send("test", "key", message);
   logger.info("发送kafka成功.");
   return new response(resultcode.success, "发送kafka成功", null);
  } catch (exception e) {
   logger.error("发送kafka失败", e);
   return new response(resultcode.exception, "发送kafka失败", null);
  }
 }
}

3、configuration:kafka consumer

1)通过@configuration、@enablekafka,声明config并且打开kafkatemplate能力。

2)通过@value注入application.properties配置文件中的kafka配置。

3)生成bean,@bean

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.kangaroo.sentinel.collect.configuration;
import org.apache.kafka.clients.consumer.consumerconfig;
import org.apache.kafka.common.serialization.stringdeserializer;
import org.springframework.beans.factory.annotation.value;
import org.springframework.context.annotation.bean;
import org.springframework.context.annotation.configuration;
import org.springframework.kafka.annotation.enablekafka;
import org.springframework.kafka.config.concurrentkafkalistenercontainerfactory;
import org.springframework.kafka.config.kafkalistenercontainerfactory;
import org.springframework.kafka.core.consumerfactory;
import org.springframework.kafka.core.defaultkafkaconsumerfactory;
import org.springframework.kafka.listener.concurrentmessagelistenercontainer;
import java.util.hashmap;
import java.util.map;
@configuration
@enablekafka
public class kafkaconsumerconfig {
 @value("${kafka.consumer.servers}")
 private string servers;
 @value("${kafka.consumer.enable.auto.commit}")
 private boolean enableautocommit;
 @value("${kafka.consumer.session.timeout}")
 private string sessiontimeout;
 @value("${kafka.consumer.auto.commit.interval}")
 private string autocommitinterval;
 @value("${kafka.consumer.group.id}")
 private string groupid;
 @value("${kafka.consumer.auto.offset.reset}")
 private string autooffsetreset;
 @value("${kafka.consumer.concurrency}")
 private int concurrency;
 @bean
 public kafkalistenercontainerfactory<concurrentmessagelistenercontainer<string, string>> kafkalistenercontainerfactory() {
  concurrentkafkalistenercontainerfactory<string, string> factory = new concurrentkafkalistenercontainerfactory<>();
  factory.setconsumerfactory(consumerfactory());
  factory.setconcurrency(concurrency);
  factory.getcontainerproperties().setpolltimeout(1500);
  return factory;
 }
 
 public consumerfactory<string, string> consumerfactory() {
  return new defaultkafkaconsumerfactory<>(consumerconfigs());
 }
 
 public map<string, object> consumerconfigs() {
  map<string, object> propsmap = new hashmap<>();
  propsmap.put(consumerconfig.bootstrap_servers_config, servers);
  propsmap.put(consumerconfig.enable_auto_commit_config, enableautocommit);
  propsmap.put(consumerconfig.auto_commit_interval_ms_config, autocommitinterval);
  propsmap.put(consumerconfig.session_timeout_ms_config, sessiontimeout);
  propsmap.put(consumerconfig.key_deserializer_class_config, stringdeserializer.class);
  propsmap.put(consumerconfig.value_deserializer_class_config, stringdeserializer.class);
  propsmap.put(consumerconfig.group_id_config, groupid);
  propsmap.put(consumerconfig.auto_offset_reset_config, autooffsetreset);
  return propsmap;
 }
 
 @bean
 public listener listener() {
  return new listener();
 }
}

new listener()生成一个bean用来处理从kafka读取的数据。listener简单的实现demo如下:只是简单的读取并打印key和message值

@kafkalistener中topics属性用于指定kafka topic名称,topic名称由消息生产者指定,也就是由kafkatemplate在发送消息时指定。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.kangaroo.sentinel.collect.configuration;
import org.apache.kafka.clients.consumer.consumerrecord;
import org.slf4j.logger;
import org.slf4j.loggerfactory;
import org.springframework.kafka.annotation.kafkalistener;
 
public class listener {
 protected final logger logger = loggerfactory.getlogger(this.getclass());
 
 
 @kafkalistener(topics = {"test"})
 public void listen(consumerrecord<?, ?> record) {
  logger.info("kafka的key: " + record.key());
  logger.info("kafka的value: " + record.value().tostring());
 }
}

tips:

1)我没有介绍如何安装配置kafka,配置kafka时最好用完全bind网络ip的方式,而不是localhost或者127.0.0.1

2)最好不要使用kafka自带的zookeeper部署kafka,可能导致访问不通。

3)理论上consumer读取kafka应该是通过zookeeper,但是这里我们用的是kafkaserver的地址,为什么没有深究。

4)定义监听消息配置时,group_id_config配置项的值用于指定消费者组的名称,如果同组中存在多个监听器对象则只有一个监听器对象能收到消息。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/kangoroo/p/7353330.html

延伸 · 阅读

精彩推荐