Related Documentation : Integrations : Using Ehcache with JRuby and Rails : Using the jruby-ehcache API directly
Using the jruby-ehcache API directly
To make Ehcache available to JRuby:
require 'ehcache'
Note that, because jruby-ehcache is provided as a Ruby Gem, you must make your Ruby interpreter aware of Ruby Gems in order to load it. You can do this by either including -rubygems on your jruby command line, or you can make Ruby Gems available to JRuby globally by setting the RUBYOPT environment variable as follows:
export RUBYOPT=rubygems
To create a CacheManager, which you do once when the application starts:
manager = Ehcache::CacheManager.new
To access an existing cache (call it "sampleCache1"):
cache = manager.cache("sampleCache1")
To create a new cache from the defaultCache:
cache = manager.cache
To put into a cache:
cache.put("key", "value", {:ttl => 120})
To get from a cache:
cache.get("key") # Returns the Ehcache Element object
cache["key"] # Returns the value of the element directly
To shut down the CacheManager: This is only when you shut your application down. It is not necessary to call this if the cache is configured for persistence or is clustered with Terracotta, but it is always a good idea to do it.
manager.shutdown
Supported Properties
The following caching options are supported in JRuby:
Property
Argument Type
Description
unlessExist, ifAbsent
boolean
If true, use the putIfAbsent method.
elementEvictionData
ElementEvictionData
Sets this element’s eviction data instance.
eternal
boolean
Sets whether the element is eternal.
timeToIdle, tti
int
Sets time to idle.
timeToLive, ttl, expiresIn
int
Sets time to live.
version
long
Sets the version attribute of the ElementAttributes object.
Example Configuration
class SimpleEhcache
#Code here
require 'ehcache'
manager = Ehcache::CacheManager.new
cache = manager.cache
cache.put("answer", "42", {:ttl => 120})
answer = cache.get("answer")
puts "Answer: #{answer.value}"
question = cache["question"] || 'unknown'
puts "Question: #{question}"
manager.shutdown
end
As you can see from the example, you create a cache using CacheManager.new, and you can control the "time to live" value of a cache entry using the :ttl option in cache.put.
Copyright © 2010-2017 Software AG, Darmstadt, Germany. (Innovation Release)

Product Logo |   Feedback