

Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.

# Tutorials: Erste Schritte mit Python und ElastiCache
<a name="ElastiCache-Getting-Started-Tutorials"></a>

Dieser Abschnitt enthält praktische Tutorials, die Ihnen helfen, mehr über Valkey und Redis OSS zu ElastiCache erfahren. Wir empfehlen Ihnen, eines der sprachspezifischen Tutorials durchzuarbeiten. 

**Anmerkung**  
AWS SDKs sind für eine Vielzahl von Sprachen verfügbar. Eine vollständige Liste finden Sie unter [Tools für Amazon Web Services](https://aws.amazon.com/tools/).

**Topics**
+ [Python und ElastiCache](ElastiCache-Getting-Started-Tutorials-Python.md)

# Python und ElastiCache
<a name="ElastiCache-Getting-Started-Tutorials-Python"></a>

In diesem Tutorial verwenden Sie das AWS SDK for Python (Boto3), um einfache Programme für die folgenden ElastiCache Operationen zu schreiben:
+  ElastiCache Für Redis OSS-Cluster erstellen (Clustermodus aktiviert und Clustermodus deaktiviert)
+ Prüfen Sie, ob Benutzer oder Benutzergruppen existieren, andernfalls erstellen Sie sie. (Diese Funktion ist mit Valkey 7.2 und höher sowie mit Redis OSS 6.0 bis 7.1 verfügbar.)
+ Verbinden mit ElastiCache
+ Führe Operationen wie das Einstellen und Abrufen von Zeichenketten, das Lesen von und Schreiben in Streams sowie das Veröffentlichen und Abonnieren von Inhalten über den Kanal aus. Pub/Sub 

Während Sie dieses Tutorial durcharbeiten, können Sie sich auf die Dokumentation zum AWS SDK für Python (Boto) beziehen. Der folgende Abschnitt ist spezifisch für ElastiCache: [ElastiCache Low-Level-Client](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/elasticache.html)

## Tutorial-Voraussetzungen
<a name="ElastiCache-Getting-Started-Tutorials-Prerquisites"></a>
+ Richten Sie einen AWS Zugriffsschlüssel ein, um den zu verwenden.AWS SDKs Weitere Informationen finden Sie unter [Einrichten ElastiCache](set-up.md).
+ Python 3.0 oder später installieren. Weitere Informationen finden Sie unter [https://www.python.org/downloads](https://www.python.org/downloads). Weiter Informationen finden Sie unter [Quickstart](https://boto3.amazonaws.com/v1/documentation/api/latest/guide/quickstart.html) in der Boto 3-Dokumentation.

**Topics**
+ [Tutorial-Voraussetzungen](#ElastiCache-Getting-Started-Tutorials-Prerquisites)
+ [Tutorial: ElastiCache Cluster und Benutzer erstellen](#ElastiCache-Getting-Started-Tutorials-Create-Cluster-and-Users)
+ [Tutorial: Verbindung herstellen mit ElastiCache](#ElastiCache-Getting-Started-Tutorials-Connecting)
+ [Verwendungsbeispiele](#ElastiCache-Getting-Started-Tutorials-Usage)

## Tutorial: ElastiCache Cluster und Benutzer erstellen
<a name="ElastiCache-Getting-Started-Tutorials-Create-Cluster-and-Users"></a>

In den folgenden Beispielen werden das boto3 SDK ElastiCache für Redis OSS-Verwaltungsvorgänge (Cluster- oder Benutzererstellung) und redis-py-cluster redis-py/ für die Datenverarbeitung verwendet.

**Topics**
+ [Erstellen Sie einen Cluster mit deaktiviertem Cluster-Modus](#ElastiCache-Getting-Started-Tutorials-Create-Cluster)
+ [Erstellen eines Clusters mit deaktivierten Cluster-Modus mit TLS und RBAC](#ElastiCache-Getting-Started-Tutorials-RBAC)
+ [Erstellen Sie einen Cluster mit aktiviertem Cluster-Modus](#ElastiCache-Getting-Started-Tutorials-Cluster-Enabled)
+ [Erstellen Sie einen Cluster mit aktiviertem Cluster-Modus mit TLS und RBAC](#ElastiCache-Getting-Started-Tutorials-Cluster-RBAC)
+ [Prüfen Sie, ob sie users/usergroup existieren, andernfalls erstellen Sie sie](#ElastiCache-Getting-Started-Tutorials-Users)

### Erstellen Sie einen Cluster mit deaktiviertem Cluster-Modus
<a name="ElastiCache-Getting-Started-Tutorials-Create-Cluster"></a>

*Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen .py ein. CreateClusterModeDisabledCluster*

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_disabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumCacheClusters=2,ReplicationGroupDescription='Sample cluster',ReplicationGroupId=None):
    """Creates an ElastiCache Cluster with cluster mode disabled

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumCacheClusters: Number of nodes in the cluster. Minimum 1 (just a primary node) and maximun 6 (1 primary and 5 replicas).
    If not specified, cluster will be created with 1 primary and 1 replica.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'

    response = client.create_replication_group(
        AutomaticFailoverEnabled=True,
        CacheNodeType=CacheNodeType,
        Engine='valkey',
        EngineVersion=EngineVersion,
        NumCacheClusters=NumCacheClusters,
        ReplicationGroupDescription=ReplicationGroupDescription,
        ReplicationGroupId=ReplicationGroupId,
        SnapshotRetentionLimit=30,
    )
    return response


if __name__ == '__main__':
    
    # Creates an ElastiCache Cluster mode disabled cluster, based on cache.m6g.large nodes, Valkey 8.0, one primary and two replicas
    elasticacheResponse = create_cluster_mode_disabled(
        #CacheNodeType='cache.m6g.large', 
        EngineVersion='8.0',
        NumCacheClusters=3,
        ReplicationGroupDescription='Valkey cluster mode disabled with replicas',
        ReplicationGroupId='valkey202104053'
        )
    
    logging.info(elasticacheResponse)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python CreateClusterModeDisabledCluster.py`

Weitere Informationen finden Sie unter [Verwaltung von Clustern in ElastiCache](Clusters.md).

### Erstellen eines Clusters mit deaktivierten Cluster-Modus mit TLS und RBAC
<a name="ElastiCache-Getting-Started-Tutorials-RBAC"></a>

Um die Sicherheit zu gewährleisten, können Sie Transport Layer Security (TLS) und rollenbasierte Zugriffssteuerung (RBAC) beim Erstellen eines Clusters mit deaktiviertem Cluster-Modus verwenden. Im Gegensatz zu Valkey oder Redis OSS AUTH, bei denen alle authentifizierten Clients vollen Zugriff auf die Replikationsgruppe haben, wenn ihr Token authentifiziert ist, können Sie mit RBAC den Clusterzugriff über Benutzergruppen steuern. Diese Benutzergruppen dienen dazu, den Zugriff auf Replikationsgruppen zu organisieren. Weitere Informationen finden Sie unter [Rollenbasierte Zugriffskontrolle (RBAC)](Clusters.RBAC.md).

*Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen RBAC.py ein. ClusterModeDisabledWith*

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_disabled_rbac(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumCacheClusters=2,ReplicationGroupDescription='Sample cluster',ReplicationGroupId=None, UserGroupIds=None, SecurityGroupIds=None,CacheSubnetGroupName=None):
    """Creates an ElastiCache Cluster with cluster mode disabled and RBAC

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumCacheClusters: Number of nodes in the cluster. Minimum 1 (just a primary node) and maximun 6 (1 primary and 5 replicas).
    If not specified, cluster will be created with 1 primary and 1 replica.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Mandatory name for the cluster.
    :param UserGroupIds: The ID of the user group to be assigned to the cluster.
    :param SecurityGroupIds: List of security groups to be assigned. If not defined, default will be used
    :param CacheSubnetGroupName: subnet group where the cluster will be placed. If not defined, default will be used.
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return {'Error': 'ReplicationGroupId parameter is required'}
    elif not isinstance(UserGroupIds,(list)):
        return {'Error': 'UserGroupIds parameter is required and must be a list'}

    params={'AutomaticFailoverEnabled': True, 
            'CacheNodeType': CacheNodeType, 
            'Engine': 'valkey', 
            'EngineVersion': EngineVersion, 
            'NumCacheClusters': NumCacheClusters, 
            'ReplicationGroupDescription': ReplicationGroupDescription, 
            'ReplicationGroupId': ReplicationGroupId, 
            'SnapshotRetentionLimit': 30, 
            'TransitEncryptionEnabled': True, 
            'UserGroupIds':UserGroupIds
        }

    # defaults will be used if CacheSubnetGroupName or SecurityGroups are not explicit.
    if isinstance(SecurityGroupIds,(list)):
        params.update({'SecurityGroupIds':SecurityGroupIds})
    if CacheSubnetGroupName:
        params.update({'CacheSubnetGroupName':CacheSubnetGroupName})

    response = client.create_replication_group(**params)
    return response

if __name__ == '__main__':

    # Creates an ElastiCache Cluster mode disabled cluster, based on cache.m6g.large nodes, Valkey 8.0, one primary and two replicas.
    # Assigns the existent user group "mygroup" for RBAC authentication
   
    response=create_cluster_mode_disabled_rbac(
        CacheNodeType='cache.m6g.large',
        EngineVersion='8.0',
        NumCacheClusters=3,
        ReplicationGroupDescription='Valkey cluster mode disabled with replicas',
        ReplicationGroupId='valkey202104',
        UserGroupIds=[
            'mygroup'
        ],
        SecurityGroupIds=[
            'sg-7cc73803'
        ],
        CacheSubnetGroupName='default'
    )

    logging.info(response)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ClusterModeDisabledWithRBAC.py`

Weitere Informationen finden Sie unter [Verwaltung von Clustern in ElastiCache](Clusters.md).

### Erstellen Sie einen Cluster mit aktiviertem Cluster-Modus
<a name="ElastiCache-Getting-Started-Tutorials-Cluster-Enabled"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen *ClusterModeEnabled.py* ein.

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_enabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumNodeGroups=1,ReplicasPerNodeGroup=1, ReplicationGroupDescription='Sample cache with cluster mode enabled',ReplicationGroupId=None):
    """Creates an ElastiCache Cluster with cluster mode enabled

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumNodeGroups: Number of shards in the cluster. Minimum 1 and maximun 90.
    If not specified, cluster will be created with 1 shard.
    :param ReplicasPerNodeGroup: Number of replicas per shard. If not specified 1 replica per shard will be created.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'
    
    response = client.create_replication_group(
        AutomaticFailoverEnabled=True,
        CacheNodeType=CacheNodeType,
        Engine='valkey',
        EngineVersion=EngineVersion,
        ReplicationGroupDescription=ReplicationGroupDescription,
        ReplicationGroupId=ReplicationGroupId,
    #   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary node (implicit) and 2 replicas (replicasPerNodeGroup)
        NumNodeGroups=NumNodeGroups,
        ReplicasPerNodeGroup=ReplicasPerNodeGroup,
        CacheParameterGroupName='default.valkey7.2.cluster.on'
    )

    return response


# Creates a cluster mode enabled 
response = create_cluster_mode_enabled(
    CacheNodeType='cache.m6g.large',
    EngineVersion='6.0',
    ReplicationGroupDescription='Valkey cluster mode enabled with replicas',
    ReplicationGroupId='valkey20210',
#   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary (implicit) and 2 replicas (replicasPerNodeGroup)
    NumNodeGroups=2,
    ReplicasPerNodeGroup=1,
)

logging.info(response)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ClusterModeEnabled.py`

Weitere Informationen finden Sie unter [Verwaltung von Clustern in ElastiCache](Clusters.md).

### Erstellen Sie einen Cluster mit aktiviertem Cluster-Modus mit TLS und RBAC
<a name="ElastiCache-Getting-Started-Tutorials-Cluster-RBAC"></a>

Um die Sicherheit zu gewährleisten, können Sie Transport Layer Security (TLS) und rollenbasierte Zugriffssteuerung (RBAC) beim Erstellen eines Clusters mit aktiviertem Cluster-Modus verwenden. Im Gegensatz zu Valkey oder Redis OSS AUTH, bei denen alle authentifizierten Clients vollen Zugriff auf die Replikationsgruppe haben, wenn ihr Token authentifiziert ist, können Sie mit RBAC den Clusterzugriff über Benutzergruppen steuern. Diese Benutzergruppen dienen dazu, den Zugriff auf Replikationsgruppen zu organisieren. Weitere Informationen finden Sie unter [Rollenbasierte Zugriffskontrolle (RBAC)](Clusters.RBAC.md).

*Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen RBAC.py ein. ClusterModeEnabledWith*

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def create_cluster_mode_enabled(CacheNodeType='cache.t3.small',EngineVersion='6.0',NumNodeGroups=1,ReplicasPerNodeGroup=1, ReplicationGroupDescription='Sample cache with cluster mode enabled',ReplicationGroupId=None,UserGroupIds=None, SecurityGroupIds=None,CacheSubnetGroupName=None,CacheParameterGroupName='default.valkey7.2.cluster.on'):
    """Creates an ElastiCache Cluster with cluster mode enabled and RBAC

    Returns a dictionary with the API response

    :param CacheNodeType: Node type used on the cluster. If not specified, cache.t3.small will be used
    Refer to https://docs.aws.amazon.com/AmazonElastiCache/latest/dg/CacheNodes.SupportedTypes.html for supported node types
    :param EngineVersion: Engine version to be used. If not specified, latest will be used.
    :param NumNodeGroups: Number of shards in the cluster. Minimum 1 and maximun 90.
    If not specified, cluster will be created with 1 shard.
    :param ReplicasPerNodeGroup: Number of replicas per shard. If not specified 1 replica per shard will be created.
    :param ReplicationGroupDescription: Description for the cluster.
    :param ReplicationGroupId: Name for the cluster.
    :param CacheParameterGroupName: Parameter group to be used. Must be compatible with the engine version and cluster mode enabled.
    :return: dictionary with the API results

    """
    if not ReplicationGroupId:
        return 'ReplicationGroupId parameter is required'
    elif not isinstance(UserGroupIds,(list)):
        return {'Error': 'UserGroupIds parameter is required and must be a list'}

    params={'AutomaticFailoverEnabled': True, 
            'CacheNodeType': CacheNodeType, 
            'Engine': 'valkey', 
            'EngineVersion': EngineVersion, 
            'ReplicationGroupDescription': ReplicationGroupDescription, 
            'ReplicationGroupId': ReplicationGroupId, 
            'SnapshotRetentionLimit': 30, 
            'TransitEncryptionEnabled': True, 
            'UserGroupIds':UserGroupIds,
            'NumNodeGroups': NumNodeGroups,
            'ReplicasPerNodeGroup': ReplicasPerNodeGroup,
            'CacheParameterGroupName': CacheParameterGroupName
        }

    # defaults will be used if CacheSubnetGroupName or SecurityGroups are not explicit.
    if isinstance(SecurityGroupIds,(list)):
        params.update({'SecurityGroupIds':SecurityGroupIds})
    if CacheSubnetGroupName:
        params.update({'CacheSubnetGroupName':CacheSubnetGroupName})

    response = client.create_replication_group(**params)
    return response

if __name__ == '__main__':
    # Creates a cluster mode enabled cluster
    response = create_cluster_mode_enabled(
        CacheNodeType='cache.m6g.large',
        EngineVersion='7.2',
        ReplicationGroupDescription='Valkey cluster mode enabled with replicas',
        ReplicationGroupId='valkey2021',
    #   Creates a cluster mode enabled cluster with 1 shard(NumNodeGroups), 1 primary (implicit) and 2 replicas (replicasPerNodeGroup)
        NumNodeGroups=2,
        ReplicasPerNodeGroup=1,
        UserGroupIds=[
            'mygroup'
        ],
        SecurityGroupIds=[
            'sg-7cc73803'
        ],
        CacheSubnetGroupName='default'

    )
    
    logging.info(response)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ClusterModeEnabledWithRBAC.py`

Weitere Informationen finden Sie unter [Verwaltung von Clustern in ElastiCache](Clusters.md).

### Prüfen Sie, ob sie users/usergroup existieren, andernfalls erstellen Sie sie
<a name="ElastiCache-Getting-Started-Tutorials-Users"></a>

Mithilfe von RBAC erstellen Sie Benutzer und weisen ihnen spezifische Berechtigungen zu, indem Sie eine Zugriffszeichenfolge verwenden, wie im Folgenden beschrieben. Sie weisen die Benutzer Benutzergruppen zu, denen eine bestimmte Rolle zugewiesen ist (Administratoren, Personalabteilung), die dann einer oder mehreren ElastiCache Redis OSS-Replikationsgruppen zugewiesen werden. Auf diese Weise können Sie Sicherheitsgrenzen zwischen Clients einrichten, die dieselbe Valkey- oder Redis OSS-Replikationsgruppe (n) verwenden, und verhindern, dass Clients gegenseitig auf die Daten zugreifen. Weitere Informationen finden Sie unter [Rollenbasierte Zugriffskontrolle (RBAC)](Clusters.RBAC.md).

*Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen UserAndUserGroups .py ein.* Aktualisieren Sie den Mechanismus für die Bereitstellung von Anmeldeinformationen. In diesem Beispiel werden Anmeldeinformationen als ersetzbar angezeigt und ihnen wird ein nicht deklariertes Element zugewiesen. Vermeiden Sie die Hartkodierung von Anmeldeinformationen.

In diesem Beispiel wird eine Zugriffszeichenfolge mit den Berechtigungen für den Benutzer verwendet. Weitere Informationen zu Zugriffszeichenfolgen finden Sie unter[Spezifizieren von Berechtigungen mithilfe einer Zugriffszeichenfolge](Clusters.RBAC.md#Access-string).

```
import boto3
import logging

logging.basicConfig(level=logging.INFO)
client = boto3.client('elasticache')

def check_user_exists(UserId):
    """Checks if UserId exists

    Returns True if UserId exists, otherwise False
    :param UserId: ElastiCache User ID
    :return: True|False
    """
    try:
        response = client.describe_users(
            UserId=UserId,
        )
        if response['Users'][0]['UserId'].lower() == UserId.lower():
            return True
    except Exception as e:
        if e.response['Error']['Code'] == 'UserNotFound':
            logging.info(e.response['Error'])
            return False
        else:
            raise

def check_group_exists(UserGroupId):
    """Checks if UserGroupID exists

    Returns True if Group ID exists, otherwise False
    :param UserGroupId: ElastiCache User ID
    :return: True|False
    """

    try:
        response = client.describe_user_groups(
            UserGroupId=UserGroupId
        )
        if response['UserGroups'][0]['UserGroupId'].lower() == UserGroupId.lower():
            return True
    except Exception as e:
        if e.response['Error']['Code'] == 'UserGroupNotFound':
            logging.info(e.response['Error'])
            return False
        else:
            raise

def create_user(UserId=None,UserName=None,Password=None,AccessString=None):
    """Creates a new user

    Returns the ARN for the newly created user or the error message
    :param UserId: ElastiCache user ID. User IDs must be unique
    :param UserName: ElastiCache user name. ElastiCache allows multiple users with the same name as long as the associated user ID is unique.
    :param Password: Password for user. Must have at least 16 chars.
    :param AccessString: Access string with the permissions for the user. 
    :return: user ARN
    """
    try:
        response = client.create_user(
            UserId=UserId,
            UserName=UserName,
            Engine='Redis',
            Passwords=[Password],
            AccessString=AccessString,
            NoPasswordRequired=False
        )
        return response['ARN']
    except Exception as e:
        logging.info(e.response['Error'])
        return e.response['Error']

def create_group(UserGroupId=None, UserIds=None):
    """Creates a new group.
    A default user is required (mandatory) and should be specified in the UserIds list

    Return: Group ARN
    :param UserIds: List with user IDs to be associated with the new group. A default user is required
    :param UserGroupId: The ID (name) for the group
    :return: Group ARN
    """
    try:
        response = client.create_user_group(
            UserGroupId=UserGroupId,
            Engine='Redis',
            UserIds=UserIds
        )
        return response['ARN']
    except Exception as e:
        logging.info(e.response['Error'])


if __name__ == '__main__':
    
    groupName='mygroup2'
    userName = 'myuser2'
    userId=groupName+'-'+userName

    # Creates a new user if the user ID does not exist.
    for tmpUserId,tmpUserName in [ (userId,userName), (groupName+'-default','default')]:
        if not check_user_exists(tmpUserId):
            response=create_user(UserId=tmpUserId, UserName=EXAMPLE,Password=EXAMPLE,AccessString='on ~* +@all')
            logging.info(response)
        # assigns the new user ID to the user group
    if not check_group_exists(groupName):
        UserIds = [ userId , groupName+'-default']
        response=create_group(UserGroupId=groupName,UserIds=UserIds)
        logging.info(response)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python UserAndUserGroups.py`

## Tutorial: Verbindung herstellen mit ElastiCache
<a name="ElastiCache-Getting-Started-Tutorials-Connecting"></a>

In den folgenden Beispielen wird der Valkey- oder Redis OSS-Client verwendet, um eine Verbindung herzustellen. ElastiCache

**Topics**
+ [Herstellen einer Verbindung zu einem Cluster mit deaktiviertem Cluster-Modus](#ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-disabled)
+ [Herstellen einer Verbindung zu einem Cluster mit aktiviertem Cluster-Modus](#ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-enabled)

### Herstellen einer Verbindung zu einem Cluster mit deaktiviertem Cluster-Modus
<a name="ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-disabled"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei namens *ConnectClusterModeDisabled.py* ein. Aktualisieren Sie den Mechanismus für die Bereitstellung von Anmeldeinformationen. In diesem Beispiel werden Anmeldeinformationen als ersetzbar angezeigt und ihnen wird ein nicht deklariertes Element zugewiesen. Vermeiden Sie die Hartkodierung von Anmeldeinformationen.

```
from redis import Redis
import logging

logging.basicConfig(level=logging.INFO)
redis = Redis(host='primary.xxx.yyyyyy.zzz1.cache.amazonaws.com', port=6379, decode_responses=True, ssl=True, username=example, password=EXAMPLE)

if redis.ping():
    logging.info("Connected to Redis")
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ConnectClusterModeDisabled.py`

### Herstellen einer Verbindung zu einem Cluster mit aktiviertem Cluster-Modus
<a name="ElastiCache-Getting-Started-Tutorials-Connecting-cluster-mode-enabled"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei mit dem Namen *ConnectClusterModeEnabled.py* ein.

```
from rediscluster import RedisCluster
import logging

logging.basicConfig(level=logging.INFO)
redis = RedisCluster(startup_nodes=[{"host": "xxx.yyy.clustercfg.zzz1.cache.amazonaws.com","port": "6379"}], decode_responses=True,skip_full_coverage_check=True)

if redis.ping():
    logging.info("Connected to Redis")
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ConnectClusterModeEnabled.py`

## Verwendungsbeispiele
<a name="ElastiCache-Getting-Started-Tutorials-Usage"></a>

In den folgenden Beispielen wird das Boto3-SDK für die Arbeit mit ElastiCache ElastiCache Redis OSS verwendet.

**Topics**
+ [Zeichenfolgen festlegen und abrufen](#ElastiCache-Getting-Started-Tutorials-set-strings)
+ [Festlegen und Abrufen eines Hash mit mehreren Elementen](#ElastiCache-Getting-Started-Tutorials-set-hash)
+ [Von einem Kanal aus veröffentlichen (schreiben) und abonnieren (lesen) Pub/Sub](#ElastiCache-Getting-Started-Tutorials-pub-sub)
+ [Schreiben und Lesen aus einem Stream](#ElastiCache-Getting-Started-Tutorials-read-write-stream)

### Zeichenfolgen festlegen und abrufen
<a name="ElastiCache-Getting-Started-Tutorials-set-strings"></a>

*Kopieren Sie das folgende Programm und fügen Sie es in eine Datei namens .py ein. SetAndGetStrings*

```
import time
import logging
logging.basicConfig(level=logging.INFO,format='%(asctime)s: %(message)s')

keyName='mykey'
currTime=time.ctime(time.time())

# Set the key 'mykey' with the current date and time as value. 
# The Key will expire and removed from cache in 60 seconds.
redis.set(keyName, currTime, ex=60)

# Sleep just for better illustration of TTL (expiration) value
time.sleep(5)

# Retrieve the key value and current TTL
keyValue=redis.get(keyName)
keyTTL=redis.ttl(keyName)

logging.info("Key {} was set at {} and has {} seconds until expired".format(keyName, keyValue, keyTTL))
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python SetAndGetStrings.py`

### Festlegen und Abrufen eines Hash mit mehreren Elementen
<a name="ElastiCache-Getting-Started-Tutorials-set-hash"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei namens *SetAndGetHash.py* ein.

```
import logging
import time

logging.basicConfig(level=logging.INFO,format='%(asctime)s: %(message)s')

keyName='mykey'
keyValues={'datetime': time.ctime(time.time()), 'epochtime': time.time()}

# Set the hash 'mykey' with the current date and time in human readable format (datetime field) and epoch number (epochtime field). 
redis.hset(keyName, mapping=keyValues)

# Set the key to expire and removed from cache in 60 seconds.
redis.expire(keyName, 60)

# Sleep just for better illustration of TTL (expiration) value
time.sleep(5)

# Retrieves all the fields and current TTL
keyValues=redis.hgetall(keyName)
keyTTL=redis.ttl(keyName)

logging.info("Key {} was set at {} and has {} seconds until expired".format(keyName, keyValues, keyTTL))
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python SetAndGetHash.py`

### Von einem Kanal aus veröffentlichen (schreiben) und abonnieren (lesen) Pub/Sub
<a name="ElastiCache-Getting-Started-Tutorials-pub-sub"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei namens *PubAndSub.py* ein.

```
import logging
import time

def handlerFunction(message):
    """Prints message got from PubSub channel to the log output

    Return None
    :param message: message to log
    """
    logging.info(message)

logging.basicConfig(level=logging.INFO)
redis = Redis(host="redis202104053.tihewd.ng.0001.use1.cache.amazonaws.com", port=6379, decode_responses=True)


# Creates the subscriber connection on "mychannel"
subscriber = redis.pubsub()
subscriber.subscribe(**{'mychannel': handlerFunction})

# Creates a new thread to watch for messages while the main process continues with its routines
thread = subscriber.run_in_thread(sleep_time=0.01)

# Creates publisher connection on "mychannel"
redis.publish('mychannel', 'My message')

# Publishes several messages. Subscriber thread will read and print on log.
while True:
    redis.publish('mychannel',time.ctime(time.time()))
    time.sleep(1)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python PubAndSub.py`

### Schreiben und Lesen aus einem Stream
<a name="ElastiCache-Getting-Started-Tutorials-read-write-stream"></a>

Kopieren Sie das folgende Programm und fügen Sie es in eine Datei namens *ReadWriteStream.py* ein.

```
from redis import Redis
import redis.exceptions as exceptions
import logging
import time
import threading

logging.basicConfig(level=logging.INFO)

def writeMessage(streamName):
    """Starts a loop writting the current time and thread name to 'streamName'

    :param streamName: Stream (key) name to write messages.
    """
    fieldsDict={'writerId':threading.currentThread().getName(),'myvalue':None}
    while True:
        fieldsDict['myvalue'] = time.ctime(time.time())
        redis.xadd(streamName,fieldsDict)
        time.sleep(1)

def readMessage(groupName=None,streamName=None):
    """Starts a loop reading from 'streamName'
    Multiple threads will read from the same stream consumer group. Consumer group is used to coordinate data distribution.
    Once a thread acknowleges the message, it won't be provided again. If message wasn't acknowledged, it can be served to another thread.

    :param groupName: stream group were multiple threads will read.
    :param streamName: Stream (key) name where messages will be read.
    """

    readerID=threading.currentThread().getName()
    while True:
        try:
            # Check if the stream has any message
            if redis.xlen(streamName)>0:
                # Check if if the messages are new (not acknowledged) or not (already processed)
                streamData=redis.xreadgroup(groupName,readerID,{streamName:'>'},count=1)
                if len(streamData) > 0:
                    msgId,message = streamData[0][1][0]
                    logging.info("{}: Got {} from ID {}".format(readerID,message,msgId))
                    #Do some processing here. If the message has been processed sucessfuly, acknowledge it and (optional) delete the message.
                    redis.xack(streamName,groupName,msgId)
                    logging.info("Stream message ID {} read and processed successfuly by {}".format(msgId,readerID))
                    redis.xdel(streamName,msgId)
            else:
                pass
        except:
            raise
            
        time.sleep(0.5)

# Creates the stream 'mystream' and consumer group 'myworkergroup' where multiple threads will write/read.
try:
    redis.xgroup_create('mystream','myworkergroup',mkstream=True)
except exceptions.ResponseError as e:
    logging.info("Consumer group already exists. Will continue despite the error: {}".format(e))
except:
    raise

# Starts 5 writer threads.
for writer_no in range(5):
    writerThread = threading.Thread(target=writeMessage, name='writer-'+str(writer_no), args=('mystream',),daemon=True)
    writerThread.start()

# Starts 10 reader threads
for reader_no in range(10):
    readerThread = threading.Thread(target=readMessage, name='reader-'+str(reader_no), args=('myworkergroup','mystream',),daemon=True)
    readerThread.daemon = True
    readerThread.start()

# Keep the code running for 30 seconds
time.sleep(30)
```

Geben Sie den folgenden Befehl ein, um das Programm auszuführen:

 `python ReadWriteStream.py`