Permalink
Find file
Fetching contributors…
Cannot retrieve contributors at this time
53 lines (36 sloc) 1.75 KB

MemcacheArray

MemcacheArray is a wrapper for Memcache so it can be used as shared memory holding arrays. It is intended as a mechanism to move data from one ruby process to another.

When creating an new instance you pass the key and optionally an instance of a memcache store. If no store is passed, Rails.cache is assumed.

require 'active_support'
require 'memcache_array'

mamcache_array = MemcacheArray.new('my_key', ActiveSupport::Cache::MemCacheStore.new)
mamcache_array << [1, 2, 3]
mamcache_array << [4, 5, 6]
mamcache_array.all
=> [1, 2, 3, 1, 2, 3, 4, 5, 6]
mamcache_array.all(:delete => true)
=> [1, 2, 3, 1, 2, 3, 4, 5, 6]
mamcache_array.all
=> []

You can also pass metadata and filter for it when accessing the data. This way you can avoid reading large buckets only to discard them later.

require 'active_support'
require 'memcache_array'

mamcache_array = MemcacheArray.new('another_key', ActiveSupport::Cache::MemCacheStore.new)
mamcache_array.<<([1, 3, 5], 'odd')
mamcache_array.<<([2, 4, 6], 'even')
mamcache_array.<<([7], 'odd')
mamcache_array.all{|meta| meta == 'odd'}
=> [1, 3, 5, 7]

Caveat

When writing to the same MemcacheArray (several instances using the same key) concurrently, there is a slim chance that writes are lost. The time window of this to happen is one read of a small bucket from memcache, pushing an integer into an array and writing this small array back to memcache. With a normal setup, this schould not be more than 1-2 ms.

Installation

(sudo) gem install memcache_array

Authors

Dr. Florian Odronitz (odo@mac.com)

Contact

For questions, contact the authors or developer@traveliq.net

Copyright

Copyright © 2011 www.travel-iq.com. See LICENSE.txt for further details.