RedisConfig
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
redisTemplate.setHashValueSerializer(new GenericToStringSerializer<>(Object.class));
redisTemplate.setKeySerializer(new StringRedisSerializer());
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
redisTemplate.setConnectionFactory(redisConnectionFactory);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
RedisService
@Slf4j
@Component
public class RedisService {
@Autowired
RedisTemplate redisTemplate;
@Value("${project.redis.data.prefix}")
String redisPrefix;
public boolean set(String key, Object value) {
key = getKey(key);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
log.warn("set redis key error", e);
}
return result;
}
public boolean set(String key, Object value, long timeout) {
key = getKey(key);
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value, Duration.ofSeconds(timeout));
result = true;
} catch (Exception e) {
log.warn("set redis key error", e);
}
return result;
}
public void hset(String key, Map map){
key = getKey(key);
try {
redisTemplate.opsForHash().putAll(key,map);
}catch (Exception e) {
log.warn("hset redis key error", e);
}
}
public void expire(String key, long time) {
key = getKey(key);
if (exists(key)) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
}
public Object get(String key) {
key = getKey(key);
boolean isExist = exists(key);
if(!isExist)
return null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
return operations.get(key);
}
public Object hget(String hkey, String key) {
hkey = getKey(hkey);
boolean isExist = exists(hkey);
if(!isExist)
return null;
return redisTemplate.opsForHash().get(hkey,key);
}
public Map<String,String> hgetAll(String hkey) {
hkey = getKey(hkey);
boolean isExist = exists(hkey);
if(!isExist){
return null;
}
return redisTemplate.opsForHash().entries(hkey);
}
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
public long ttl(String key) {
key = getKey(key);
return redisTemplate.getExpire(key);
}
private String getKey(String key){
if (StringUtils.isEmpty(redisPrefix)) {
return key;
}
return redisPrefix + ":" + key;
}
public Set<String> scan(String matchKey) {
Set<String> keys = (Set<String>) redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> keysTmp = new HashSet<>();
Cursor<byte[]> cursor = connection.scan(new ScanOptions.ScanOptionsBuilder().match(matchKey).count(1000).build());
while (cursor.hasNext()) {
keysTmp.add(new String(cursor.next()));
}
return keysTmp;
});
return keys;
}
public List<String> getRedisKeys(String matchKey) {
List<String> list = new ArrayList<>();
RedisClusterConnection redisClusterConnection = redisTemplate.getConnectionFactory().getClusterConnection();
Map<String, JedisPool> clusterNodes = ((JedisCluster) redisClusterConnection.getNativeConnection()).getClusterNodes();
for (Map.Entry<String, JedisPool> entry : clusterNodes.entrySet()) {
Jedis jedis = entry.getValue().getResource();
if (!jedis.info("replication").contains("role:slave")) {
List<String> keys = getScan(jedis, matchKey);
if (keys.size() > 0) {
Map<Integer, List<String>> map = new HashMap<>(8);
for (String key : keys) {
int slot = JedisClusterCRC16.getSlot(key);
if (map.containsKey(slot)) {
map.get(slot).add(key);
} else {
List<String> list1 = new ArrayList();
list1.add(key);
map.put(slot, list1);
}
}
for (Map.Entry<Integer, List<String>> integerListEntry : map.entrySet()) {
list.addAll(integerListEntry.getValue());
}
}
}
}
return list;
}
public List<String> getScan(Jedis redisService, String key) {
List<String> list = new ArrayList<>();
ScanParams params = new ScanParams();
params.match(key);
params.count(100);
String cursor = "0";
ScanResult scanResult = redisService.scan(cursor, params);
while (null != scanResult.getStringCursor()) {
list.addAll(scanResult.getResult());
if (! "0".equals( scanResult.getStringCursor())) {
scanResult = redisService.scan(cursor, params);
} else {
break;
}
}
return list;
}
}