Spring Redis数据存储库:立即通过ID获取多个哈希值

时间:2018-05-31 15:13:57

标签: java spring spring-boot redis spring-data-redis

问题

有没有办法使用Spring Data Redis'存储库一次检索多个哈希值?

我的代码不起作用:

@RedisHash("Message")
public class Message implements Serializable {

    @Id
    private String id;
    private String text;
    private LocalDateTime posted;
    private Integer upvotes;
    private String authorId;
}

@Repository
public interface MessageRepository extends CrudRepository<Message, String> {
    // Got: IN (1): [IsIn, In]is not supported for redis query derivation
    Set<Message> getByIdIn(Set<String> ids); 
}

解决方法

目前我正在使用RestTemplate#executePipelined,但我发现这种方法很麻烦:

public Set<Message> getMessagesById(Set<String> ids) {

        // I had to implement custom mapper since BeanUtilsHashMapper fails on LocalDateTime deserialization from String
        HashMapper<Message, String, String> mapper = new DTOConverter<>(Message.class);

        List<Object> messages = template.executePipelined((RedisCallback<Object>) connection -> {
            StringRedisConnection conn = (StringRedisConnection) connection;
            ids.stream()
                    .map(id -> "Message:" + id)
                    .forEach(conn::hGetAll);
            return null;
        });

        return messages.stream()
                .map(o -> (Map<String, String>) o)
                .map(o -> mapper.fromHash(o))
                .collect(toSet());
}

有没有办法将mapper传递给executePipelined

0 个答案:

没有答案