Lấy tất cả HashKey từ Redis dựa trên key

Trong quá trình thực hiện dự án, tôi đã gặp phải một vấn đề: làm thế nào để lấy tất cả các giá trị HashKey từ Redis khi sử dụng key. Sau khi tìm kiếm, tôi phát hiện ra rằng có thể sử dụng phương thức "entries" của Redis. Dưới đây là cách thực hiện điều này thông qua mã nguồn.
import java.util.List;

public interface RedisService {

    boolean put(String key, String hashKey, Object value);

    Object get(String key, String hashKey);

    void remove(String key, String hashKey);

    Object getAllHashKeys(String key);
}
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;

@Service
public class RedisServiceImpl implements RedisService {

    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public boolean put(String key, String hashKey, Object value) {
        try {
            redisTemplate.setKeySerializer(new StringRedisSerializer());
            HashOperations ops = redisTemplate.opsForHash();
            ops.put(key, hashKey, value);
            return true;
        } catch (Exception e) {
            System.err.println("Lỗi khi lưu vào Redis: " + e.getMessage());
            return false;
        }
    }

    @Override
    public Object get(String key, String hashKey) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        HashOperations ops = redisTemplate.opsForHash();
        return StringUtils.isBlank(key) ? null : ops.get(key, hashKey);
    }

    @Override
    public void remove(String key, String hashKey) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        HashOperations ops = redisTemplate.opsForHash();
        ops.delete(key, hashKey);
    }

    @Override
    public Object getAllHashKeys(String key) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        HashOperations ops = redisTemplate.opsForHash();
        return ops.entries(key);
    }
}

Thẻ: Redis Spring Data Redis HashOperations RedisTemplate

Đăng vào ngày 15 tháng 6 lúc 21:09