Spring Boot Redis-Template 调用 HMGET 等原始命令

问题描述 投票:0回答:1

Redis-Template 具有支持 HMGET 命令的方法。 我可以使用 Redis-Template 中的哪种方法来运行此命令“HMGET KEY field1 field2”

另外我们如何通过Redis-Template运行相同的命令?,所以在不使用预定义方法的情况下,我直接想通过方法运行上述/任何命令,我们对此是否支持。

spring spring-boot redis spring-data-redis
1个回答
0
投票

在 Redis-Template 中,有一个名为

opsForHash()
的方法用于
HASH
数据结构,此类方法是使用 Redis 命令的推荐方法。

但是,如果你真的想使用“原始”命令,你可以使用

connection.execute()
,这里有一个例子:

@Component
public class RedisDemo {
    private final RedisTemplate<String, String> redisTemplate;

    @Autowired
    public RedisDemo(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    // This method can execute any command
    public Object executeCommand(String command, byte[]... parts) {
        return redisTemplate.execute(connection ->
             connection.execute(command, parts),
             true
        );
    }
}

调用该方法:

redisDemo.executeCommand(
   "HMGET", 
   "test".getBytes(), 
   "field1".getBytes(), 
   "field1".getBytes()
);

这里只是为了比较,这里是与

opsForHash()
的示例:

public List<Object> callHMGet() {
    return redisTemplate.opsForHash().multiGet(
        "test", 
        List.of("field1", "field2")
    );
}
© www.soinside.com 2019 - 2024. All rights reserved.