package com.ai.ipu.server.util; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Component; import com.ai.ipu.basic.string.StringUtil; import com.ai.ipu.basic.util.IpuUtility; import com.ai.ipu.cache.ICache; @Component public class RedisOperUtil implements ICache{ @Autowired private StringRedisTemplate strRedisTemplate; @Autowired private RedisTemplate redisTemplate; /** * Redis常见的五大数据类型: * stringRedisTemplate.opsForValue();[String(字符串)] * stringRedisTemplate.opsForList();[List(列表)] * stringRedisTemplate.opsForSet();[Set(集合)] * stringRedisTemplate.opsForHash();[Hash(散列)] * stringRedisTemplate.opsForZSet();[ZSet(有序集合)] */ /** * 存 */ public boolean put(Object key, Object value) throws Exception { boolean result = true; try{ if (key instanceof String) strRedisTemplate.opsForValue().set(key.toString(), String.valueOf(value)); else IpuUtility.error("key只支持String,保存数据到缓存操作失败"); }catch (NullPointerException e) { if (StringUtil.isEmpty((String)key)) IpuUtility.error("由于key值为空,导致保存数据到缓存操作失败", e); IpuUtility.error("由于value值为空,导致保存数据到缓存操作失败", e); result = false; } return result; } /** * 取 */ public Object get(Object key) throws Exception { return strRedisTemplate.opsForValue().get(key); } /** * 移除 */ public boolean remove(Object key) throws Exception { redisTemplate.delete(key); return true; } /** * 清除 */ public void clear() throws Exception { ; } /** * key是否存在 */ public boolean keyExists(String key) { return strRedisTemplate.hasKey(key); } /** * 设置数据 * @param key * @param value * @param timeoutSeconds * @return * @throws Exception */ public boolean put(Object key, Object value, int timeoutSeconds) throws Exception { boolean result = true; try { if (key instanceof String) strRedisTemplate.opsForValue().set(key.toString(), String.valueOf(value), timeoutSeconds, TimeUnit.SECONDS); else IpuUtility.error("key只支持String,保存数据到缓存操作失败"); }catch (NullPointerException e) { if (StringUtil.isEmpty((String)key)) IpuUtility.error("由于key值为空,导致保存数据到缓存操作失败", e); IpuUtility.error("由于value值为空,导致保存数据到缓存操作失败", e); result = false; } return result; } public void close() throws Exception { ; } }