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. 命令行工具--LLDP

    目录 命令行工具--LLDP 一.场景引入 二.什么是LLDP? 三.在CentOS上安装LLDP 四.命令详解 五.脚本 命令行工具--LLDP 一.场景引入 有的时候,我们需要知道服务器上联交换机 ...

  2. Image Processing and Computer Vision_Review:Recent Advances in Features Extraction and Description Algorithms: A Comprehensive Survey——2017.03

    翻译 特征提取和描述算法的最新进展:全面的调查 摘要 - 计算机视觉是当今信息技术中最活跃的研究领域之一.让机器和机器人能够以视线的速度看到和理解周围的世界,创造出无穷无尽的潜在应用和机会.特征检测和 ...

  3. sed交换任意两行

    命令: sed -n 'A{h;n;B!{:a;N;C!ba;x;H;n};x;H;x};p' 文件名 解释: A.B分别是需要交换的行,C是B-1 其中,A.B.C可以是行号,也可以通过匹配模式,如 ...

  4. Java中的集合(上):概述、Collection集合、List集合及其子类

    一.集合的体系结构 二.Collection集合 1.基本使用 如下代码 import java.util.ArrayList; import java.util.Collection; public ...

  5. 微信小程序开发(六)获取手机信息

    // succ.js var app = getApp() Page({ data: { mobileModel: '', // 手机型号 mobileePixelRatio: '', // 手机像素 ...

  6. 13_Redis_持久化

    一:概述: Redis的高性能是山于其将所有数据都存储在了内存中,为了使Redis在重启之后仍能保证数据不丢失,需要将数据从内存中同步到硬盘中,这一过程就是持久化. Redis支持两种方式的持久化,一 ...

  7. PMM 监控 MySQL 使用钉钉告警

    打开 PMM Server 页面,如图所示点进Alerting --> Notification channels 输入钉钉的信息,并且 Save Test 测试结果,没问题了 如何使用 gra ...

  8. tigervnc-server安装

    #vncserver安装方法 #su - root rpm -ivh tigervnc-server-1.8.0-13.el7.x86_64.rpm cp /lib/systemd/system/vn ...

  9. PAT Basic 1084 外观数列 (20 分)

    外观数列是指具有以下特点的整数序列: d, d1, d111, d113, d11231, d112213111, ... 它从不等于 1 的数字 d 开始,序列的第 n+1 项是对第 n 项的描述. ...

  10. python_函数作用域

    py文件:全局作用域 函数:局部作用域 一个函数是一个作用域 def func(): x = 9 print(x) func() print(x) 作用域中查找数据规则:优先在自己的作用域找数据,自己 ...