基础版:
import java.util.concurrent.TimeUnit;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
/**
* Redis帮助类
*
* @author aaa
*/
public class RedisCacheUtils implements BeanFactoryAware {
private static BeanFactory beanFactory = null;
/**
* 设置缓存
*
* @param key
* @param object
* @param expireTime 秒
*/
@SuppressWarnings("unchecked")
public static void set(String key, Object object, long expireTime) {
RedisTemplate redisTemplate = getRedisTemplate();
if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForValue() != null) {
if (expireTime > 0) {
redisTemplate.opsForValue().set(key, object, expireTime, TimeUnit.SECONDS);
}
else {
redisTemplate.opsForValue().set(key, object, 86400L, TimeUnit.SECONDS);
}
}
}
/**
* 删除缓存
*
* @param key
*/
@SuppressWarnings("unchecked")
public static void del(String key) {
RedisTemplate redisTemplate = getRedisTemplate();
if (!StringUtils.isEmpty(key) && redisTemplate != null) {
redisTemplate.delete(key);
}
}
/**
* 获取缓存
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public static T get(String key, Class clazz) {
Object obj = null;
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate != null && redisTemplate.opsForValue() != null) {
obj = redisTemplate.opsForValue().get(key);
}
if (null != obj) {
return clazz.cast(obj);
}
else {
return null;
}
}
/**
* 设置Hash类型缓存
*
* @author aaa
* @param key
* @param hashKey
* @param object
* @param expireTime
*/
public static void setH(String key, Object hashKey, Object object, long expireTime) {
RedisTemplate redisTemplate = getRedisTemplate();
if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForHash() != null) {
redisTemplate.opsForHash().put(key, hashKey, object);
if (expireTime > 0) {
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
}
else {
redisTemplate.expire(key, CacheConstant.REDIS_DEAULT_EXPIRE, TimeUnit.SECONDS);
}
}
}
/**
* 设置Hash类型
*
* @param key
* @param hashKey
* @param object
*/
public static void setH(String key, Object hashKey, Object object) {
RedisTemplate redisTemplate = getRedisTemplate();
if (!StringUtils.isEmpty(key) && redisTemplate != null && redisTemplate.opsForHash() != null) {
redisTemplate.opsForHash().put(key, hashKey, object);
}
}
/**
* 获取Hash类型缓存
*
* @author aaa
* @param key
* @param hashKey
* @param clazz
*/
@SuppressWarnings("unchecked")
public static T getH(String key, Object hashKey, Class clazz) {
Object obj = null;
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate != null && redisTemplate.opsForHash() != null) {
obj = redisTemplate.opsForHash().get(key, hashKey);
}
if (null != obj) {
return clazz.cast(obj);
}
else {
return null;
}
}
/**
* 获取Hash类型缓存
*
* @author aaa
* @param key
* @param hashKey
*/
@SuppressWarnings("unchecked")
public static void delH(String key, Object hashKey) {
RedisTemplate redisTemplate = getRedisTemplate();
if (!StringUtils.isEmpty(key) && null != hashKey && redisTemplate != null
&& redisTemplate.opsForHash() != null) {
redisTemplate.opsForHash().delete(key, hashKey);
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
RedisCacheUtils.beanFactory = beanFactory;
}
public static Object getBean(String bean) {
if (beanFactory != null) {
return beanFactory.getBean(bean);
}
return null;
}
public static RedisTemplate getRedisTemplate() {
return (RedisTemplate) getBean("redisTemplate");
}
}
优化版:
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.lang.NonNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.function.Predicate;
/**
*
* redis缓存工具类
*
*
* @author aaa
*/
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisCacheExtUtils implements BeanFactoryAware {
private static BeanFactory beanFactory = null;
private static final RedisCacheExtUtils INSTANCE = new RedisCacheExtUtils();
public static RedisCacheExtUtils getInstance() {
return INSTANCE;
}
public static boolean hasKey(String key) {
return hasKey(key, e -> {
throw new RuntimeException(e);
});
}
public static boolean hasKey(String key, Predicate predicate) {
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return false;
}
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
return predicate.test(e);
}
}
public static boolean hasKey(String key, String hashKey) {
return hasKey(key, hashKey, e -> {
throw new RuntimeException(e);
});
}
public static boolean hasKey(String key, String hashKey, Predicate predicate) {
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return false;
}
try {
return redisTemplate.opsForHash().hasKey(key, hashKey);
} catch (Exception e) {
return predicate.test(e);
}
}
/**
* 设置缓存
*
* @param key key
* @param object object
* @param expireTime 秒
*/
public static void set(String key, Object object, long expireTime) {
set(key, object, expireTime, e -> {
throw new RuntimeException(e);
});
}
public static void set(String key, Object object, long expireTime, Function function) {
try {
RedisCacheUtils.set(key, object, expireTime);
} catch (Exception e) {
function.apply(e);
}
}
/**
* 删除缓存
*
* @param key key
*/
public static void del(String key) {
del(key, e -> {
throw new RuntimeException(e);
});
}
public static void del(String key, Function function) {
try {
RedisCacheUtils.del(key);
} catch (Exception e) {
function.apply(e);
}
}
/**
* 获取缓存
*
* @param key key
* @return 值
*/
public static T get(String key) {
return get(key, e -> {
throw new RuntimeException(e);
});
}
public static T get(String key, Function function) {
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate == null) {
return function.apply(null);
}
try {
return redisTemplate.opsForValue().get(key);
} catch (Exception e) {
return function.apply(e);
}
}
/**
* 设置Hash类型缓存
*
* @author aaa
* @param key key
* @param hashKey hashKey
* @param object object
* @param expireTime expireTime
*/
public static void setH(String key, String hashKey, T object, long expireTime) {
setH(key, hashKey, object, expireTime, e -> {
throw new RuntimeException(e);
});
}
public static void setH(String key, String hashKey, T object, long expireTime, Function function) {
try {
long actualExpireTime = expireTime > 0 ? expireTime : CacheConstant.REDIS_DEAULT_EXPIRE;
RedisTemplate redisTemplate = getRedisTemplate();
if (redisTemplate != null) {
HashOperations hashOperations = redisTemplate.opsForHash();
redisTemplate.execute(new SessionCallback
优化的点:提供了一个redis连不上,或者执行报错的时候的Function接口给调用方,用来处理缓存异常的时候,提供容错解决办法,比如查数据库、返回默认值等
Redis分布式工具类:
package com.zte.crm.iepms.common.util;
import com.google.common.collect.Maps;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import javax.annotation.Nonnull;
import javax.annotation.PostConstruct;
import java.security.SecureRandom;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.function.Predicate;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
/**
* redis 分布式锁工具类
*
* @author aaa
* @since 2018/11/2 11:20
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class RedisLockUtils implements EnvironmentAware {
private static final String PARAM_SERVICE_NAME = "spring.application.name";
private static final RedisLockUtils INSTANCE = new RedisLockUtils();
private static final Logger LOGGER = LoggerFactory.getLogger(RedisLockUtils.class);
private static final ThreadLocal
依赖的StringHelper.getGUID()方法如下:
public class StringHelper {
public StringHelper() {
}
public static String getGUID() {
UUID uuid = UUID.randomUUID();
return uuid.toString();
}
}
private static String LOCK_KEY = "{0}:lock:%s";
MessageFormat.format(LOCK_KEY, redisLockPrefix); // 替换{0}
String lockKey = String.format(LOCK_KEY, lockTarget); // 替换%s