import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
public class RedisUtils {
private RedisUtils() {
}
@SuppressWarnings(“unchecked”)
public static RedisTemplate<String, Object> redisTemplate=ContextLoader.getCurrentWebApplicationContext().getBean(RedisTemplate.class);
public static boolean expire(final String key, final long timeout) {
return expire(key, timeout, TimeUnit.SECONDS);
}
public static boolean expire(final String key, final long timeout, final TimeUnit unit) {
Boolean ret=redisTemplate.expire(key, timeout, unit);
return ret !=null && ret;
}
public static boolean del(final String key) {
redisTemplate.delete(key);
return true;
}
public static long del(final Collection<String> keys) {
redisTemplate.delete(keys);
return 0;
}
public static void set(final String key, final Object value) {
redisTemplate.opsForValue().set(key, value, 1, TimeUnit.MINUTES);
}
// 存储普通对象操作
public static void set(final String key, final Object value, final long timeout) {
redisTemplate.opsForValue().set(key, value, timeout, TimeUnit.SECONDS);
}
public static Object get(final String key) {
return redisTemplate.opsForValue().get(key);
}
// 存储Hash操作
public static void hPut(final String key, final String hKey, final Object value) {
redisTemplate.opsForHash().put(key, hKey, value);
}
public static void hPutAll(final String key, final Map<String, Object> values) {
redisTemplate.opsForHash().putAll(key, values);
}
public static Object hGet(final String key, final String hKey) {
return redisTemplate.opsForHash().get(key, hKey);
}
public static List<Object> hMultiGet(final String key, final Collection<Object> hKeys) {
return redisTemplate.opsForHash().multiGet(key, hKeys);
}
// 存储Set相关操作
public static long sSet(final String key, final Object… values) {
Long count=redisTemplate.opsForSet().add(key, values);
return count==null ? 0 : count;
}
public static long sDel(final String key, final Object… values) {
Long count=redisTemplate.opsForSet().remove(key, values);
return count==null ? 0 : count;
}
// 存储List相关操作
public static long lPush(final String key, final Object value) {
Long count=redisTemplate.opsForList().rightPush(key, value);
return count==null ? 0 : count;
}
public static long lPushAll(final String key, final Collection<Object> values) {
Long count=redisTemplate.opsForList().rightPushAll(key, values);
return count==null ? 0 : count;
}
public static long lPushAll(final String key, final Object… values) {
Long count=redisTemplate.opsForList().rightPushAll(key, values);
return count==null ? 0 : count;
}
public static List<Object> lGet(final String key, final int start, final int end) {
return redisTemplate.opsForList().range(key, start, end);
}
}