1、通过key获取缓存数
/**
*
* getCache(通过key获取缓存数据)
*
* @param key 写入redis的key值
* @return String 对应的数据
*/
@Override
public String getCache(String key)
{
try{
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
return valueOperations.get(key) == null ? "" : valueOperations.get(key).toString();
}catch (RedisConnectionFailureException e){
return null;
}
catch (Exception e){
return null;
}
}
2、获取多个key对应的缓存数据
/**
*
* multiGetCaches(获取多个key对应的缓存数据)
*
* @param key redis的key值,可以为多个
* @return List 对应的值,若key值不存在则返回null
*/
@Override
public List<String> multiGetCaches(String... key){
try{
if (null != key && key.length > 0) {
Collection<String> collection = Arrays.asList(key);
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
List<String> list = valueOperations.multiGet(collection);
if (null != list && list.size() > 0) {
return list;
} else {
return null;
}
}else {
return null;
}
}catch (RedisConnectionFailureException e){
return null;
} catch (Exception e){
return null;
}
}
3、将数据写入redis,并设置过期时间/* *
* setCacheWithExpire(将数据写入redis,并设置过期时间)
*
* @param key 写入redis的key值
* @param value 写入redis的数据
* @param timeOut 过期时间,单位秒
*/
@Override
public void setCacheWithExpire(String key, String value, long timeOut){
try {
ValueOperations<String, String> valueOperations = redisTemplate.opsForValue();
valueOperations.set(key, value, timeOut, TimeUnit.SECONDS);
}
catch (RedisConnectionFailureException e){
}catch (Exception e){
}
}