如何保存和显示Dashing历史值?

时间:2016-03-03 19:41:53

标签: ruby redis dashing

目前,要设置graph窗口小部件,作业应传递要显示的所有值:

  data = [
    { "x" => 1980, "y" => 1323 },
    { "x" => 1981, "y" => 53234 },
    { "x" => 1982, "y" => 2344 }
  ]

我想从我的服务器读取当前(最新)值,但也应显示以前的值。

看起来我可以create a job,它将从服务器读取当前值,但是要从Redis(或sqlite database)读取剩余值,但我更喜欢Redis。之后的当前值应保存到数据库中。

我之前从未使用过Ruby和Dashing,所以我遇到的第一个问题是 - 有可能吗?如果我将使用Redis,那么问题是如何存储数据,因为这是键值数据库。我可以将其保留为widget-id-1widget-id-2widget-id-3 ... widget-id-N等,但在这种情况下,我必须存储N值(如widget-id=N)。或者,还有更好的方法吗?

1 个答案:

答案 0 :(得分:0)

我找到了以下解决方案:

require 'redis' # https://github.com/redis/redis-rb
redis_uri = URI.parse(ENV["REDISTOGO_URL"])
redis = Redis.new(:host => redis_uri.host, :port => redis_uri.port, :password => redis_uri.password)

if redis.exists('values_x') && redis.exists('values_y')
    values_x = redis.lrange('values_x', 0, 9) # get latest 10 records
    values_y = redis.lrange('values_y', 0, 9) # get latest 10 records
else
    values_x = []
    values_y = []
end

SCHEDULER.every '10s', :first_in => 0 do |job|
  rand_data = (Date.today-rand(10000)).strftime("%d-%b") # replace this line with the code to get your data
  rand_value = rand(50) # replace this line with the code to get your data
  values_x << rand_data
  values_y << rand_value

  redis.multi do # execute as a single transaction
    redis.lpush('values_x', rand_data)
    redis.lpush('values_y', rand_value)
    # feel free to add more datasets values here, if required
  end

  data = [
    {
      label: 'dataset-label',
      fillColor: 'rgba(220,220,220,0.5)',
      strokeColor: 'rgba(220,220,220,0.8)',
      highlightFill: 'rgba(220,220,220,0.75)',
      highlightStroke: 'rgba(220,220,220,1)',
      data: values_y.last(10) # display last 10 values only
     }
  ]
  options = { scaleFontColor: '#fff' }

  send_event('barchart', { labels: values_x.last(10), datasets: data, options: options })
end

不确定这里是否所有内容都已正确实施,但确实有效。