Skip to content
Redis

Strings & Counters

Set, get, increment, and expire string values.

By EZ4Code Team
stringcountercache

Code

# Basic set/get with expiration
SET session:abc "user-data" EX 3600
GET session:abc
TTL session:abc
PERSIST session:abc

# Conditional set
SET cache:lock "1" NX EX 10

# Counters
INCR page:home:views
INCRBY page:home:views 5
DECR stock:item:42
SET stock:item:42 100

# Append and substring
APPEND greeting "World"
STRLEN greeting
GETRANGE greeting 0 4

# MGET for batch reads
MGET k1 k2 k3

Explanation

Redis strings are binary-safe byte sequences that can hold values up to 512MB and serve as counters via INCR/DECR. The EX flag sets a TTL in seconds, and NX makes SET conditional on the key not existing, perfect for distributed locks. MGET batches multiple reads in a single round-trip.

More Redis Snippets