首先是程序的自定义,这里设置了redis插件需要的参数,默认值,以及校验等。

然后注册Redis实例需要的信息,比如key的名字或者url等,可以看到默认的data_type是list模式。

程序运行的主要入口,根据不同的data_type,传递不同的实现方法,然后调用listener_loop执行循环监听

Listner_loop方法传递了两个参数,一个是监听器实现的方法,一个是处理的数据队列。循环是每秒钟执行一次,如果循环标识被设置,则退出。

上面的循环方法可以看到,是通过一个参数shutdown_requested来判断是否继续循环。该参数通过tear_down方法设置为true,然后根据不同的模式,指定不同的退出方式。
如果是list模式,则直接退出;如果是channel模式,则发送redis的unsubsribe命令退出;如果是pattern_channel,则发送punsubscribe退出。

在循环内部,判断是否已经创建了redis实例,如果没有创建,则调用connect方法创建;否则直接执行。

这里前一段是调用Redis的new方法,初始化一个redis实例。紧接着判断batch_count是否大于1,如果等于1,就什么也不做,然后返回redis。
如果batch_count大于1,那么就调用load_batch_script方法,加载Lua脚本,存储到redis中的lua脚本字典中,供后面使用。代码如下:

上面的代码应该是这个插件最难理解的部分了。为了弄清楚这段代码的工作,需要了解下面几个知识点:

  • lua脚本基本概念
  • Redis中的EVAL命令如何使用
  • 理解上面脚本的工作

首先,要想运行上面的脚本,必须是Redis2.6+的版本,才支持EVAL,否则会报错!EVAL命令与js中的差不多,就是可以把某一个字符串当做命令解析,其中字符串就包括lua脚本。这样有什么好处呢?

说白了,就是能一次性进行多个操作。比如我们可以在脚本中写入一连串的操作,这些操作会以原子模式,一次性在服务器执行完,在返回回来。

Lua脚本

关于lua脚本,其实没有详细研究的必要,但是一定要知道一个local和table的概念。local是创建本地的变量,这样就不会污染redis的数据。table是lua的一种数据结构,有点类似于json,可以存储数据。

EVAL命令

另外还要知道EVAL命令的使用方法,看下面这个命令,就好理解了!
EVAL "return KEYS[1] KEYS[2] ARGV[1] ARGV[2];" 2 name:xing age:13
就会返回:

name
age
xing
13

这段代码没有经过真正的操作,但是有助于理解就好!也就是说,EVAL后面跟着一段脚本,脚本后面跟着的就是参数,可以通过KEYS和ARGV数组获得,但是下标从1开始。

再来说说EVAL命令,它的执行过程如下:

  • 解析字符串脚本,根据校验和生成lua的方法
  • 把校验和和函数放入一个lua_script字典里面,之后就可以通过EVALSHA命令直接使用校验和执行函数。

有了这些理论基础以后,就可以看看上面的代码都做了什么了!
首先是获取参数,这个参数赋值给i;然后创建了一个对象res;紧接着调用llen命令,获得指定list的长度;如果list的长度大于i,则什么也不做;如果小于i,那么i就等于lenth;然后执行命令lpop,取出list中的元素,一共取i次,放入res中,最后返回。

说得通俗点,就是比较一下list元素个数与设置batch_count的值。如果batch_count为5,列表list中有5条以上的数据,那么直接取5条,一次性返回;否则取length条返回。

可以看到这段脚本的作用,就是让logstash一次请求,最多获得batch_count条事件,减小了服务器处理请求的压力。

讲完这段代码,可以看看不同的工作模式的实现代码了:

首先是list的代码,其实就是执行BLPOP命令,获取数据。如果在list模式中,还会去判断batch_count的值,如果是1直接退出;如果大于1,则使用evalsha命令调用之前保存的脚本方法。

至于channel和pattern_channel,就没啥解释的了,就是分别调用subscribe和psubsribe命令而已。

其实最难理解的,就是中间那段lua脚本~明白它的用处,redis插件也就不难理解了。

代码

# encoding: utf-8
require "logstash/inputs/base"
require "logstash/inputs/threadable"
require "logstash/namespace"# This input will read events from a Redis instance; it supports both Redis channels and lists.
# The list command (BLPOP) used by Logstash is supported in Redis v1.3.1+, and
# the channel commands used by Logstash are found in Redis v1.3.8+.
# While you may be able to make these Redis versions work, the best performance
# and stability will be found in more recent stable versions.  Versions 2.6.0+
# are recommended.
#
# For more information about Redis, see <http://redis.io/>
#
# `batch_count` note: If you use the `batch_count` setting, you *must* use a Redis version 2.6.0 or
# newer. Anything older does not support the operations used by batching.
#
class LogStash::Inputs::Redis < LogStash::Inputs::Threadableconfig_name "redis"default :codec, "json"# The `name` configuration is used for logging in case there are multiple instances.# This feature has no real function and will be removed in future versions.config :name, :validate => :string, :default => "default", :deprecated => true# The hostname of your Redis server.config :host, :validate => :string, :default => "127.0.0.1"# The port to connect on.config :port, :validate => :number, :default => 6379# The Redis database number.config :db, :validate => :number, :default => 0# Initial connection timeout in seconds.config :timeout, :validate => :number, :default => 5# Password to authenticate with. There is no authentication by default.config :password, :validate => :password# The name of the Redis queue (we'll use BLPOP against this).# TODO: remove soon.config :queue, :validate => :string, :deprecated => true# The name of a Redis list or channel.# TODO: change required to trueconfig :key, :validate => :string, :required => false# Specify either list or channel.  If `redis\_type` is `list`, then we will BLPOP the# key.  If `redis\_type` is `channel`, then we will SUBSCRIBE to the key.# If `redis\_type` is `pattern_channel`, then we will PSUBSCRIBE to the key.# TODO: change required to trueconfig :data_type, :validate => [ "list", "channel", "pattern_channel" ], :required => false# The number of events to return from Redis using EVAL.config :batch_count, :validate => :number, :default => 1publicdef registerrequire 'redis'@redis = nil@redis_url = "redis://#{@password}@#{@host}:#{@port}/#{@db}"# TODO remove after setting key and data_type to trueif @queueif @key or @data_typeraise RuntimeError.new("Cannot specify queue parameter and key or data_type")end@key = @queue@data_type = 'list'endif not @key or not @data_typeraise RuntimeError.new("Must define queue, or key and data_type parameters")end# end TODO@logger.info("Registering Redis", :identity => identity)end # def register# A string used to identify a Redis instance in log messages# TODO(sissel): Use instance variables for this once the @name config# option is removed.privatedef identity@name || "#{@redis_url} #{@data_type}:#{@key}"endprivatedef connectredis = Redis.new(:host => @host,:port => @port,:timeout => @timeout,:db => @db,:password => @password.nil? ? nil : @password.value)load_batch_script(redis) if @data_type == 'list' && (@batch_count > 1)return redisend # def connectprivatedef load_batch_script(redis)#A Redis Lua EVAL script to fetch a count of keys#in case count is bigger than current items in queue whole queue will be returned without extra nil valuesredis_script = <<EOFlocal i = tonumber(ARGV[1])local res = {}local length = redis.call('llen',KEYS[1])if length < i then i = length endwhile (i > 0) dolocal item = redis.call("lpop", KEYS[1])if (not item) thenbreakendtable.insert(res, item)i = i-1endreturn res
EOF@redis_script_sha = redis.script(:load, redis_script)endprivatedef queue_event(msg, output_queue)begin@codec.decode(msg) do |event|decorate(event)                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               output_queue << eventendrescue LogStash::ShutdownSignal => e# propagate upraise(e)rescue => e # parse or event creation error@logger.error("Failed to create event", :message => msg, :exception => e, :backtrace => e.backtrace);endendprivatedef list_listener(redis, output_queue)item = redis.blpop(@key, 0, :timeout => 1)return unless item # from timeout or other conditions# blpop returns the 'key' read from as well as the item result# we only care about the result (2nd item in the list).queue_event(item[1], output_queue)# If @batch_count is 1, there's no need to continue.return if @batch_count == 1beginredis.evalsha(@redis_script_sha, [@key], [@batch_count-1]).each do |item|queue_event(item, output_queue)end# Below is a commented-out implementation of 'batch fetch'# using pipelined LPOP calls. This in practice has been observed to# perform exactly the same in terms of event throughput as# the evalsha method. Given that the EVALSHA implementation uses# one call to Redis instead of N (where N == @batch_count) calls,# I decided to go with the 'evalsha' method of fetching N items# from Redis in bulk.#redis.pipelined do#error, item = redis.lpop(@key)#(@batch_count-1).times { redis.lpop(@key) }#end.each do |item|#queue_event(item, output_queue) if item#end# --- End commented out implementation of 'batch fetch'rescue Redis::CommandError => eif e.to_s =~ /NOSCRIPT/ then@logger.warn("Redis may have been restarted, reloading Redis batch EVAL script", :exception => e);load_batch_script(redis)retryelseraise eendendendprivatedef channel_listener(redis, output_queue)redis.subscribe @key do |on|on.subscribe do |channel, count|@logger.info("Subscribed", :channel => channel, :count => count)endon.message do |channel, message|queue_event message, output_queueendon.unsubscribe do |channel, count|@logger.info("Unsubscribed", :channel => channel, :count => count)endendendprivatedef pattern_channel_listener(redis, output_queue)redis.psubscribe @key do |on|on.psubscribe do |channel, count|@logger.info("Subscribed", :channel => channel, :count => count)endon.pmessage do |ch, event, message|queue_event message, output_queueendon.punsubscribe do |channel, count|@logger.info("Unsubscribed", :channel => channel, :count => count)endendend# Since both listeners have the same basic loop, we've abstracted the outer# loop.privatedef listener_loop(listener, output_queue)while !@shutdown_requestedbegin@redis ||= connectself.send listener, @redis, output_queuerescue Redis::BaseError => e@logger.warn("Redis connection problem", :exception => e)# Reset the redis variable to trigger reconnect@redis = nilsleep 1endendend # listener_looppublicdef run(output_queue)if @data_type == 'list'listener_loop :list_listener, output_queueelsif @data_type == 'channel'listener_loop :channel_listener, output_queueelselistener_loop :pattern_channel_listener, output_queueendrescue LogStash::ShutdownSignal# ignore and quitend # def runpublicdef teardown@shutdown_requested = trueif @redisif @data_type == 'list'@redis.quit rescue nilelsif @data_type == 'channel'@redis.unsubscribe rescue nil@redis.connection.disconnectelsif @data_type == 'pattern_channel'@redis.punsubscribe rescue nil@redis.connection.disconnectend@redis = nilendend
end # class LogStash::Inputs::Redis

logstash-input-redis源码解析相关推荐

  1. Redis源码解析——双向链表

    相对于之前介绍的字典和SDS字符串库,Redis的双向链表库则是非常标准的.教科书般简单的库.但是作为Redis源码的一部分,我决定还是要讲一讲的.(转载请指明出于breaksoftware的csdn ...

  2. Redis源码解析——字典基本操作

    有了<Redis源码解析--字典结构>的基础,我们便可以对dict的实现进行展开分析.(转载请指明出于breaksoftware的csdn博客) 创建字典 一般字典创建时,都是没有数据的, ...

  3. Redis源码解析——内存管理

    在<Redis源码解析--源码工程结构>一文中,我们介绍了Redis可能会根据环境或用户指定选择不同的内存管理库.在linux系统中,Redis默认使用jemalloc库.当然用户可以指定 ...

  4. Redis源码解析——前言

    今天开启Redis源码的阅读之旅.对于一些没有接触过开源代码分析的同学来说,可能这是一件很麻烦的事.但是我总觉得做一件事,不管有多大多难,我们首先要在战略上蔑视它,但是要在战术上重视它.除了一些高大上 ...

  5. Redis源码解析(15) 哨兵机制[2] 信息同步与TILT模式

    Redis源码解析(1) 动态字符串与链表 Redis源码解析(2) 字典与迭代器 Redis源码解析(3) 跳跃表 Redis源码解析(4) 整数集合 Redis源码解析(5) 压缩列表 Redis ...

  6. Redis源码解析——有序整数集

    有序整数集是Redis源码中一个以大尾(big endian)形式存储,由小到大排列且无重复的整型集合.它存储的类型包括16位.32位和64位的整型数.在介绍这个库的实现前,我们还需要先熟悉下大小尾内 ...

  7. Redis源码解析——Zipmap

    本文介绍的是Redis中Zipmap的原理和实现.(转载请指明出于breaksoftware的csdn博客) 基础结构 Zipmap是为了实现保存Pair(String,String)数据的结构,该结 ...

  8. Redis源码解析——字典结构

    C++语言中有标准的字典库,我们可以通过pair(key,value)的形式存储数据.但是C语言中没有这种的库,于是就需要自己实现.本文讲解的就是Redis源码中的字典库的实现方法.(转载请指明出于b ...

  9. Redis源码解析——字典遍历

    之前两篇博文讲解了字典库的基础,本文将讲解其遍历操作.之所以将遍历操作独立成一文来讲,是因为其中的内容和之前的基本操作还是有区别的.特别是高级遍历一节介绍的内容,充满了精妙设计的算法智慧.(转载请指明 ...

  10. Redis源码解析(1)——源码目录介绍

    概念 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合).这些 ...

最新文章

  1. Beta阶段总结博客(麻瓜制造者)
  2. 原因代码10044-Erdos number Time limit exceeded
  3. Web开发:HTML5、CSS、JavaScript必备教程
  4. 我的家乡-客家小山村
  5. Blind Return Oriented Programming (BROP) Attack - 攻击原理
  6. linux命令行怎么播放,如何在在 Linux 命令行中观看彩虹猫
  7. jzoj1293,P2933-气象牛(气象测量)【dp】
  8. VC++ COleSafeArray VARIANT的使用
  9. 996.ICU 下被过度消费的程序员,还配享受生活吗?
  10. bzoj 2987: Earthquake(类欧几里得)
  11. 依赖注入框架Autofac的简单使用
  12. Rabin-Karp算法详解和实现(python)
  13. Apple Pay 详解
  14. 关于BOM表的一些事
  15. Voxelization 三维模型体素化
  16. 关于树莓派屏幕显示不全的问题
  17. Win10微软帐户切换不回Administrator本地帐户的解决方法
  18. python中使用modbus_tk操作浮点数
  19. bitcoinj生成中文助记词
  20. android rom签名 作用,Ubuntu下折腾Android笔记(一)——ROM 签名 | 翅膀~

热门文章

  1. 二叉树高度的代码解析_剑指offer 从上到下打印二叉树
  2. 利用python做一个小游戏_如何使用python做一个简单的猜数字的小游戏
  3. 数据库mysql中贴换函数_关于一个自定义MYSQL函数,实现点击链接后,在数据库里改变数据的问题。...
  4. qt动态添加窗口到垂直布局
  5. CTF-MISC杂项题1
  6. php启动 大量sess文件,关于PHP中Session文件过多的问题
  7. python 调c++生成的dll 中识别char *_基于tensorflow 实现端到端的OCR:二代身份证号识别...
  8. html 选中状态,html默认选中状态
  9. 《软件项目管理(第二版)》第 5 章——项目进度和成本管理 重点部分总结
  10. 数据库管理工具:如何使用 Navicat Premium 转储(导出)和运行(导入)*.sql 文件?