Spring boot 整合KAFKA消息队列的示例
这里使用spring-kafka依赖和KafkaTemplate对象来操作Kafka服务。
一、添加依赖和添加配置项
1.1、在Pom文件中添加依赖
org.springframework.kafka spring-kafka
1.2、添加配置项
spring: kafka: bootstrap-servers:12.168.3.62:9092#指定kafka代理地址,可以多个 producer: retries:2#写入失败时,重试次数。当retris为0时,produce不会重复。 batch-size:1000#每次批量发送消息的数量,produce积累到一定数据,一次发送 buffer-memory:33554432#produce积累数据一次发送,缓存大小达到buffer.memory就发送数据 acks:0#procedure要求leader在考虑完成请求之前收到的确认数,用于控制发送记录在服务端的持久化,如果设置为零,则生产者将不会等待来自服务器的任何确认。 key-serializer:org.apache.kafka.common.serialization.StringSerializer#指定消息key和消息体的编解码方式 value-serializer:org.apache.kafka.common.serialization.StringSerializer
二、代码编写
2.1、添加一个消息类
packagecom.jsh.mgt.kafkaTemplate.kafka; importjava.util.Date; importlombok.Data; /** *@since2020/5/2114:13 */ @Data publicclassMessage{ privateLongid;//id privateStringmsg;//消息 privateDatesendTime;//时间戳 }
2.2、设置消息生产者
packagecom.jsh.mgt.kafkaTemplate.Controllers; importcom.google.gson.Gson; importcom.google.gson.GsonBuilder; importcom.jsh.mgt.kafkaTemplate.kafka.Message; importjava.util.Date; importjava.util.UUID; importorg.springframework.beans.factory.annotation.Autowired; importorg.springframework.kafka.core.KafkaTemplate; importorg.springframework.web.bind.annotation.GetMapping; importorg.springframework.web.bind.annotation.PathVariable; importorg.springframework.web.bind.annotation.RestController; /** *@since2020/5/2111:19 */ @RestController publicclassKafkaController{ @Autowired privateKafkaTemplatekafkaTemplate; privateGsongson=newGsonBuilder().create(); @GetMapping("/kafka/{msg}") publicObjecttest(@PathVariable("msg")Stringmsg){ Messagemessage=newMessage(); message.setId(System.currentTimeMillis()); message.setMsg(UUID.randomUUID().toString()+"-"+msg); message.setSendTime(newDate()); kafkaTemplate.send("topic-create",gson.toJson(message)); return"ok"; } }
以上就是Springboot整合KAFKA消息队列的示例的详细内容,更多关于Springboot整合消息队列的资料请关注毛票票其它相关文章!
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。