flume接收http请求,并将数据写到kafka,spark消费kafka的数据。是数据采集的经典框架。

直接上flume的配置:

source : http

channel : file

sink : kafka

xx :~/software/flume1.8/conf$ cat http-file-kafka.conf
# example.conf: A single-node Flume configuration
##########
# data example
# use post request, select raw, data example : [{"body" : "{'xx':'xxxxx1'}"}]
# just use the office request demo #[{
# "headers" : {
# "timestamp" : "434324343",
# "host" : "random_host.example.com"
# "topic" : "venn" # if headers contain topic, will replace the default topic
# },
# "body" : "random_body" # random_body is the message send to channel
# }] # Name the components on this agent1
agent1.sources = s1
agent1.sinks = k1
agent1.channels = c1
# Describe/configure the source
agent1.sources.s1.type = http
agent1.sources.s1.bind = spring # localhost 只能接收本地请求
agent1.sources.s1.port = 8084 # http的端口
agent1.sources.s1.handler = org.apache.flume.source.http.JSONHandler # 自带的接收http请求的handler
# Describe the sink
agent1.sinks.k1.type = org.apache.flume.sink.kafka.KafkaSink # kafkasink
agent1.sinks.k1.kafka.topic = mytopic # topic
agent1.sinks.k1.kafka.bootstrap.servers = localhost:9092 # kafka host and port
agent1.sinks.k1.kafka.flumeBatchSize = 20
agent1.sinks.k1.kafka.producer.acks = 1
agent1.sinks.k1.kafka.producer.linger.ms = 1
agent1.sinks.k1.kafka.producer.compression.type = snappy # 压缩
# Use a channel which buffers events in memory
agent1.channels.c1.type = file
#agent1.channels.c1.capacity = 1000 # 这两个参数要配置,需要配大一点,不然channel满了会报错,http返回503(通道已满)
#agent1.channels.c1.transactionCapacity = 100
agent1.channels.c1.checkpointDir = /opt/flume/checkpoint
agent1.channels.c1.dataDirs = /opt/flume/channel
# Bind the source and sink to the channel
agent1.sources.s1.channels = c1
agent1.sinks.k1.channel = c1

有了flume的配置,下面启动flume:

./bin/flume-ng agent -n agent1 -c conf -f conf/http-to-kafka.properties -Dflume.root.logger=INFO,console

启动之后,就可以发http请求了。

http请求的格式如下:

[{
"headers" : {
"timestamp" : "434324343",
"host" : "random_host.example.com",
"topic" : "xxx"
},
"body" : "random_body"
},
{
"headers" : {
"namenode" : "namenode.example.com",
"datanode" : "random_datanode.example.com"
},
"body" : "really_random_body"
}]

注: http请求的headers中又topic 会替代配置文件中的topic

  flume官网文档说:1.8.0版本的flume只支持0.9.x的kafka,不支持0.8.x的kafka了(没测过)

然后就是发数的程序了(自己请求太麻烦了。)

package com.venn.http;

import com.venn.entity.User;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*; import org.apache.flume.Context;
import org.apache.flume.Event;
import org.apache.flume.event.JSONEvent;
import com.google.gson.Gson;
import org.apache.flume.source.http.HTTPBadRequestException;
import org.apache.flume.source.http.HTTPSourceHandler; import javax.servlet.http.HttpServletRequest; /**
* Created by venn on 19-1-17.
*/
public class HttpDemo { private static String urlStr = "http://localhost:8084";
private static Random random = new Random();
public static void main(String[] args) throws InterruptedException { while (true){
String message = new User().toString();
send(message); // Thread.sleep(1);
}
}
public static void send(String message){
System.out.println("send message : " + message);
try{
//创建连接
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream()); JSONEvent jsonEvent = new JSONEvent();
Map header = new HashMap();
header.put("timestamp", System.currentTimeMillis());
header.put("host", "venn");
header.put("topic","venn"+random.nextInt(4));
jsonEvent.setBody(message.getBytes());
jsonEvent.setHeaders(header);
Gson gson = new Gson();
List list = new ArrayList();
list.add(jsonEvent);
out.writeBytes(gson.toJson(list));
out.flush();
out.close(); //读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream())); // 不会返回数据
int code = connection.getResponseCode();
String lines;
StringBuffer sb = new StringBuffer("");
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sb.append(lines);
}
System.out.println("code : " + code + ", message : " + sb);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} }

搞定。。

发数:

kafka接收到的数据:

注意: 由于在headers中加入了topic参数,实际接收到的数据是在不同的kafka topic中的

flume接收http请求,并将数据写到kafka的更多相关文章

  1. C# -- HttpWebRequest 和 HttpWebResponse 的使用 C#编写扫雷游戏 使用IIS调试ASP.NET网站程序 WCF入门教程 ASP.Net Core开发(踩坑)指南 ASP.Net Core Razor+AdminLTE 小试牛刀 webservice创建、部署和调用 .net接收post请求并把数据转为字典格式

    C# -- HttpWebRequest 和 HttpWebResponse 的使用 C# -- HttpWebRequest 和 HttpWebResponse 的使用 结合使用HttpWebReq ...

  2. .net接收post请求并把数据转为字典格式

    public SortedDictionary<string, string> GetRequestPost() { int i = 0; SortedDictionary<stri ...

  3. MVC Control 接收post请求的json数据

    [HttpPost] public string QueryInvoice() { string stream; using (var sr = new StreamReader(Request.In ...

  4. servlet接收request请求的json数据

    此次使用的是alibaba的fastjson:jar包为fastjson-1.2.7.jar 参考:https://www.qingtingip.com/h_229797.html 思路:由于此次接收 ...

  5. FLume监控文件夹,将数据发送给Kafka以及HDFS的配置文件详解

    详细配置文件flume-conf.properties如下: ############################################ # producer config ###### ...

  6. 将数据写到kafka的topic

    package test05 import java.util.Propertiesimport org.apache.kafka.clients.producer.{KafkaProducer, P ...

  7. Struts2 Action接收POST请求JSON数据及其实现解析

    一.认识JSON JSON是一种轻量级.基于文本.与语言无关的数据交换格式,可以用文本格式的形式来存储或表示结构化的数据. 二.POST请求与Content-Type: application/jso ...

  8. javaweb Servlet接收Android请求,并返回json数据

    1.实现功能 (1)接收http请求 (2)获取Android客户端发送的参数对应的内容 (3)hibernate查询数据库 (4)返回json数据 2.java代码 import EntityCla ...

  9. 学习笔记_springmvc返回值、数据写到页面、表单提交、ajax、重定向

    数据写到页面 后台往前台传数据 TestController添加 /** * 方法的返回值采用ModelAndView, new ModelAndView("index", map ...

随机推荐

  1. 最长公共前缀(python) leetcode答案

    直接上代码: def longestCommonPrefix(strs): """ :type strs: List[str] :rtype: str "&qu ...

  2. Golang源码探索(一) 编译和调试源码(转)

    GO可以说是近几年最热门的新兴语言之一了, 一般人看到分布式和大数据就会想到GO,这个系列的文章会通过研究golang的源代码来分析内部的实现原理,和CoreCLR不同的是, golang的源代码已经 ...

  3. MySql:SELECT 语句(四)通配符的使用

    1. LIKE 操作符 要在搜索子句中使用通配符,必须要使用 LIKE 操作符. 1)百分号通配符 最常用的通配符是百分号(%). % 表示任何字符出现的任意次数.但是 NULL 除外.可以匹配 0 ...

  4. Linux网络编程学习(九) ----- 消息队列(第四章)

    1.System V IPC System V中引入的几种新的进程间通信方式,消息队列,信号量和共享内存,统称为System V IPC,其具体实例在内核中是以对象的形式出现的,称为IPC 对象,每个 ...

  5. MySQL 登陆

    #==========================登陆mysql ============================================ # 登陆用户名:-u,登陆IP: -h, ...

  6. UE4 多人网络对战游戏笔记

    1.给物体施加一个径向力 定义一个径向力: URadialForceComponent* RadialForceComp; 在构造函数里赋默认值: RadialForceComp = CreateDe ...

  7. CamStar insitexmlclient重新封装为.net Core类库

    工作原因经常使用camstar的 InsiteXMLClient类库做二次开发,但是只能在4.X环境下使用,对于日益繁荣的.net core生态,花费了些时间把原有的类库重新封装为.net core ...

  8. python基础系列教程,数学基础系列教程,数据分析系列教程,神经网络系列教程,深度学习系列视频教程分享交流

    大家好,我是一个技术爱好者,目前对大数据人工智能很是痴迷,虽然学历只有高中,目前正在大踏步的向着人工智能狂奔,如果你也想学习,那就来吧 我的学习进度python基础(Numpy,pandas,matp ...

  9. Arcmap 空间连接,在通过面包含面的空间关系做属性关联的时候,发生关联冗余的问题。

    处理过程: (1)用 空间关联 工具实现  面与面的  空间和属性关联. (2) 问题描述: 一个子面要素对应多个父面要素,出现数据冗余. 问题根源: 解决办法: 取子面要素的 中心点,在用中心点和 ...

  10. springboot指定端口的三种方式

    第一配置文件中添加server.port=9090 第二在命令行中指定启动端口,比如传入参数一server. port=9000     java -jar bootsample. jar -- se ...