OpenRestry +Lua + Kafka 实战代码

下载OpenRestry 

OpenResty - OpenResty 1.21.4.2 Released

下载Lua和Kafka 集成插件

https://github.com/doujiang24/lua-resty-kafka

-- 导入依赖
local producer = require "resty.kafka.producer"

local broker_list = {
         { host = "192.168.x.xxx", port = 9000 },
         { host = "192.168.x.yyy", port = 9000 },

}
-- 分区发送策略
local function partitioner(key, num, correlation_id)
	return key % num
end
-- producer_type  async 表示异步批量发送,非async 是单条发送;
local CONNECT_PARAMS = { producer_type = "async", socket_timeout = 5000,flush_time = 50,producer_retry_times = 3,partitioner =partitioner }

--发送kafka类型 1正确
local function sendkafka(p,topic, key, r,t)
    if r ~= nil then
		local offset, err = p:send(topic, key, r)
		--print("offset"..err)
		if not offset then
            -- 收集错误日志
			print("send type "..t..",and send data is "..r.." and send err:", err)
			return
		end
	else
	    print("send data is nil and type is "..t)
	end

end
-- 开始接收请求body
ngx.req.read_body()
ngx.update_time()
local nows = ngx.now()
local times,count = string.gsub(nows, "%.", "")
local strlen = string.len(times)
if strlen == 10 then 
	   times = times.."000"
	end
if strlen == 11 then 
	   times = times.."00"
	end
if strlen == 12 then 
	   times = times.."0"
	end
local topic = "mytopic"
local key = string.sub(times,-3)
local body = ngx.var.request_body


if body then
	local p = producer:new(broker_list,CONNECT_PARAMS)
	sendkafka(p,topic, key, tostring(body),1)
end
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HuntFalcon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值