Using Predix Cache with Ruby

Get code samples and recommended libraries for using a Predix Cache service with Ruby.

Recommended Ruby Library
Redis-rb. See https://github.com/redis/redis-rb
Alternative Libraries
None.

Code Samples Using Redis-rb Library

To install the library, add to Gemfile for use with bundler:

source 'https://rubygems.org'

  ruby '2.3.1'
  gem 'redis', '~>3.2'
  gem 'cf-app-utils'

Sample Cloud Foundry manifest.yml:

applications:
  - name: redis-sample
    command: ruby redis-sentinel-sample.rb
    mem: 256M
    disk: 1024M
    instances: 1
    services:
      - redis-ha-sample

Redis-rb sample for shared and dedicated single node service plans:

require 'redis'
  require 'cf-app-utils'

  credentials = CF::App::Credentials.find_by_service_label('predix-redis')
  $stdout.puts("Credentials: #{credentials}")

  redis = Redis.new(:host => credentials['host'], :port => credentials['port'], :password => credentials['password'])

  redis.set('foo', 'bar')
  res = redis.get('foo')
  $stdout.puts("Results: #{res}")

Redis-rb Sample for High availability Service Plans Using Sentinels

require 'redis'
  require 'cf-app-utils'

  credentials = CF::App::Credentials.find_by_service_label('predix-redis')
  $stdout.puts("Credentials: #{credentials}")

  SENTINELS = [
    {:host => credentials['ip_list'][0], :port => credentials['sentinel_port']},
    {:host => credentials['ip_list'][1], :port => credentials['sentinel_port']},
    {:host => credentials['ip_list'][2], :port => credentials['sentinel_port']}
  ]

  redis = Redis.new(:url => "redis://#{credentials['master_name']}", :sentinels => SENTINELS, :password => credentials['password'], :role => :master)
  redis.set('foo', 'bar')
  res = redis.get('foo')
  $stdout.puts("Results: #{res}")

Validate Connectivity

Even though the sample app will not start, it should output credentials info found in VCAP variables, as well as the key bar that was added in the redis.set command.

To verify the application is able to connect, look at the log output by using the following command:
cf logs redis-sample --recent
Output example:
[App/0] OUT Credentials: {"host"=>"172.72.9.249", 
"port"=>6379, 
"password"=>"password", 
"master_name"=>"cf-svc-redis-clustered-prod-9e0757fc-9813-4034-9496-097a2aa8469b", 
"sentinel_port"=>16379, 
"ip_list"=>["172.72.8.161", "172.72.9.249", "172.72.8.162"]}
  [App/0] OUT Results: bar