Skip Navigation
Show nav
Heroku Dev Center
  • Get Started
  • Documentation
  • Changelog
  • Search
  • Get Started
    • Node.js
    • Ruby on Rails
    • Ruby
    • Python
    • Java
    • PHP
    • Go
    • Scala
    • Clojure
  • Documentation
  • Changelog
  • More
    Additional Resources
    • Home
    • Elements
    • Products
    • Pricing
    • Careers
    • Help
    • Status
    • Events
    • Podcasts
    • Compliance Center
    Heroku Blog

    Heroku Blog

    Find out what's new with Heroku on our blog.

    Visit Blog
  • Log inorSign up
View categories

Categories

  • Heroku Architecture
    • Dynos (app containers)
    • Stacks (operating system images)
    • Networking & DNS
    • Platform Policies
    • Platform Principles
  • Command Line
  • Deployment
    • Deploying with Git
    • Deploying with Docker
    • Deployment Integrations
  • Continuous Delivery
    • Continuous Integration
  • Language Support
    • Node.js
    • Ruby
      • Working with Bundler
      • Rails Support
    • Python
      • Background Jobs in Python
      • Working with Django
    • Java
      • Working with Maven
      • Java Database Operations
      • Working with Spring Boot
      • Java Advanced Topics
    • PHP
    • Go
      • Go Dependency Management
    • Scala
    • Clojure
  • Databases & Data Management
    • Heroku Postgres
      • Postgres Basics
      • Postgres Getting Started
      • Postgres Performance
      • Postgres Data Transfer & Preservation
      • Postgres Availability
      • Postgres Special Topics
    • Heroku Data For Redis
    • Apache Kafka on Heroku
    • Other Data Stores
  • Monitoring & Metrics
    • Logging
  • App Performance
  • Add-ons
    • All Add-ons
  • Collaboration
  • Security
    • App Security
    • Identities & Authentication
    • Compliance
  • Heroku Enterprise
    • Private Spaces
      • Infrastructure Networking
    • Enterprise Accounts
    • Enterprise Teams
    • Heroku Connect (Salesforce sync)
      • Heroku Connect Administration
      • Heroku Connect Reference
      • Heroku Connect Troubleshooting
    • Single Sign-on (SSO)
  • Patterns & Best Practices
  • Extending Heroku
    • Platform API
    • App Webhooks
    • Heroku Labs
    • Building Add-ons
      • Add-on Development Tasks
      • Add-on APIs
      • Add-on Guidelines & Requirements
    • Building CLI Plugins
    • Developing Buildpacks
    • Dev Center
  • Accounts & Billing
  • Troubleshooting & Support
  • Integrating with Salesforce
  • Databases & Data Management
  • Heroku Data For Redis
  • Connecting to Heroku Data for Redis

Connecting to Heroku Data for Redis

English — 日本語に切り替える

Last updated March 02, 2023

Table of Contents

  • Connection Permissions
  • External Connections
  • Connecting in Java
  • Connecting in Ruby
  • Connecting in Python
  • Connecting in Node.js
  • Connecting in PHP
  • Connecting in Go

Heroku Data for Redis is accessible from any language with a Redis driver, including all languages and frameworks supported by Heroku. You can also access Heroku Data for Redis hosted on the Mini or Premium plan from clients running in your own environment.

Connection Permissions

All Heroku Data for Redis users are granted access to all commands within Redis except CONFIG, SHUTDOWN, BGREWRITEAOF, BGSAVE, SAVE, MOVE, MODULE, MIGRATE, SLAVEOF, REPLICAOF, ACL and DEBUG.

External Connections

In addition to being available to the Heroku runtime, you can access Heroku Data for Redis Mini and Premium plan instances from clients running on your local computer or elsewhere.

Before version 6, Redis is unable to encrypt data over the network via SSL or other mechanisms. See Securing Heroku Data for Redis Versions 4 and 5 for more information on how to connect to Heroku Data for Redis securely, either natively or using stunnel.

To connect from an external system or client, retrieve the Redis connection string using either of the following methods:

  • Running the heroku redis:credentials CLI command (for more information, see redis:credentials)
  • Inspecting your app’s config vars by running the command heroku config:get REDIS_URL -a example-app.

For production Heroku Data for Redis plans, only REDIS_URL is available. For Heroku Data for Redis Mini plans, REDIS_URL and REDIS_TLS_URL are both available for non-TLS and TLS connections. If you’re on a Heroku Data for Redis Mini plan, use REDIS_TLS_URL to connect to your Redis add-on via a TLS connection.

 

The REDIS_URL and REDIS_TLS_URL config vars can change at any time. If you rely on the config var outside of your Heroku app and it changes, you must recopy the value.

Connecting in Java

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

A variety of ways exist to connect to Heroku Data for Redis but each depends on the Java framework in use. All methods of connecting use the REDIS_URL environment variable to determine connection information.

Spring Boot

Spring Boot’s support for Redis picks up all Redis configuration such as REDIS_URL automatically. Define a LettuceClientConfigurationBuilderCustomizer bean to disable TLS peer verification:

@Configuration
class AppConfig {

    @Bean
    public LettuceClientConfigurationBuilderCustomizer lettuceClientConfigurationBuilderCustomizer() {
        return clientConfigurationBuilder -> {
            if (clientConfigurationBuilder.build().isUseSsl()) {
                clientConfigurationBuilder.useSsl().disablePeerVerification();
            }
        };
    }
}

Lettuce

This snippet uses the REDIS_URL environment variable to create a connection to Redis via Lettuce. StatefulRedisConnection is thread-safe and can be safely used in a multithreaded environment:

 public static StatefulRedisConnection<String, String> connect() {
    RedisURI redisURI = RedisURI.create(System.getenv("REDIS_URL"));
    redisURI.setVerifyPeer(false);

    RedisClient redisClient = RedisClient.create(redisURI);
    return redisClient.connect();
}

Jedis

This snippet uses the REDIS_URL environment variable to create a URI. The new URI is used to create a connection to Redis via Jedis. In this example, we’re creating one connection to Redis:

private static Jedis getConnection() {
    try {
        TrustManager bogusTrustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{bogusTrustManager}, new java.security.SecureRandom());

        HostnameVerifier bogusHostnameVerifier = (hostname, session) -> true;

        return new Jedis(URI.create(System.getenv("REDIS_URL")),
                sslContext.getSocketFactory(),
                sslContext.getDefaultSSLParameters(),
                bogusHostnameVerifier);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException("Cannot obtain Redis connection!", e);
    }
}

If you’re running Jedis in a multithreaded environment, such as a web server, don’t use the same Jedis instance to interact with Redis. Instead, create a Jedis Pool so that the application code can check out a Redis connection and return it to the pool when it’s done:

// The assumption with this method is that it's been called when the application
// is booting up so that a static pool has been created for all threads to use.
// e.g. pool = getPool()
public static JedisPool getPool() {
    try {
        TrustManager bogusTrustManager = new X509TrustManager() {
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        };

        SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, new TrustManager[]{bogusTrustManager}, new java.security.SecureRandom());

        HostnameVerifier bogusHostnameVerifier = (hostname, session) -> true;

        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxTotal(10);
        poolConfig.setMaxIdle(5);
        poolConfig.setMinIdle(1);
        poolConfig.setTestOnBorrow(true);
        poolConfig.setTestOnReturn(true);
        poolConfig.setTestWhileIdle(true);

        return new JedisPool(poolConfig,
                URI.create(System.getenv("REDIS_URL")),
                sslContext.getSocketFactory(),
                sslContext.getDefaultSSLParameters(),
                bogusHostnameVerifier);

    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        throw new RuntimeException("Cannot obtain Redis connection!", e);
    }
}
// In your multithreaded code this is where you'd checkout a connection
// and then return it to the pool
try (Jedis jedis = pool.getResource()){
  jedis.set("foo", "bar");
}

Connecting in Ruby

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

To use Redis in your Ruby application, you must include the redis gem in your Gemfile:

gem 'redis'

Run bundle install to download and resolve all dependencies.

Connecting in Rails

Create an initializer file named config/initializers/redis.rb containing:

$redis = Redis.new(url: ENV["REDIS_URL"], ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE })

Connecting from Sidekiq

Create an initializer file named config/initializers/sidekiq.rb containing:

Sidekiq.configure_server do |config|
  config.redis = {
    url: ENV["REDIS_URL"],
    ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE }
  }
end

Sidekiq.configure_client do |config|
  config.redis = {
      url: ENV["REDIS_URL"],
      ssl_params: { verify_mode: OpenSSL::SSL::VERIFY_NONE }
  }
end

Connecting in Python

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

To use Redis in Python your application, use the redis package:

$ pip install redis
$ pip freeze > requirements.txt

And use this package to connect to REDIS_URL in your code:

import os
import redis

r = redis.from_url(os.environ.get("REDIS_URL"))

If your Redis requires TLS, configure ssl_cert_reqs to disable certificate validation:

import os
from urllib.parse import urlparse
import redis

url = urlparse(os.environ.get("REDIS_URL"))
r = redis.Redis(host=url.hostname, port=url.port, password=url.password, ssl=True, ssl_cert_reqs=None)

Connecting in Django

To use Redis in your Django application, use django-redis:

$ pip install django-redis
$ pip freeze > requirements.txt

In your settings.py, configure your CACHES as:

import os

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
        }
    }
}

If your Redis requires TLS, configure ssl_cert_reqs to disable certificate validation:

import os

CACHES = {
    "default": {
        "BACKEND": "django_redis.cache.RedisCache",
        "LOCATION": os.environ.get('REDIS_URL'),
        "OPTIONS": {
            "CLIENT_CLASS": "django_redis.client.DefaultClient",
            "CONNECTION_POOL_KWARGS": {
                "ssl_cert_reqs": None
            },
        }
    }
}

Connecting in Node.js

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

redis Module

Add the redis NPM module to your dependencies:

npm install redis

And use the module to connect to REDIS_URL:

const redis = require("redis");
const client = redis.createClient({url: process.env.REDIS_URL});

Additionally, you configure redis to use TLS:

const redis = require("redis");

const client = redis.createClient({
  url: process.env.REDIS_URL,
  tls: {
    rejectUnauthorized: false
  }
});

ioredis Module

Add ioredis NPM module to your dependencies:

npm install ioredis

And use the module to connect to REDIS_URL:

const Redis = require("ioredis");
const client = new Redis(process.env.REDIS_URL);

If you want to set up the client with TLS, you can use the following:

const Redis = require("ioredis");

const client = new Redis(process.env.REDIS_URL, {
    tls: {
        rejectUnauthorized: false
    }
});

Connecting in PHP

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

Connecting with the Redis Extension

Add ext-redis to your requirements in composer.json:

"require": {
  …
  "ext-redis": "*",
  …
}

Connect to Redis after parsing the REDIS_URL config var from the environment:

$url = parse_url(getenv("REDIS_URL"));
$redis = new Redis();
$redis->connect("tls://".$url["host"], $url["port"], 0, NULL, 0, 0, [
  "auth" => $url["pass"],
  "stream" => ["verify_peer" => false, "verify_peer_name" => false],
]);

Connecting with Predis

Add the predis package to your requirements in composer.json:

"require": {
  ...
  "predis/predis": "^1.1",
  ...
}

Connect to Redis using the REDIS_URL config var from the environment:

$redis = new Predis\Client(getenv('REDIS_URL') . "?ssl[verify_peer_name]=0&ssl[verify_peer]=0");

Connecting in Go

If you’re using a Mini Heroku Data for Redis add-on, use REDIS_TLS_URL instead of REDIS_TLS to connect to your Redis add-on via a TLS connection.

Add the redigo package in your application:

$ go get github.com/gomodule/redigo/redis

Import the package:

import "github.com/gomodule/redigo/redis"

Connect to Redis using the REDIS_URL configuration variable:

c, err := redis.DialURL(os.Getenv("REDIS_URL"),  redis.DialTLSSkipVerify(true))
if err != nil {
    // Handle error
}
defer c.Close()

Keep reading

  • Heroku Data For Redis

Feedback

Log in to submit feedback.

Upgrading a Heroku Data for Redis Version Connecting to Heroku Data for Redis in a Private or Shield Space via PrivateLink

Information & Support

  • Getting Started
  • Documentation
  • Changelog
  • Compliance Center
  • Training & Education
  • Blog
  • Podcasts
  • Support Channels
  • Status

Language Reference

  • Node.js
  • Ruby
  • Java
  • PHP
  • Python
  • Go
  • Scala
  • Clojure

Other Resources

  • Careers
  • Elements
  • Products
  • Pricing

Subscribe to our monthly newsletter

Your email address:

  • RSS
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku Blog
    • Heroku News Blog
    • Heroku Engineering Blog
  • Heroku Podcasts
  • Twitter
    • Dev Center Articles
    • Dev Center Changelog
    • Heroku
    • Heroku Status
  • Facebook
  • Instagram
  • Github
  • LinkedIn
  • YouTube
Heroku is acompany

 © Salesforce.com

  • heroku.com
  • Terms of Service
  • Privacy
  • Cookies
  • Cookie Preferences