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. shiro系列二、身份验证和授权

    一.身份验证 先来看看身份验证的流程 流程如下: 1.首先调用Subject.login(token)进行登录,其会自动委托给Security Manager,调用之前必须通过SecurityUtil ...

  2. web开发:web前端初识

    一.前端三剑客 二.编辑器 三.第一个页面 四.基本标签 五.标签分类 一.前端三剑客 html:完成页面架构的搭建 css:完成页面样式布局 js:完成页面功能 二.编辑器 插件: 插件管理器 ct ...

  3. Django_01_创建图书管理项目

    在django中,项目的组织结构为一个项目包含多个应用,一个应用对应一个业务模块 示例:创建项目的名称为test1,完成“图书-英雄”信息的维护,创建应用名称为booktest 创建项目:首先进入到虚 ...

  4. Git---初入开源代码管理库的学习过程003

    Git常用命令总结 上接<Git 初入开源代码管理库的学习过程>学了一周Git,基本有了个认识.每一位比我厉害的,都是大牛,网上找了几篇博客和教材(感谢你们),边学习边实践用了四天,写笔记 ...

  5. BZOJ2140 稳定婚姻[强连通分量]

    发现如果$B_i$和$G_j$配对,那么$B_j$又要找一个$G_k$配对,$B_k$又要找一个$G_l$配对,一直到某一个$B_x$和$G_i$配对上为止,才是不稳定的. 暴力是二分图匹配.匈牙利算 ...

  6. sysbench库文件路径不对

    #sysbench --versionsysbench: error while loading shared libraries: libmysqlclient.so .20: cannot ope ...

  7. Mysql-sql行转列

    原始数据如下图所示:(商品的销售明细)date=业务日期:Item=商品名称:saleqty=销售数量 -- 建立测试数据(表)create table test (Date varchar(10), ...

  8. Java中的集合Collections工具类(六)

    操作集合的工具类Collections Java提供了一个操作Set.List和Map等集合的工具类:Collections,该工具类里提供了大量方法对集合元素进行排序.查询和修改等操作,还提供了将集 ...

  9. spring-boot-configuration-processor 是干啥用的

    spring默认使用yml中的配置,但有时候要用传统的xml或properties配置,就需要使用spring-boot-configuration-processor了 引入pom依赖 <de ...

  10. gcc/g++以c++11编译

    方法一: //在程序头加上预定义编译器命令 #pragma GCC diagnostic error "-std=c++11" //通过#pragma 指示 GCC编译器处理错误的 ...