Best Practices for Using Alibaba Cloud Redis: Key Design, Command Usage, Client Integration, and Tools
This article outlines comprehensive development guidelines for Alibaba Cloud Redis, covering readable and concise key naming, avoiding big keys, proper command selection, safe client usage with connection pools, eviction policies, and practical code examples for deleting large hashes, lists, sets, and sorted sets.
This article introduces the development specifications for using Alibaba Cloud Redis, aiming to reduce common pitfalls during Redis usage.
1. Key Design
1.1 Key Naming
Use a business or database prefix to avoid collisions, separated by colons, e.g., ugc:video:1 . Keep keys readable and manageable.
Readability and Manageability
Prefix with business name and separate parts with colons, such as business:table:id .
Simplicity
Control key length while preserving semantics, e.g., user:{uid}:friends:messages:{mid} can be shortened to u:{uid}:fr:m:{mid} .
Avoid Special Characters
Do not include spaces, line breaks, quotes, or escape characters in keys.
1.2 Value Design
Avoid Big Keys
Limit string values to 10KB and keep hash/list/set/zset element counts below 5,000 to prevent network congestion and slow queries.
Select Appropriate Data Types
Choose data structures that balance memory encoding and performance, e.g., using HMSET for user objects instead of multiple SET commands.
Control Key Lifecycle
Set expiration with EXPIRE (preferably staggered) and monitor idle time for non‑expiring keys.
2. Command Usage
2.1 Pay Attention to O(N) Commands
Commands like HGETALL , LRANGE , SMEMBERS , ZRANGE are acceptable if the size (N) is known; otherwise use HSCAN , SSCAN , ZSCAN for incremental iteration.
2.2 Disable Dangerous Commands
Prohibit KEYS , FLUSHALL , FLUSHDB in production, using Redis rename or scan‑based alternatives.
2.3 Use SELECT Sparingly
Multiple logical databases are weakly supported and can cause interference; prefer separate Redis instances.
2.4 Batch Operations
Native batch commands: MGET , MSET .
Non‑native batch: use pipelines for higher throughput.
Limit batch size (e.g., ≤500 elements) based on element byte size.
2.5 Avoid Excessive Transactions
Redis transactions lack rollback and require all keys in a transaction to reside in the same slot when using clusters.
2.6 Lua Scripts in Cluster
All keys must be passed via the KEYS array and reside in the same slot; otherwise the script fails.
2.7 Monitor Command
Use MONITOR only when necessary and avoid long‑running sessions.
3. Client Usage
3.1 Separate Applications
Do not share a single Redis instance across unrelated services; isolate data via dedicated instances or service‑oriented designs.
3.2 Use Connection Pools
Example (Java/Jedis):
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
// execute commands
jedis.executeCommand();
} catch (Exception e) {
logger.error("op key {} error: ", key, e);
} finally {
if (jedis != null) {
jedis.close(); // returns to pool
}
}3.3 Add Circuit Breaker
Integrate a circuit‑breaker (e.g., Netflix Hystrix) for high‑concurrency scenarios.
3.4 Secure Connections
Configure strong passwords and enable SSL if needed (supported by Alibaba Cloud Redis).
3.5 Eviction Policies
Choose an appropriate maxmemory-policy (e.g., volatile-lru , allkeys-lru , noeviction ) and set expiration times according to business needs.
4. Related Tools
Data synchronization: redis-port .
Big‑key search tools.
Hot‑key detection (e.g., redis-faina ).
5. Deleting Big Keys
Use pipelines for faster deletion. Redis 4.0 supports asynchronous key deletion.
5.1 Delete Large Hashes
public void delBigHash(String host, int port, String password, String bigHashKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult
> scanResult = jedis.hscan(bigHashKey, cursor, scanParams);
List
> entryList = scanResult.getResult();
if (entryList != null && !entryList.isEmpty()) {
for (Entry
entry : entryList) {
jedis.hdel(bigHashKey, entry.getKey());
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
jedis.del(bigHashKey);
}5.2 Delete Large Lists
public void delBigList(String host, int port, String password, String bigListKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
long llen = jedis.llen(bigListKey);
int counter = 0;
int left = 100;
while (counter < llen) {
// Trim 100 elements from the left each iteration
jedis.ltrim(bigListKey, left, llen);
counter = left;
}
jedis.del(bigListKey);
}5.3 Delete Large Sets
public void delBigSet(String host, int port, String password, String bigSetKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult
scanResult = jedis.sscan(bigSetKey, cursor, scanParams);
List
memberList = scanResult.getResult();
if (memberList != null && !memberList.isEmpty()) {
for (String member : memberList) {
jedis.srem(bigSetKey, member);
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
jedis.del(bigSetKey);
}5.4 Delete Large Sorted Sets
public void delBigZset(String host, int port, String password, String bigZsetKey) {
Jedis jedis = new Jedis(host, port);
if (password != null && !"".equals(password)) {
jedis.auth(password);
}
ScanParams scanParams = new ScanParams().count(100);
String cursor = "0";
do {
ScanResult
scanResult = jedis.zscan(bigZsetKey, cursor, scanParams);
List
tupleList = scanResult.getResult();
if (tupleList != null && !tupleList.isEmpty()) {
for (Tuple tuple : tupleList) {
jedis.zrem(bigZsetKey, tuple.getElement());
}
}
cursor = scanResult.getStringCursor();
} while (!"0".equals(cursor));
jedis.del(bigZsetKey);
}By following these guidelines, developers can design efficient keys, use commands safely, manage client connections properly, and handle big‑key deletions without causing performance degradation.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.