Memcached (Object cache)

Memcached is a simple in-memory object store well-suited for application level caching.

See the Memcached documentation for more information.

Both Memcached and Redis can be used for application caching. As a general rule, Memcached is simpler and thus more widely supported while Redis is more robust. Platform.sh recommends using Redis if possible but Memcached is fully supported if an application favors that cache service."

Use a framework 

If you use one of the following frameworks, follow its guide:

For more implementation ideas, consult a template.

Supported versions 

Grid Dedicated Gen 3 Dedicated Gen 2
  • 1.6
  • 1.5
  • 1.4
None available
  • 1.4

Relationship 

The format exposed in the $PLATFORM_RELATIONSHIPS environment variable:

{
    "service": "memcached16",
    "ip": "169.254.228.111",
    "hostname": "3sdm72jgaxge2b6aunxdlzxyea.memcached16.service._.eu-3.platformsh.site",
    "cluster": "rjify4yjcwxaa-master-7rqtwti",
    "host": "memcached.internal",
    "rel": "memcached",
    "scheme": "memcached",
    "type": "memcached:1.6",
    "port": 11211
}

Usage example 

1. Configure the service 

Use the memcached type to define the service:

.platform/services.yaml
<SERVICE_NAME>:
    type: memcached:<VERSION>

Note that if you later change the name, it’s treated as an entirely new service. This removes all data from your service. Always backup your data before changing the service.

2. Add the relationship 

Use the memcached endpoint to define the relationship:

.platform.app.yaml
relationships:
    <RELATIONSHIP_NAME>: "<SERVICE_NAME>:memcached"

You can define <SERVICE_NAME> and <RELATIONSHIP_NAME> as you like, but it’s best if they’re distinct.

For PHP, enable the extension for the service:

.platform.app.yaml
runtime:
    extensions:
        - memcached

For Python, include the proper dependency:

.platform.app.yaml
dependencies:
    python:
        python-memcached: '*'

Example Configuration 

Service definition

.platform/services.yaml
cachemc:
    type: memcached:1.6

App configuration

.platform.app.yaml
relationships:
    memcachedcache: "cachemc:memcached"

# If using PHP
runtime:
    extensions:
        - memcached

# If using Python
dependencies:
    python:
        python-memcached: '*'

Use in app 

Then use the service in your app with a configuration file like the following:

package examples

import (
	"fmt"
	"github.com/bradfitz/gomemcache/memcache"
	psh "github.com/platformsh/config-reader-go/v2"
	gomemcache "github.com/platformsh/config-reader-go/v2/gomemcache"
)

func UsageExampleMemcached() string {

	// Create a NewRuntimeConfig object to ease reading the Platform.sh environment variables.
	// You can alternatively use os.Getenv() yourself.
	config, err := psh.NewRuntimeConfig()
	checkErr(err)

	// Get the credentials to connect to the Solr service.
	credentials, err := config.Credentials("memcached")
	checkErr(err)

	// Retrieve formatted credentials for gomemcache.
	formatted, err := gomemcache.FormattedCredentials(credentials)
	checkErr(err)

	// Connect to Memcached.
	mc := memcache.New(formatted)

	// Set a value.
	key := "Deploy_day"
	value := "Friday"

	err = mc.Set(&memcache.Item{Key: key, Value: []byte(value)})

	// Read it back.
	test, err := mc.Get(key)

	return fmt.Sprintf("Found value <strong>%s</strong> for key <strong>%s</strong>.", test.Value, key)
}
package sh.platform.languages.sample;

import net.spy.memcached.MemcachedClient;
import sh.platform.config.Config;

import java.util.function.Supplier;

import sh.platform.config.Memcached;

public class MemcachedSample implements Supplier<String> {

    @Override
    public String get() {
        StringBuilder logger = new StringBuilder();

        // Create a new config object to ease reading the Platform.sh environment variables.
        // You can alternatively use getenv() yourself.
        Config config = new Config();

        // Get the credentials to connect to the Memcached service.
        Memcached memcached = config.getCredential("memcached", Memcached::new);

        final MemcachedClient client = memcached.get();

        String key = "cloud";
        String value = "platformsh";

        // Set a value.
        client.set(key, 0, value);

        // Read it back.
        Object test = client.get(key);

        logger.append("<p>");
        logger.append(String.format("Found value <code>%s</code> for key <code>%s</code>.", test, key));
        logger.append("</p>");

        return logger.toString();
    }
}
const Memcached = require('memcached');
const config = require("platformsh-config").config();
const { promisify } = require('util');

exports.usageExample = async function() {
    const credentials = config.credentials('memcached');
    const client = new Memcached(`${credentials.host}:${credentials.port}`);

    // The MemcacheD client is not Promise-aware, so make it so.
    const memcachedGet = promisify(client.get).bind(client);
    const memcachedSet = promisify(client.set).bind(client);

    const key = 'Deploy-day';
    const value = 'Friday';

    // Set a value.
    await memcachedSet(key, value, 10);

    // Read it back.
    const test = await memcachedGet(key);

    return `Found value <strong>${test}</strong> for key <strong>${key}</strong>.`;
};
<?php

declare(strict_types=1);

use Platformsh\ConfigReader\Config;

// Create a new config object to ease reading the Platform.sh environment variables.
// You can alternatively use getenv() yourself.
$config = new Config();

// Get the credentials to connect to the Memcached service.
$credentials = $config->credentials('memcached');

try {
    // Connecting to Memcached server.
    $memcached = new Memcached();
    $memcached->addServer($credentials['host'], $credentials['port']);
    $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true);

    $key = "Deploy day";
    $value = "Friday";

    // Set a value.
    $memcached->set($key, $value);

    // Read it back.
    $test = $memcached->get($key);

    printf('Found value <strong>%s</strong> for key <strong>%s</strong>.', $test, $key);

} catch (Exception $e) {
    print $e->getMessage();
}

import pymemcache
from platformshconfig import Config


def usage_example():

    # Create a new Config object to ease reading the Platform.sh environment variables.
    # You can alternatively use os.environ yourself.
    config = Config()

    # Get the credentials to connect to the Memcached service.
    credentials = config.credentials('memcached')

    try:
        # Try connecting to Memached server.
        memcached = pymemcache.Client((credentials['host'], credentials['port']))
        memcached.set('Memcached::OPT_BINARY_PROTOCOL', True)

        key = "Deploy_day"
        value = "Friday"

        # Set a value.
        memcached.set(key, value)

        # Read it back.
        test = memcached.get(key)

        return 'Found value <strong>{0}</strong> for key <strong>{1}</strong>.'.format(test.decode("utf-8"), key)

    except Exception as e:
        return e

Accessing Memcached directly 

To access the Memcached service directly you can use netcat as Memcached doesn’t have a dedicated client tool. Assuming your Memcached relationship is named cache, the host name and port number obtained from PLATFORM_RELATIONSHIPS would be cache.internal and 11211. Open an SSH session and access the Memcached server as follows:

netcat cache.internal 11211