[hiredis] Use the SELECT command to switch the Redis database and return "ERR unknown command SELECT"

overview

Because of the requirements of the program architecture, data stored in Redis needs to be divided into different databases. The Redis operation library uses hiredis

environmental information

Server: Two Linux servers
Redis version: 3.2.9, configured with master-slave mode
Development language: C/C++

question

The calling code is as follows (error example)

redisContext *c;
...
char buf[32] = {
    
    0};
sprintf(buf,"select %d", ind);
redisReply *reply = static_cast<redisReply *>(redisCommand(c, "%s", buf));
...

It is found that the above code is executed, and only "ERR unknown command 'select 1'" will be returned.

After testing, it is found that as long as it is in the form of command + parameter (KEYS\GET\SET, etc.), the following code needs to be used to get the result we want. For a single command (INFO\ROLE, etc.), the above code is inverted no problem.

redisContext *c;
...
redisReply *reply = static_cast<redisReply *>(redisCommand(c, "select %d", ind));

in conclusion

The redisCommand function encapsulates "%s" with single quotes into a whole command, which causes the SELECT 1 command to be regarded as 'SELECT 1' when Redis interprets it, which leads to an Err unknown command error, but the command without parameters , 'INFO' is still INFO after interpretation, so commands without parameters can be recognized and executed successfully.
As for the "%s" parameter, the reason why the redisCommand function automatically adds single quotes is to avoid grammatical errors caused by characters such as spaces in the string.

For example:

localhost:6379>set TEXT '1 2 3'
OK
localhost:6379>get TEXT
"1 2 3"
localhost:6379>set TEXT 1 2 
(error) ERR syntax error

reference link

ERR unknown command SELECT, with args beginning with: 2 #1991

Guess you like

Origin blog.csdn.net/qq_38189542/article/details/129110654