1、pom.xml添加依赖

 <dependency>
<groupId>org.springframework.kafka</groupId>
<artifactId>spring-kafka</artifactId>
</dependency>
<dependency>
<groupId>com.typesafe</groupId>
<artifactId>config</artifactId>
<version>1.2.1</version>
</dependency>

2、创建配置文件

package com.youfan.config;

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; import java.util.HashMap;
import java.util.Map; @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<String, String>(producerConfigs());
} @Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<String, String>(producerFactory());
}
}

3、properties文件添加配置信息

                kafka.consumer.zookeeper.connect=192.168.227.129:2181
kafka.consumer.servers=192.168.227.129: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=192.168.227.129:9092
kafka.producer.retries=0
kafka.producer.batch.size=4096
kafka.producer.linger=1
kafka.producer.buffer.memory=40960

4、编写读取topic的配置文件

public class ReadProperties {
public final static Config config = ConfigFactory.load("kafka.properties");
public static String getKey(String key){
return config.getString(key).trim();
}
public static String getKey(String key,String filename){
Config config = ConfigFactory.load(filename);
return config.getString(key).trim();
}
}
//配置文件内容
//attentionProductLog=attentionProductLog
//buyCartProductLog=buyCartProductLog
//collectProductLog=collectProductLog
//scanProductLog=scanProductLog
 

5、使用kafka

package com.youfan.Control;

import com.alibaba.fastjson.JSONObject;
import com.youfan.entity.ResultMessage;
import com.youfan.log.AttentionProductLog;
import com.youfan.log.BuyCartProductLog;
import com.youfan.log.CollectProductLog;
import com.youfan.log.ScanProductLog;
import com.youfan.utils.ReadProperties;
import org.apache.commons.lang3.StringUtils;
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.RequestMethod;
import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest;
import java.util.Date; /**
*
*/
@RestController
@RequestMapping("infolog")
public class InfoInControl {
private final String attentionProductLogTopic = ReadProperties.getKey("attentionProductLog");
private final String buyCartProductLogTopic = ReadProperties.getKey("buyCartProductLog");
private final String collectProductLogTopic = ReadProperties.getKey("collectProductLog");
private final String scanProductLogTopic = ReadProperties.getKey("scanProductLog"); @Autowired
private KafkaTemplate<String, String> kafkaTemplate; @RequestMapping(value = "helloworld",method = RequestMethod.GET)
public String hellowolrd(HttpServletRequest req){
String ip =req.getRemoteAddr();
ResultMessage resultMessage = new ResultMessage();
resultMessage.setMessage("hello:"+ip);
resultMessage.setStatus("success");
String result = JSONObject.toJSONString(resultMessage);
return result;
} /**
* AttentionProductLog:{productid:productid....}
BuyCartProductLog:{productid:productid....}
CollectProductLog:{productid:productid....}
ScanProductLog:{productid:productid....}
* @param recevicelog
* @param req
* @return
*/
@RequestMapping(value = "receivelog",method = RequestMethod.POST)
public String hellowolrd(String recevicelog,HttpServletRequest req){
if(StringUtils.isBlank(recevicelog)){
return null;
}
String[] rearrays = recevicelog.split(":",2);
String classname = rearrays[0];
String data = rearrays[1];
String resulmesage= ""; if("AttentionProductLog".equals(classname)){
AttentionProductLog attentionProductLog = JSONObject.parseObject(data,AttentionProductLog.class);
resulmesage = JSONObject.toJSONString(attentionProductLog);
kafkaTemplate.send(attentionProductLogTopic,resulmesage+"##1##"+new Date().getTime());
}else if("BuyCartProductLog".equals(classname)){
BuyCartProductLog buyCartProductLog = JSONObject.parseObject(data,BuyCartProductLog.class);
resulmesage = JSONObject.toJSONString(buyCartProductLog);
kafkaTemplate.send(buyCartProductLogTopic,resulmesage+"##1##"+new Date().getTime());
}else if("CollectProductLog".equals(classname)){
CollectProductLog collectProductLog = JSONObject.parseObject(data,CollectProductLog.class);
resulmesage = JSONObject.toJSONString(collectProductLog);
kafkaTemplate.send(collectProductLogTopic,resulmesage+"##1##"+new Date().getTime());
}else if("ScanProductLog".equals(classname)){
ScanProductLog scanProductLog = JSONObject.parseObject(data,ScanProductLog.class);
resulmesage = JSONObject.toJSONString(scanProductLog);
kafkaTemplate.send(scanProductLogTopic,resulmesage+"##1##"+new Date().getTime());
}
ResultMessage resultMessage = new ResultMessage();
resultMessage.setMessage(resulmesage);
resultMessage.setStatus("success");
String result = JSONObject.toJSONString(resultMessage);
return result;
} }

kafka整合springboot的更多相关文章

  1. SpringBoot Kafka 整合集成 示例教程

    1.使用IDEA新建工程,创建工程 springboot-kafka-producer 工程pom.xml文件添加如下依赖: <!-- 添加 kafka 依赖 --> <depend ...

  2. 03篇ELK日志系统——升级版集群之ELK日志系统整合springboot项目

    [ 前言:整个ELK日志系统已经搭建好了,接下来的流程就是: springboot项目中的logback日志配置通过tcp传输,把springboot项目中所有日志数据传到————>logsta ...

  3. Windows平台整合SpringBoot+KAFKA_第1部分_环境配置部分

    项目需要,需要整合 SpringBoot+KAFKA 我调查了一下,发现Linux中,要先装zoomkeeper,再装KAFKA,如  https://blog.csdn.net/zhangcongy ...

  4. RabbitMQ从概念到使用、从Docker安装到RabbitMQ整合Springboot【1.5w字保姆级教学】

    @ 目录 一.前言 二.RabbitMQ作用 1. 异步处理 2. 应用解耦 3. 流量控制 三.RabbitMQ概念 1. RabbitMQ简介 2. 核心概念 四.JMS与AMQP比较 五.Rab ...

  5. flume与kafka整合

    flume与kafka整合 前提: flume安装和测试通过,可参考:http://www.cnblogs.com/rwxwsblog/p/5800300.html kafka安装和测试通过,可参考: ...

  6. 5 kafka整合storm

    本博文的主要内容有 .kafka整合storm   .storm-kafka工程  .storm + kafka的具体应用场景有哪些? 要想kafka整合storm,则必须要把这个storm-kafk ...

  7. 【转】Spark Streaming和Kafka整合开发指南

    基于Receivers的方法 这个方法使用了Receivers来接收数据.Receivers的实现使用到Kafka高层次的消费者API.对于所有的Receivers,接收到的数据将会保存在Spark ...

  8. 整合springboot(app后台框架搭建四)

    springboot可以说是为了适用SOA服务出现,一方面,极大的简便了配置,加速了开发速度:第二方面,也是一个嵌入式的web服务,通过jar包运行就是一个web服务: 还有提供了很多metric,i ...

  9. SparkStreaming+Kafka整合

    SparkStreaming+Kafka整合 1.需求 使用SparkStreaming,并且结合Kafka,获取实时道路交通拥堵情况信息. 2.目的 对监控点平均车速进行监控,可以实时获取交通拥堵情 ...

随机推荐

  1. 【异常】ssh无法登录验证,非root用户ssh本机无法成功

    1 自己搭建的是伪分布式环境,需要以非root用户启动Hadoop集群,之前root已经配置了ssh免密登录,但是自己切换到hdfs用户重新生成了一套ssh key, 但是切换到hdfs始终无法成功登 ...

  2. Django—logging日志

    简介 Django使用python自带的logging 作为日志打印工具.简单介绍下logging. logging 是线程安全的,其主要由4部分组成: Logger 用户使用的直接接口,将日志传递给 ...

  3. SQLSERVER EXISTS IN 优化

    数据量: 首先我们看看待优化的SQL: 简单的分析下来发现: EXISTS 这部分执行比较慢,我们来看一下, 这种写法比较便于理解,但是执行起来却很慢.既然这里慢,我们就要优化这部分. 首先我是想把拼 ...

  4. CentOS7 - Package does not match intended download 问题解决

    yum 安装软件,有时会出现 Error: Package does not match intended download,这时需要彻底清除已有的下载,然后重新安装即可. $ sudo yum cl ...

  5. 下划线文字,鼠标hover小样式

    CSS样式 //不只是a标签,其他有下划线的字体也可以 a:hover{ color: #ff3100; //这里的颜色是指字体颜色不是波浪下划线效果的svg图颜色     text-decorati ...

  6. myeclipse 关闭jsp悬浮提示

    myeclipse越来越智能,身为码农的我却越来越伤心.虽然你很智能,但请你提供一些有用的信息给我,不要乱七八槽的,不问青红皂白就塞一大堆提示给我,对不起,哥不需要这些!!! 都知道,使用myecli ...

  7. GPU Debugger

    https://gpuopen.com/presentations/2019/digital-dragons-2019-make-your-game-friendly.pdf https://grap ...

  8. STM32调试利器之ITM

    原创: Osprey  鱼鹰谈单片机 2月17日 STM32 有一个代码跟踪功能,即 ITM,这个调试功能非常强大,可以替代串口输入输出功能,而且只需要占用一根 I/O 线就可以实现.当然它的好处不仅 ...

  9. 简单了解学习PHP(针对前端开发)

    1.服务器(服务器系统) 通常是指较强的计算能力能够同时服务多人的计算机 常见的服务器操作系统: 1.各个版本的Linux操作系统 2.乌班图.centos 3.mac  os(苹果) 4.windo ...

  10. SQL Server text field里面有换行符的时候copy到excel数据会散乱

    解决方法: select '"'+convert(varchar(8000),testField)+'"'astestField from testTable 这样虽然结果集里面有 ...