# Memcached (Object cache)

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

See the [Memcached documentation](https://memcached.org) 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. Upsun Fixed 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:

- [Drupal](https://fixed.docs.upsun.com/guides/drupal/memcached.md)

## Supported versions

You can select the major and minor version.

Patch versions are applied periodically for bug fixes and the like. When you deploy your app, you always get the latest available patches.

| Grid | Dedicated Gen 2 |
| 

   - 1.6

   - 1.5

   - 1.4

\* No High-Availability on Dedicated Gen 2.

## Relationship reference

Example information available through the [`PLATFORM_RELATIONSHIPS` environment variable](https://fixed.docs.upsun.com/development/variables/use-variables.md#use-provided-variables)
or by running `platform relationships`.

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed.
So your apps should only rely on the `PLATFORM_RELATIONSHIPS` environment variable directly rather than hard coding any values.

```json
{
  "service": "memcached",
  "ip": "123.456.78.90",
  "hostname": "azertyuiopqsdfghjklm.memcached.service._.eu-1.platformsh.site",
  "cluster": "azertyuiopqsdf-main-afdwftq",
  "host": "memcached.internal",
  "rel": "memcached",
  "scheme": "memcached",
  "type": "memcached:1.6",
  "port": 11211
}
```

## Usage example

### 1. Configure the service

To define the service, use the `memcached` type:

```yaml  {location=".platform/services.yaml"}
# The name of the service container. Must be unique within a project.
<SERVICE_NAME>:
  type: memcached:<VERSION>
```

### 2. Define the relationship

To define the relationship, use the following configuration:

```yaml {}
name: myapp
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
  <SERVICE_NAME>:
```

You can define ``<SERVICE_NAME>`` as you like, so long as it’s unique between all defined services
and matches in both the application and services configuration.
The example above leverages [default endpoint](https://fixed.docs.upsun.com/create-apps/image-properties/relationships.md) configuration for relationships.
That is, it uses default endpoints behind the scenes, providing a [relationship](https://fixed.docs.upsun.com/create-apps/image-properties/relationships.md)
(the network address a service is accessible from) that is identical to the name of that service.
Depending on your needs, instead of default endpoint configuration,
you can use [explicit endpoint configuration](https://fixed.docs.upsun.com/create-apps/image-properties/relationships.md).
With the above definition, the application container now has [access to the service](#use-in-app) via the relationship ``<SERVICE_NAME>`` and its corresponding [PLATFORM_RELATIONSHIPS](https://fixed.docs.upsun.com/development/variables/use-variables.md#use-provided-variables).

    .platform.app.yaml

```yaml {}
name: myapp
# Relationships enable access from this app to a given service.
# The example below shows configuration with an explicitly set service name and endpoint.
# See the Application reference for all options for defining relationships and endpoints.
# Note that legacy definition of the relationship is still supported.
# More information: https://docs.upsun.com/anchors/fixed/app/reference/relationships/
relationships:
  <RELATIONSHIP_NAME>:
    service: <SERVICE_NAME>
    endpoint: memcached
```

You can define ``<SERVICE_NAME>`` and ``<RELATIONSHIP_NAME>`` as you like, so long as it’s unique between all defined services and relationships
and matches in both the application and services configuration.
The example above leverages [explicit endpoint](https://fixed.docs.upsun.com/create-apps/image-properties/relationships.md) configuration for relationships.
Depending on your needs, instead of explicit endpoint configuration,
you can use [default endpoint configuration](https://fixed.docs.upsun.com/create-apps/image-properties/relationships.md).
With the above definition, the application container now has [access to the service](#use-in-app) via the relationship ``<RELATIONSHIP_NAME>`` and its corresponding [PLATFORM_RELATIONSHIPS](https://fixed.docs.upsun.com/development/variables/use-variables.md#use-provided-variables).

### Example configuration

### [Service definition](https://fixed.docs.upsun.com/add-services.md)

```yaml  {location=".platform/services.yaml"}
# The name of the service container. Must be unique within a project.
memcached:
  type: memcached:1.6
```

#### [App configuration](https://fixed.docs.upsun.com/create-apps.md)

```yaml {}
name: myapp
# Relationships enable access from this app to a given service.
# The example below shows simplified configuration leveraging a default service
# (identified from the relationship name) and a default endpoint.
# See the Application reference for all options for defining relationships and endpoints.
relationships:
  memcached:
```

    .platform.app.yaml

```yaml {}
name: myapp
# Relationships enable access from this app to a given service.
# The example below shows configuration with an explicitly set service name and endpoint.
# See the Application reference for all options for defining relationships and endpoints.
# Note that legacy definition of the relationship is still supported.
# More information: https://docs.upsun.com/anchors/fixed/app/reference/relationships/
relationships:
  memcached:
    service: memcached
    endpoint: memcached
```

### Use in app

To use the configured service in your app, add a configuration file similar to the following to your project.

```java {}
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 Upsun Fixed 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();
    }
}

```
```js {}
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 {}
<?php

declare(strict_types=1);

use Platformsh\ConfigReader\Config;

// Create a new config object to ease reading the Upsun Fixed 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();
}

```
```python {}

import pymemcache
from platformshconfig import Config

def usage_example():

    # Create a new Config object to ease reading the Upsun Fixed 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 `memcached`, the host name and port number obtained from `PLATFORM_RELATIONSHIPS` would be `memcached.internal` and `11211`.
Open an [SSH session](https://fixed.docs.upsun.com/development/ssh.md) and access the Memcached server as follows:

```bash  {location="Terminal"}
netcat memcached.internal 11211
```

Note that the information about the relationship can change when an app is redeployed or restarted or the relationship is changed. So your apps should only rely on the `PLATFORM_RELATIONSHIPS` environment variable directly rather than hard coding any values.

