前一段時間,做項目的時候遇到一個問題,就是如果緩存的時候使用 HashKey,那么如何能通過key獲取所有的HashKey的值,通過百度發現沒有直接答案,沒辦法就看了下redis的使用,通過查找發現有“entries”方法可以做到,接下來我們看具體代碼。
import java.util.List; /** * @Package com.ywtg.common.service * @ClassName: RedisObjectService * @Description: redis處理 * @Author youli * @date 2020年9月7日 */ public interface RedisObjectService { /** * @Title: put * @Description: Hset放入 * @Author youli * @date 2020年9月8日 * @param key * @param hashKey * @param value * @return */ boolean put(String key, String hashKey, Object value); /** * Hset緩存獲取 * * @param key * @return */ Object get(String key, String hashKey); /** * Hset緩存移除 * * @param key * @return */ void remove(String key, String hashKey); /** * @Title: getHashKeyValue * @Description: 根據key獲取 所有的 HashKeyValue * @Author youli * @date 2021年1月4日 * @param key * @return */ Object getHashKeyValue(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.core.ValueOperations; import org.springframework.data.redis.serializer.StringRedisSerializer; import org.springframework.stereotype.Service; import com.ywtg.common.service.RedisObjectService; import lombok.extern.slf4j.Slf4j; @Slf4j @Service public class RedisObjectServiceImpl implements RedisObjectService { @Resource private RedisTemplate<String, Object> redisTemplate; @Override public boolean put(String key, String hashKey, Object value) { try { redisTemplate.setKeySerializer(new StringRedisSerializer()); HashOperations<String, Object, Object> ops = redisTemplate.opsForHash(); ops.put(key, hashKey, value); return true; } catch (Exception e) { log.error("RedisObjectService hashPut simple error detail:{}", e.getMessage()); return false; } } @Override public Object get(String key, String hashKey) { log.info("獲取redis-key:{},hashKey:{}", key, hashKey); redisTemplate.setKeySerializer(new StringRedisSerializer()); HashOperations<String, Object, Object> ops = redisTemplate.opsForHash(); log.info("獲取redis-key redisTemplate:{}", redisTemplate); return StringUtils.isBlank(key) ? null : ops.get(key, hashKey); } @Override public void remove(String key, String hashKey) { redisTemplate.setKeySerializer(new StringRedisSerializer()); HashOperations<String, Object, Object> ops = redisTemplate.opsForHash(); ops.delete(hashKey, hashKey); } @Override public Object getHashKeyValue(String key) { log.info("獲取HashKey key:{}", key); redisTemplate.setKeySerializer(new StringRedisSerializer()); HashOperations<String, Object, Object> ops = redisTemplate.opsForHash(); log.info("獲取HashKey redisTemplate:{}", redisTemplate); return ops.entries(key); } }
