自定义redis工具类
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.data.redis.core.BoundListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
@Component
public class RedisCache {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate;
}
public boolean expire(final String key, final long time) {
return expire(key, time, TimeUnit.SECONDS);
}
public boolean expire(final String key, final long time, final TimeUnit unit) {
try {
if(time>0){
redisTemplate.expire(key, time, unit);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key){
return redisTemplate.getExpire(key,TimeUnit.SECONDS);
}
public boolean hasKey(String key){
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String ... key){
if(key!=null&&key.length>0){
if(key.length==1){
redisTemplate.delete(key[0]);
}else{
redisTemplate.delete((Collection<String>) CollectionUtils.arrayToList(key));
}
}
}
public Object get(String key){
return key==null?null:redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key,Object value,long time){
return set(key, value, time, TimeUnit.SECONDS);
}
public boolean set(String key,Object value,long time, TimeUnit unit){
try {
if(time > 0){
redisTemplate.opsForValue().set(key, value, time, unit);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta){
if(delta<0){
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta){
if(delta<0){
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public Object hget(String key,String item){
return redisTemplate.opsForHash().get(key, item);
}
public Map<Object,Object> hmget(String key){
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map<String,Object> map){
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map<String,Object> map, long time){
try {
redisTemplate.opsForHash().putAll(key, map);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key,String item,Object value,long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if(time>0){
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item){
redisTemplate.opsForHash().delete(key,item);
}
public boolean hHasKey(String key, String item){
return redisTemplate.opsForHash().hasKey(key, item);
}
public double hincr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item,double by){
return redisTemplate.opsForHash().increment(key, item,-by);
}
public Set<Object> sGet(String key){
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key,Object value){
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object...values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key,long time,Object...values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time>0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key){
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object ...values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public List<Object> lGet(String key, long start, long end){
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key){
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key,long index){
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index,Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key,long count,Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Set<?> keys(String pattern){
return redisTemplate.keys(pattern);
}
public void convertAndSend(String channel, Object message){
redisTemplate.convertAndSend(channel,message);
}
public List<Object> rangeList(String listKey, long start, long end) {
BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
return boundValueOperations.range(start, end);
}
public Object rifhtPop(String listKey){
BoundListOperations<String, Object> boundValueOperations = redisTemplate.boundListOps(listKey);
return boundValueOperations.rightPop();
}
public static String handleCacheKey (String spliter, String ... vals) {
return String.join(spliter, vals);
}
}
redis序列化配置
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(LettuceConnectionFactory lcf) {
RedisTemplate<String, Object> restTemplate = new RedisTemplate<String, Object>();
restTemplate.setKeySerializer(new StringRedisSerializer());
restTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
restTemplate.setHashKeySerializer(new StringRedisSerializer());
restTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
restTemplate.setConnectionFactory(lcf);
return restTemplate;
}
}
redis工具类的封装
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.data.redis.core.DefaultTypedTuple;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
@Component
public class RedisUtils {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public void setJsonObj(String key, Object obj, Duration timeout) {
String jsonStr = ObjectUtils.toJSON(obj);
if (ObjectUtils.isEmpty(timeout)) {
this.redisTemplate.opsForValue().set(key, jsonStr);
} else {
this.redisTemplate.opsForValue().set(key, jsonStr, timeout);
}
}
public void setObj(String key, Object obj, Duration timeout) {
if (ObjectUtils.isEmpty(timeout)) {
this.redisTemplate.opsForValue().set(key, obj);
} else {
this.redisTemplate.opsForValue().set(key, obj, timeout);
}
}
public void setLong(String key, Long num, Duration timeout) {
this.redisTemplate.opsForValue().set(key, num, timeout);
}
public void setStr(String key, String val, Duration timeout) {
this.redisTemplate.opsForValue().set(key, val, timeout);
}
public void setMap(Map<String, Object> map) {
this.redisTemplate.opsForValue().multiSet(map);
}
public List<Object> getMap(Collection<String> keys) {
List<Object> multiGet = this.redisTemplate.opsForValue().multiGet(keys);
return multiGet;
}
public void setLong(String key, Long num) {
setLong(key, num, null);
}
public void setObj(String key, Object obj) {
setObj(key, obj, null);
}
public void setJsonObj(String key, Object obj) {
setJsonObj(key, obj, null);
}
public void setStr(String key, String val) {
setStr(key, val);
}
public String getStr(String key) {
return ObjectUtils.getStr(this.redisTemplate.opsForValue().get(key));
}
public String getJson(String key) {
return getStr(key);
}
public Object getObj(String key) {
return ObjectUtils.getObj(this.redisTemplate.opsForValue().get(key));
}
public boolean remove(String key) {
if (ObjectUtils.isEmpty(key)) {
return false;
}
return this.redisTemplate.delete(key);
}
public boolean remove(Collection<String> keys) {
Long del = this.redisTemplate.delete(keys);
if (del > 0) {
return true;
}
return false;
}
public boolean remove(String... keys) {
if (ObjectUtils.checkArr(keys)) {
return false;
}
Set<String> set = new HashSet<String>(Arrays.asList(keys));
return remove(set);
}
public void lPush(String key, Object val) {
this.redisTemplate.opsForList().leftPush(key, val);
}
public Long lPushAll(String key, Object... val) {
Long count = this.redisTemplate.opsForList().leftPushAll(key, val);
if (ObjectUtils.isBlank(count)) {
return 0L;
}
return count;
}
public Long lPush(String key, Object existVal, Object newVal) {
Long count = this.redisTemplate.opsForList().leftPush(key, existVal, newVal);
return count;
}
public void rPush(String key, Object val) {
this.redisTemplate.opsForList().rightPush(key, val);
}
public Long rPushAll(String key, Object... val) {
Long count = this.redisTemplate.opsForList().rightPushAll(key, val);
if (ObjectUtils.isBlank(count)) {
return 0L;
}
return count;
}
public Long rPush(String key, Object existVal, Object newVal) {
Long count = this.redisTemplate.opsForList().rightPush(key, existVal, newVal);
return count;
}
public List<Object> getList(String key, long startIndex, long endIndex) {
List<Object> list = this.redisTemplate.opsForList().range(key, startIndex, endIndex);
return list;
}
public List<Object> getListAll(String key) {
List<Object> list = this.redisTemplate.opsForList().range(key, 0, -1);
return list;
}
public Long getListSize(String key) {
Long size = this.redisTemplate.opsForList().size(key);
return ObjectUtils.isBlank(size) ? 0L : size;
}
public Long removeList(String key, Long count, Object val) {
Long rem = this.redisTemplate.opsForList().remove(key, count, val);
return ObjectUtils.isBlank(rem) ? 0L : rem;
}
public boolean removeList(String key, Object val) {
Long rem = this.redisTemplate.opsForList().remove(key, 1, val);
return ObjectUtils.isBlank(rem);
}
public Object lPop(String key) {
Object obj = this.redisTemplate.opsForList().leftPop(key);
return obj;
}
public Object rPop(String key) {
Object obj = this.redisTemplate.opsForList().rightPop(key);
return obj;
}
public Long sAdd(String key, Object[] obj) {
if (ObjectUtils.isBlank(obj)) {
return 0L;
}
return sAdds(key, obj);
}
public Long sAdds(String key, Object... obj) {
if (ObjectUtils.isBlank(obj)) {
return 0L;
}
Long count = this.redisTemplate.opsForSet().add(key, obj);
return count;
}
public Set<Object> getSet(String key) {
if (ObjectUtils.isBlank(key)) {
return new HashSet<Object>();
}
Set<Object> set = this.redisTemplate.opsForSet().members(key);
return set;
}
public Long getSetSize(String key) {
if (ObjectUtils.isBlank(key)) {
return 0L;
}
Long size = this.redisTemplate.opsForSet().size(key);
return ObjectUtils.isBlank(size) ? 0L : size;
}
public Long removeSet(String key, Object... obj) {
if (ObjectUtils.isBlank(obj)) {
return 0L;
}
Long rem = this.redisTemplate.opsForSet().remove(key, obj);
return ObjectUtils.isBlank(rem) ? 0L : rem;
}
public boolean addZSet(String key, Object obj, double val) {
if (ObjectUtils.isBlank(key)) {
return false;
}
return this.redisTemplate.opsForZSet().add(key, obj, val);
}
public Long addZSet(String key, Map<String, Double> map) {
if (ObjectUtils.isBlank(map)) {
return 0L;
}
Set<ZSetOperations.TypedTuple<Object>> tupleSet = new HashSet<>();
for (String k : map.keySet()) {
tupleSet.add(new DefaultTypedTuple<>(k, map.get(k)));
}
Long count = this.redisTemplate.opsForZSet().add(key, tupleSet);
return ObjectUtils.isBlank(count) ? 0L : count;
}
public Set<Object> getZSet(String key, long startIndex, long endIndex) {
if (ObjectUtils.isBlank(key)) {
return new HashSet<Object>();
}
Set<Object> set = this.redisTemplate.opsForZSet().range(key, startIndex, endIndex);
return set;
}
public Set<Object> getZSetAll(String key) {
if (ObjectUtils.isBlank(key)) {
return new HashSet<Object>();
}
Set<Object> set = getZSet(key, 0, -1);
return set;
}
public Long removeZSet(String key, Object[] obj) {
if (ObjectUtils.isBlank(obj)) {
return 0L;
}
Long rem = this.redisTemplate.opsForZSet().remove(key, obj);
return ObjectUtils.isBlank(rem) ? 0L : rem;
}
public Long removeZSets(String key, Object... obj) {
if (ObjectUtils.isBlank(obj)) {
return 0L;
}
return removeZSet(key, obj);
}
public void setExpire(String key, Long timeout, TimeUnit unit) {
this.redisTemplate.expire(key, timeout, unit);
}
public void setTimeout(String key, Long timeout, TimeUnit unit) {
setExpire(key, timeout, unit);
}
public Long getExpire(String key) {
if (ObjectUtils.isBlank(key)) {
return 0L;
}
Long timeout = this.redisTemplate.getExpire(key);
return ObjectUtils.isBlank(timeout) ? 0L : timeout;
}
public Long getExpire(String key, TimeUnit unit) {
if (ObjectUtils.isBlank(key)) {
return 0L;
}
Long timeout = this.redisTemplate.getExpire(key, unit);
return ObjectUtils.isBlank(timeout) ? 0L : timeout;
}
@SuppressWarnings("unchecked")
public <T> T getJsonToObj(String key, Class<T> obj) {
String jsonStr = ObjectUtils.getStr(this.redisTemplate.opsForValue().get(key));
if (ObjectUtils.isNotEmpty(jsonStr)) {
return ObjectUtils.toObj(jsonStr, obj);
}
return (T) obj.getClass();
}
}
对象工具类
import java.io.IOException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializeConfig;
import cn.molu.wstm.vo.ResponseVo;
public class ObjectUtils {
public static String getStr(Object obj) {
if (!isBlank(obj)) {
return String.valueOf(obj);
}
return "";
}
@SuppressWarnings("unchecked")
public static <T> T getObj(Object obj) {
if (isBlank(obj)) {
return (T) obj.getClass();
}
return (T) obj;
}
public static boolean isBlank(Object obj) {
if (obj == null || "".equals(String.valueOf(obj))) {
return true;
}
if (obj instanceof String) {
String str = String.valueOf(obj).trim();
return StringUtils.isBlank(str);
}
if (obj instanceof Long || obj instanceof Integer || obj instanceof Double || obj instanceof Short
|| obj instanceof Float || obj instanceof Boolean) {
return StringUtils.isBlank(String.valueOf(obj).trim());
}
if (obj instanceof Object[]) {
return checkArr((Object[]) obj);
}
if (obj instanceof Collection<?>) {
return checkCol((Collection<?>) obj);
}
if (obj instanceof Map<?, ?>) {
return checkMap((Map<?, ?>) obj);
}
return !org.apache.commons.lang3.ObjectUtils.allNotNull(obj);
}
public static boolean checkArr(Object[] obj) {
if (obj == null) {
return true;
}
if (obj.length < 1) {
return true;
}
int i = 0;
for (Object o : obj) {
if (StringUtils.isBlank(String.valueOf(o).trim())) {
++i;
}
}
return i == obj.length ? true : false;
}
public static boolean isEmpty(Object obj) {
return isBlank(obj);
}
public static boolean isEmpty(Object... obj) {
if (obj == null) {
return true;
}
for (Object o : obj) {
if (isBlank(o)) {
return true;
}
}
return false;
}
public static boolean isNotEmpty(Object obj) {
return !isBlank(obj);
}
public static boolean checkMap(Map<?, ?> obj) {
if (obj == null || obj.isEmpty() || obj.keySet().size() < 1 || obj.values().size() < 1) {
return true;
}
int i = 0;
for (Object o : obj.values()) {
if (obj == null || StringUtils.isBlank(String.valueOf(o).trim())) {
++i;
}
}
return i == obj.values().size() ? true : false;
}
public static boolean checkCol(Collection<?> c) {
if (c == null || c.isEmpty() || c.size() < 1) {
return true;
}
int i = 0;
for (Object v : c) {
if (v == null || StringUtils.isBlank(String.valueOf(v).trim())) {
++i;
}
}
return i == c.size() ? true : false;
}
private static Map<?, ?> jsonToMap(String jsonStr) {
if (isBlank(jsonStr)) {
return new HashMap<String, Object>();
}
return JSONObject.parseObject(jsonStr, Map.class);
}
@SuppressWarnings("unchecked")
public static <T> T mapToObj(Map<String, Object> map, Class<T> obj) {
if (!isBlank(map)) {
String jsonString = toJSON(map);
return JSONObject.parseObject(jsonString, obj);
}
return (T) obj.getClass();
}
@SuppressWarnings("unchecked")
public static <T> T toObj(String jsonStr, Class<T> obj) {
if (!isBlank(jsonStr)) {
return JSONObject.parseObject(jsonStr, obj);
}
return (T) obj.getClass();
}
public static String toJSON(Object obj) {
if (!isBlank(obj)) {
Object json = JSONObject.toJSON(obj, SerializeConfig.globalInstance);
return getStr(json);
}
return "";
}
public static boolean checkNull(HttpServletResponse res, Object params, String errMsg) {
if (StringUtils.isEmpty(errMsg)) {
errMsg = ResponseVo.PARAM_ERROR.msg();
}
if (isBlank(params)) {
return true;
}
errMsg(res, errMsg);
throw new NullPointerException(errMsg);
}
public static boolean checkNull(HttpServletResponse res, String errMsg, Object... params) {
if (StringUtils.isEmpty(errMsg)) {
errMsg = ResponseVo.PARAM_ERROR.msg();
}
for (Object object : params) {
if (isBlank(object)) {
errMsg(res, errMsg);
throw new NullPointerException(errMsg);
}
}
return true;
}
public static void errMsg(HttpServletResponse res, String msg) {
printJsonMsg(res, false, msg, null, 500);
}
public static void printMsg(HttpServletResponse res, String msg, Object data, Integer code) {
printJsonMsg(res, true, msg, data, code);
}
public static void printJsonMsg(HttpServletResponse res, Object flag, String msg, Object data, Integer coed) {
JSONObject jo = new JSONObject();
jo.put("flag", flag);
if (StringUtils.isNotBlank(msg)) {
jo.put("msg", msg);
}
if (data != null) {
jo.put("data", data);
}
if (coed != null) {
jo.put("coed", coed);
}
res.setContentType("text/json;charset=UTF-8");
try {
res.getWriter().print(jo);
} catch (IOException e) {
e.printStackTrace();
}
}
}