package com.nineclient.redis;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @ClassName: RedisUtil
* @Description: redis工具类
*/
@Component("secondaryRedisUtils")
public class SecondaryRedisUtils<T> {
private static Logger log = LoggerFactory.getLogger(SecondaryRedisUtils.class);
@Autowired
@Qualifier("secondaryRedisTemplate")
RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
@SuppressWarnings("unchecked")
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
*
* @param key
*/
@SuppressWarnings("unchecked")
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
@SuppressWarnings("unchecked")
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.error("redis set error. key:{},value:{}", key, value, e);
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
result = true;
} catch (Exception e) {
log.error("redis set error. key:{},value:{},expireTime:{}", key, value, expireTime, e);
}
return result;
}
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime, RedisTemplate redisTemplate) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.MILLISECONDS);
result = true;
} catch (Exception e) {
log.error("redis set error. key:{},value:{},expireTime:{}", key, value, expireTime, e);
}
return result;
}
@SuppressWarnings("unchecked")
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
log.error("redis set error. key:{},value:{},expireTime:{}", key, value, expireTime, e);
}
return result;
}
/**
* @param key
* @return Long 返回类型
* @Title: getListSize
* @Description: 获取redis list 数据类型 长度
*/
public Long getListSize(String key) {
Long size = 0L;
try {
size = redisTemplate.opsForList().size(key);
} catch (Exception e) {
log.error("redis getListSize error. key:{}", key, e);
}
return size;
}
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
log.error("exception when hash set key {}. ", key, e);
return false;
}
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 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) {
log.error("exception when hash set key {}. ", key, e);
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
log.error("exception when hash set key {}, item {} ", key, item, e);
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 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) {
log.error("exception when hash set key {}, item {} ", key, item, e);
return false;
}
}
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
}
return true;
} catch (Exception e) {
log.error("exception when expire key {}. ", key, e);
return false;
}
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* 写入缓存
*
* @param key
* @param ttl
* @return
*/
public boolean setTTL(final String key, long ttl) {
return redisTemplate.expire(key, ttl, TimeUnit.MILLISECONDS);
}
/**
* *左侧push
*
* @param key
* @param values
* @return
*/
public Long lPush(String key, Object... values) {
return this.redisTemplate.opsForList().leftPush(key, values);
}
/**
* *左侧push
*
* @param key
* @return
*/
public <T> T rPop(String key) {
return (T) this.redisTemplate.opsForList().rightPop(key);
}
/**
* *获取List(queue)全部的数据
*
* @param key
* @return
*/
public List<JSONArray> getListById(String key) {
return redisTemplate.opsForList().range(key, 0, -1);
}
/**
* *获取List(queue)全部的数据
*
* @param key
* @return
*/
public void trimList(String key, int size) {
redisTemplate.opsForList().trim(key, size, -1);
}
public Set<String> getKey(String collectionName) {
return redisTemplate.keys(collectionName);
}
/**
* 获取符合条件的key
*
* @param pattern 表达式
* @return
*/
public List<String> keys(String pattern) throws IOException {
long start = System.currentTimeMillis();
//需要匹配的key
// String patternKey = "pay:*";
ScanOptions options = ScanOptions.scanOptions()
//这里指定每次扫描key的数量(很多博客瞎说要指定Integer.MAX_VALUE,这样的话跟 keys有什么区别?)
.count(10000)
.match(pattern).build();
RedisSerializer<String> redisSerializer = (RedisSerializer<String>) redisTemplate.getKeySerializer();
Cursor cursor = (Cursor) redisTemplate.executeWithStickyConnection(redisConnection -> new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize));
List<String> result = new ArrayList<>();
while (cursor.hasNext()) {
result.add(cursor.next().toString());
}
//切记这里一定要关闭,否则会耗尽连接数。报Cannot get Jedis connection; nested exception is redis.clients.jedis.exceptions.JedisException: Could not get a
cursor.close();
log.debug("scan扫描共耗时:{} ms key数量:{}", System.currentTimeMillis() - start, result.size());
return result;
}
public void putToList(String key, Object value) {
redisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
List<Object> result = null;
do {
operations.watch(key);
JSONObject document = (JSONObject) operations.opsForValue().get(key);
List valueList = null;
if (document == null) {
document = new JSONObject();
valueList = new ArrayList();
} else {
valueList = (List) document.get("value");
}
if (!valueList.contains(value)) {
valueList.add(value);
document.put("value", valueList);
operations.multi();
operations.opsForValue().set(key, document);
} else {
break;
}
try {
result = operations.exec();
} catch (Exception e) {
}
} while (result == null);
return result;
}
});
//redisTemplate.putToList(getKey(id, collectionName), value);
}
public void removeFromList(String key, Object id, Object value) {
redisTemplate.execute(new SessionCallback<List<Object>>() {
@Override
public List<Object> execute(RedisOperations operations) throws DataAccessException {
List<Object> result = null;
do {
operations.watch(key);
JSONObject document = (JSONObject) operations.opsForValue().get(key);
if (document == null) {
break;
}
List valueList = (List) document.get("value");
valueList.remove(value);
document.put("value", valueList);
operations.multi();
operations.opsForValue().set(key, document);
try {
result = operations.exec();
} catch (Exception e) {
}
} while (result == null);
return result;
}
});
//redisTemplate.removeFromList(getKey(id, collectionName), value);
}
public void incrBy(String key, long delta, long time) {
redisTemplate.opsForValue().increment(key, delta);
redisTemplate.expire(key, time, TimeUnit.MILLISECONDS);
}
}
这是我的redis工具类,请帮我获取一个上面那个list
最新发布