springboot 集成kafka系列 二、springboot集成kafka生产者

 

 

1、新建springboot脚手架工程,pom文件如下,其中引入了kafka需要的依赖,注意这里的kafka版本号需要和之前安装的kafka版本一致,要不然会有问题



	4.0.0

	com.zeshan
	kafka-producer
	0.0.1-SNAPSHOT
	jar

	kafka-producer
	kafka集成

	
		org.springframework.boot
		spring-boot-starter-parent
		2.0.2.RELEASE
		
	

	
		UTF-8
		UTF-8
		1.8
	

	
		
			org.springframework.boot
			spring-boot-starter-web
		
		
			org.springframework.kafka
			spring-kafka
			2.1.10.RELEASE
		

		
			org.springframework.boot
			spring-boot-starter-test
			test
		
	
	
		
			
				org.springframework.boot
				spring-boot-maven-plugin
			
		
	

2、在application.properties中配置producer基本信息

kafka.producer.servers=127.0.0.1:9092
kafka.producer.retries=0
kafka.producer.batch.size=4096
kafka.producer.linger=1
kafka.producer.buffer.memory=40960

3.编写ProducerController

 

package com.zeshan.kafka;

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.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("kafka-producer")
public class ProducerController {
    @Autowired
    private  KafkaTemplate kafkaTemplate;
    @RequestMapping("send")
    @ResponseBody
    public String  sengMessage(HttpServletRequest request, HttpServletResponse response){
        String message = request.getParameter("message");
        try {
            kafkaTemplate.send("demo",message);
            return "success";
        }catch (Exception e){
            e.printStackTrace();
            return  "error";
        }
    }
}

4.启动项目,访问 http://127.0.0.1:6060/kafka-producer/send?message=hello kafka,访问结果如下

springboot 集成kafka系列 二、springboot集成kafka生产者_第1张图片

 

通过观察我们发送的消息已经被consumer消费,至此springboot集成kafka producer成功。

项目源码地址  https://gitee.com/yanfaze/kafka

下一篇文件会介绍springboot 集成kafka consumer,比克https://blog.csdn.net/yfz792178428/article/details/83415004

 

 

你可能感兴趣的:(Java)