Databases 9 min read

Redis for DBAs: Quick Installation, Core Commands, Caching Design Patterns, and High‑Concurrency Practices

This article explains why Redis is becoming a DBA's favorite, provides a five‑minute installation guide, essential commands, cache‑design pitfalls and solutions, explores Redis data structures with Java examples, demonstrates distributed locking and flash‑sale implementations, and covers clustering, backup, monitoring, and performance tuning.

IT Xianyu
IT Xianyu
IT Xianyu
Redis for DBAs: Quick Installation, Core Commands, Caching Design Patterns, and High‑Concurrency Practices

Redis is gaining popularity among DBAs because its in‑memory read/write speed can handle high‑concurrency scenarios that traditional relational databases struggle with.

Installation (Aimalinux version)

# 下载+编译安装
wget http://download.redis.io/releases/redis-7.0.0.tar.gz

tar xzf redis-7.0.0.tar.gz

cd redis-7.0.0

make && make install

# 启动Redis服务(后台运行)
nohup src/redis-server &

Default port is 6379; remember to open the firewall.

Essential Redis commands

# 存数据(String类型)
SET user:1001 "张三"

# 取数据
GET user:1001

# 存哈希表(适合存对象)
HSET product:8888 name "手机" price 3999

# 设置过期时间(30秒后自动删除)
EXPIRE product:8888 30

# 查看内存信息
INFO memory

Cache design pitfalls and solutions

Cache penetration : use empty‑value caching or Bloom filters.

Cache avalanche : assign random expiration times, e.g., 300 ± 60 seconds .

Hot key overload : combine local cache (Guava) with Redis replicas.

// Java example: cache empty value to prevent penetration
public String getProduct(String id) {
    String key = "product:" + id;
    String value = redis.get(key);
    if (value == null) {
        value = db.query("SELECT * FROM product WHERE id=?", id);
        if (value == null) {
            redis.setex(key, 300, ""); // cache empty for 5 minutes
        } else {
            redis.setex(key, 3600, value); // cache normal data for 1 hour
        }
    }
    return value;
}

Redis data structures (Java examples)

String – store numbers, JSON, or binary data. Jedis jedis = new Jedis("localhost"); jedis.set("user:1001", "{'name':'老王','age':28}"); String user = jedis.get("user:1001");

Hash – store object attributes. Map product = new HashMap<>(); product.put("price", "99.99"); product.put("stock", "1000"); jedis.hset("product:888", product);

List – implement queues such as order processing. jedis.lpush("order:queue", "order1001", "order1002"); String latestOrder = jedis.rpop("order:queue");

Set – deduplication and UV statistics. redis-cli SADD active_users:20240507 "user1001" "user1002" redis-cli SCARD active_users:20240507

ZSet – ranking, e.g., game leaderboards. jedis.zadd("game_rank", 5000, "player1"); jedis.zadd("game_rank", 8000, "player2"); Set top3 = jedis.zrevrange("game_rank", 0, 2);

High‑concurrency patterns (Java + Redis)

1. Distributed lock using SETNX (or SET … NX EX ) to prevent overselling.

public boolean lock(String key, String value, int expireTime) {
    String result = jedis.set(key, value, "NX", "EX", expireTime);
    return "OK".equals(result);
}

// Unlock with Lua script for atomicity
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
jedis.eval(script, Collections.singletonList(key), Collections.singletonList(value));

2. Flash‑sale (秒杀) using a Lua script to atomically decrement stock.

-- Lua script (atomic stock decrement)
local stock = tonumber(redis.call('GET', KEYS[1]))
if stock > 0 then
    redis.call('DECR', KEYS[1])
    return 1   -- success
else
    return 0   -- failure
end

Pre‑warm stock: SET stock:1001 1000 .

Redis cluster deployment

1. Master‑slave replication (one master, two slaves) – configure redis.conf with bind 0.0.0.0 , port 6379 , and replicaof for slaves.

2. Sentinel for automatic failover – sentinel.conf example:

sentinel monitor mymaster
6379 2
sentinel down-after-milliseconds mymaster 5000
sentinel failover-timeout mymaster 60000

3. Cluster mode for sharding – create a 6‑node (3 master, 3 replica) cluster:

redis-cli --cluster create node1:6379 node2:6379 node3:6379 node4:6379 node5:6379 node6:6379 --cluster-replicas 1

Operations essentials

Persistence: RDB snapshots and AOF logs (enable with appendonly yes ).

Monitoring: redis-cli info stats for ops/sec, redis-cli info memory for memory usage.

Connection pool tuning (Java):

JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(100); // max connections
config.setMaxIdle(20);   // max idle
JedisPool pool = new JedisPool(config, "redis-host", 6379);

Mastering Redis enables DBAs and developers to dramatically improve database performance and handle high‑traffic workloads.

JavaperformancedatabaseRedisCachingClusterDistributed Lock
IT Xianyu
Written by

IT Xianyu

We share common IT technologies (Java, Web, SQL, etc.) and practical applications of emerging software development techniques. New articles are posted daily. Follow IT Xianyu to stay ahead in tech. The IT Xianyu series is being regularly updated.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.