修改问题

This commit is contained in:
lpphan
2022-03-18 10:25:21 +08:00
committed by hanzhishun
parent e6562296b2
commit dca9c071f7
3 changed files with 505 additions and 501 deletions
@@ -1,495 +1,498 @@
package com.central.common.redis.template; package com.central.common.redis.template;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException; import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisClusterNode; import org.springframework.data.redis.connection.RedisClusterNode;
import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisServerCommands; import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.*;
import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationUtils; import org.springframework.data.redis.serializer.SerializationUtils;
import org.springframework.util.Assert; import org.springframework.util.Assert;
import java.util.*; import java.util.*;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
/** /**
* Redis Repository * Redis Repository
* redis 基本操作 可扩展,基本够用了 * redis 基本操作 可扩展,基本够用了
* *
* @author zlt * @author zlt
* <p> * <p>
* Blog: https://zlt2000.gitee.io * Blog: https://zlt2000.gitee.io
* Github: https://github.com/zlt2000 * Github: https://github.com/zlt2000
*/ */
@Slf4j @Slf4j
public class RedisRepository { public class RedisRepository {
/** /**
* Spring Redis Template * Spring Redis Template
*/ */
private RedisTemplate<String, Object> redisTemplate; private RedisTemplate<String, Object> redisTemplate;
public RedisRepository(RedisTemplate<String, Object> redisTemplate) { public RedisRepository(RedisTemplate<String, Object> redisTemplate) {
this.redisTemplate = redisTemplate; this.redisTemplate = redisTemplate;
} }
/** /**
* 获取链接工厂 * 获取链接工厂
*/ */
public RedisConnectionFactory getConnectionFactory() { public RedisConnectionFactory getConnectionFactory() {
return this.redisTemplate.getConnectionFactory(); return this.redisTemplate.getConnectionFactory();
} }
/** /**
* 获取 RedisTemplate对象 * 获取 RedisTemplate对象
*/ */
public RedisTemplate<String, Object> getRedisTemplate() { public RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate; return redisTemplate;
} }
/** /**
* 清空DB * 清空DB
* *
* @param node redis 节点 * @param node redis 节点
*/ */
public void flushDB(RedisClusterNode node) { public void flushDB(RedisClusterNode node) {
this.redisTemplate.opsForCluster().flushDb(node); this.redisTemplate.opsForCluster().flushDb(node);
} }
/** /**
* 添加到带有 过期时间的 缓存 * 添加到带有 过期时间的 缓存
* *
* @param key redis主键 * @param key redis主键
* @param value 值 * @param value 值
* @param time 过期时间(单位秒) * @param time 过期时间(单位秒)
*/ */
public void setExpire(final byte[] key, final byte[] value, final long time) { public void setExpire(final byte[] key, final byte[] value, final long time) {
redisTemplate.execute((RedisCallback<Long>) connection -> { redisTemplate.execute((RedisCallback<Long>) connection -> {
connection.setEx(key, time, value); connection.setEx(key, time, value);
return 1L; return 1L;
}); });
} }
/** /**
* 添加到带有 过期时间的 缓存 * 添加到带有 过期时间的 缓存
* *
* @param key redis主键 * @param key redis主键
* @param value 值 * @param value 值
* @param time 过期时间 * @param time 过期时间
* @param timeUnit 过期时间单位 * @param timeUnit 过期时间单位
*/ */
public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit) { public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit) {
redisTemplate.opsForValue().set(key, value, time, timeUnit); redisTemplate.opsForValue().set(key, value, time, timeUnit);
} }
public void setExpire(final String key, final Object value, final long time) { public void setExpire(final String key, final Object value, final long time) {
this.setExpire(key, value, time, TimeUnit.SECONDS); this.setExpire(key, value, time, TimeUnit.SECONDS);
} }
public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit, RedisSerializer<Object> valueSerializer) { public void setExpire(final String key, final Object value, final long time, final TimeUnit timeUnit, RedisSerializer<Object> valueSerializer) {
byte[] rawKey = rawKey(key); byte[] rawKey = rawKey(key);
byte[] rawValue = rawValue(value, valueSerializer); byte[] rawValue = rawValue(value, valueSerializer);
redisTemplate.execute(new RedisCallback<Object>() { redisTemplate.execute(new RedisCallback<Object>() {
@Override @Override
public Object doInRedis(RedisConnection connection) throws DataAccessException { public Object doInRedis(RedisConnection connection) throws DataAccessException {
potentiallyUsePsetEx(connection); potentiallyUsePsetEx(connection);
return null; return null;
} }
public void potentiallyUsePsetEx(RedisConnection connection) { public void potentiallyUsePsetEx(RedisConnection connection) {
if (!TimeUnit.MILLISECONDS.equals(timeUnit) || !failsafeInvokePsetEx(connection)) { if (!TimeUnit.MILLISECONDS.equals(timeUnit) || !failsafeInvokePsetEx(connection)) {
connection.setEx(rawKey, TimeoutUtils.toSeconds(time, timeUnit), rawValue); connection.setEx(rawKey, TimeoutUtils.toSeconds(time, timeUnit), rawValue);
} }
} }
private boolean failsafeInvokePsetEx(RedisConnection connection) { private boolean failsafeInvokePsetEx(RedisConnection connection) {
boolean failed = false; boolean failed = false;
try { try {
connection.pSetEx(rawKey, time, rawValue); connection.pSetEx(rawKey, time, rawValue);
} catch (UnsupportedOperationException e) { } catch (UnsupportedOperationException e) {
failed = true; failed = true;
} }
return !failed; return !failed;
} }
}, true); }, true);
} }
/** /**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
* *
* @param keys redis主键数组 * @param keys redis主键数组
* @param values 值数组 * @param values 值数组
* @param time 过期时间(单位秒) * @param time 过期时间(单位秒)
*/ */
public void setExpire(final String[] keys, final Object[] values, final long time) { public void setExpire(final String[] keys, final Object[] values, final long time) {
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
redisTemplate.opsForValue().set(keys[i], values[i], time, TimeUnit.SECONDS); redisTemplate.opsForValue().set(keys[i], values[i], time, TimeUnit.SECONDS);
} }
} }
/** /**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销 * 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
* *
* @param keys the keys * @param keys the keys
* @param values the values * @param values the values
*/ */
public void set(final String[] keys, final Object[] values) { public void set(final String[] keys, final Object[] values) {
for (int i = 0; i < keys.length; i++) { for (int i = 0; i < keys.length; i++) {
redisTemplate.opsForValue().set(keys[i], values[i]); redisTemplate.opsForValue().set(keys[i], values[i]);
} }
} }
/** /**
* 添加到缓存 * 添加到缓存
* *
* @param key the key * @param key the key
* @param value the value * @param value the value
*/ */
public void set(final String key, final Object value) { public void set(final String key, final Object value) {
redisTemplate.opsForValue().set(key, value); redisTemplate.opsForValue().set(key, value);
} }
/** /**
* 查询在以keyPatten的所有 key * 查询在以keyPatten的所有 key
* *
* @param keyPatten the key patten * @param keyPatten the key patten
* @return the set * @return the set
*/ */
public Set<String> keys(final String keyPatten) { public Set<String> keys(final String keyPatten) {
return redisTemplate.keys(keyPatten + "*"); return redisTemplate.keys(keyPatten + "*");
} }
/** /**
* 根据key获取对象 * 根据key获取对象
* *
* @param key the key * @param key the key
* @return the byte [ ] * @return the byte [ ]
*/ */
public byte[] get(final byte[] key) { public byte[] get(final byte[] key) {
return redisTemplate.execute((RedisCallback<byte[]>) connection -> connection.get(key)); return redisTemplate.execute((RedisCallback<byte[]>) connection -> connection.get(key));
} }
/** /**
* 根据key获取对象 * 根据key获取对象
* *
* @param key the key * @param key the key
* @return the string * @return the string
*/ */
public Object get(final String key) { public Object get(final String key) {
return redisTemplate.opsForValue().get(key); return redisTemplate.opsForValue().get(key);
} }
/** /**
*获取原来key键对应的值并重新赋新值。 *获取原来key键对应的值并重新赋新值。
* @param key * @param key
* @param value * @param value
* @return * @return
*/ */
public String getAndSet(final String key,Object value) { public String getAndSet(final String key,String value) {
String result = null; String result = null;
if (StringUtils.isEmpty(key)){ if (StringUtils.isEmpty(key)){
log.error("key不能为空"); log.error("非法入参");
return null; return null;
} }
try { try {
result = (String) redisTemplate.opsForValue().getAndSet(key, value); Object object =redisTemplate.opsForValue().getAndSet(key, value);
}catch (Exception e){ if (object !=null){
e.printStackTrace(); result = object.toString();
} }
return result; }catch (Exception e){
} log.error("redisTemplate操作异常",e);
/** }
* 根据key获取对象 return result;
* }
* @param key the key /**
* @param valueSerializer 序列化 * 根据key获取对象
* @return the string *
*/ * @param key the key
public Object get(final String key, RedisSerializer<Object> valueSerializer) { * @param valueSerializer 序列化
byte[] rawKey = rawKey(key); * @return the string
return redisTemplate.execute(connection -> deserializeValue(connection.get(rawKey), valueSerializer), true); */
} public Object get(final String key, RedisSerializer<Object> valueSerializer) {
byte[] rawKey = rawKey(key);
return redisTemplate.execute(connection -> deserializeValue(connection.get(rawKey), valueSerializer), true);
/** }
* Ops for hash hash operations.
*
* @return the hash operations /**
*/ * Ops for hash hash operations.
public HashOperations<String, String, Object> opsForHash() { *
return redisTemplate.opsForHash(); * @return the hash operations
} */
public HashOperations<String, String, Object> opsForHash() {
/** return redisTemplate.opsForHash();
* 对HashMap操作 }
*
* @param key the key /**
* @param hashKey the hash key * 对HashMap操作
* @param hashValue the hash value *
*/ * @param key the key
public void putHashValue(String key, String hashKey, Object hashValue) { * @param hashKey the hash key
opsForHash().put(key, hashKey, hashValue); * @param hashValue the hash value
} */
public void putHashValue(String key, String hashKey, Object hashValue) {
/** opsForHash().put(key, hashKey, hashValue);
* 获取单个field对应的值 }
*
* @param key the key /**
* @param hashKey the hash key * 获取单个field对应的值
* @return the hash values *
*/ * @param key the key
public Object getHashValues(String key, String hashKey) { * @param hashKey the hash key
return opsForHash().get(key, hashKey); * @return the hash values
} */
public Object getHashValues(String key, String hashKey) {
/** return opsForHash().get(key, hashKey);
* 根据key值删除 }
*
* @param key the key /**
* @param hashKeys the hash keys * 根据key值删除
*/ *
public void delHashValues(String key, Object... hashKeys) { * @param key the key
opsForHash().delete(key, hashKeys); * @param hashKeys the hash keys
} */
public void delHashValues(String key, Object... hashKeys) {
/** opsForHash().delete(key, hashKeys);
* key只匹配map }
*
* @param key the key /**
* @return the hash value * key只匹配map
*/ *
public Map<String, Object> getHashValue(String key) { * @param key the key
return opsForHash().entries(key); * @return the hash value
} */
public Map<String, Object> getHashValue(String key) {
/** return opsForHash().entries(key);
* 批量添加 }
*
* @param key the key /**
* @param map the map * 批量添加
*/ *
public void putHashValues(String key, Map<String, Object> map) { * @param key the key
opsForHash().putAll(key, map); * @param map the map
} */
public void putHashValues(String key, Map<String, Object> map) {
/** opsForHash().putAll(key, map);
* 集合数量 }
*
* @return the long /**
*/ * 集合数量
public long dbSize() { *
return redisTemplate.execute(RedisServerCommands::dbSize); * @return the long
} */
public long dbSize() {
/** return redisTemplate.execute(RedisServerCommands::dbSize);
* 清空redis存储的数据 }
*
* @return the string /**
*/ * 清空redis存储的数据
public String flushDB() { *
return redisTemplate.execute((RedisCallback<String>) connection -> { * @return the string
connection.flushDb(); */
return "ok"; public String flushDB() {
}); return redisTemplate.execute((RedisCallback<String>) connection -> {
} connection.flushDb();
return "ok";
/** });
* 判断某个主键是否存在 }
*
* @param key the key /**
* @return the boolean * 判断某个主键是否存在
*/ *
public boolean exists(final String key) { * @param key the key
return redisTemplate.hasKey(key); * @return the boolean
} */
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
/** }
* 删除key
*
* @param keys the keys /**
* @return the long * 删除key
*/ *
public boolean del(final String... keys) { * @param keys the keys
boolean result = false; * @return the long
for (String key : keys) { */
result = redisTemplate.delete(key); public boolean del(final String... keys) {
} boolean result = false;
return result; for (String key : keys) {
} result = redisTemplate.delete(key);
}
/** return result;
* 对某个主键对应的值加一,value值必须是全数字的字符串 }
*
* @param key the key /**
* @return the long * 对某个主键对应的值加一,value值必须是全数字的字符串
*/ *
public long incr(final String key) { * @param key the key
return redisTemplate.opsForValue().increment(key); * @return the long
} */
public long incr(final String key) {
/** return redisTemplate.opsForValue().increment(key);
* redis List 引擎 }
*
* @return the list operations /**
*/ * redis List 引擎
public ListOperations<String, Object> opsForList() { *
return redisTemplate.opsForList(); * @return the list operations
} */
public ListOperations<String, Object> opsForList() {
/** return redisTemplate.opsForList();
* redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头 }
*
* @param key the key /**
* @param value the value * redis List数据结构 : 将一个或多个值 value 插入到列表 key 的表头
* @return the long *
*/ * @param key the key
public Long leftPush(String key, Object value) { * @param value the value
return opsForList().leftPush(key, value); * @return the long
} */
public Long leftPush(String key, Object value) {
/** return opsForList().leftPush(key, value);
* redis List数据结构 : 移除并返回列表 key 的头元素 }
*
* @param key the key /**
* @return the string * redis List数据结构 : 移除并返回列表 key 的头元素
*/ *
public Object leftPop(String key) { * @param key the key
return opsForList().leftPop(key); * @return the string
} */
public Object leftPop(String key) {
/** return opsForList().leftPop(key);
* redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。 }
*
* @param key the key /**
* @param value the value * redis List数据结构 :将一个或多个值 value 插入到列表 key 的表尾(最右边)。
* @return the long *
*/ * @param key the key
public Long in(String key, Object value) { * @param value the value
return opsForList().rightPush(key, value); * @return the long
} */
public Long in(String key, Object value) {
/** return opsForList().rightPush(key, value);
* redis List数据结构 : 移除并返回列表 key 的末尾元素 }
*
* @param key the key /**
* @return the string * redis List数据结构 : 移除并返回列表 key 的末尾元素
*/ *
public Object rightPop(String key) { * @param key the key
return opsForList().rightPop(key); * @return the string
} */
public Object rightPop(String key) {
return opsForList().rightPop(key);
/** }
* redis List数据结构 : 返回列表 key 的长度 ; 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ; 如果 key 不是列表类型,返回一个错误。
*
* @param key the key /**
* @return the long * redis List数据结构 : 返回列表 key 的长度 ; 如果 key 不存在,则 key 被解释为一个空列表,返回 0 ; 如果 key 不是列表类型,返回一个错误。
*/ *
public Long length(String key) { * @param key the key
return opsForList().size(key); * @return the long
} */
public Long length(String key) {
return opsForList().size(key);
/** }
* redis List数据结构 : 根据参数 i 的值,移除列表中与参数 value 相等的元素
*
* @param key the key /**
* @param i the * redis List数据结构 : 根据参数 i 的值,移除列表中与参数 value 相等的元素
* @param value the value *
*/ * @param key the key
public void remove(String key, long i, Object value) { * @param i the
opsForList().remove(key, i, value); * @param value the value
} */
public void remove(String key, long i, Object value) {
/** opsForList().remove(key, i, value);
* redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value }
*
* @param key the key /**
* @param index the index * redis List数据结构 : 将列表 key 下标为 index 的元素的值设置为 value
* @param value the value *
*/ * @param key the key
public void set(String key, long index, Object value) { * @param index the index
opsForList().set(key, index, value); * @param value the value
} */
public void set(String key, long index, Object value) {
/** opsForList().set(key, index, value);
* redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。 }
*
* @param key the key /**
* @param start the start * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
* @param end the end *
* @return the list * @param key the key
*/ * @param start the start
public List<Object> getList(String key, int start, int end) { * @param end the end
return opsForList().range(key, start, end); * @return the list
} */
public List<Object> getList(String key, int start, int end) {
/** return opsForList().range(key, start, end);
* redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。 }
*
* @param key the key /**
* @param start the start * redis List数据结构 : 返回列表 key 中指定区间内的元素,区间以偏移量 start 和 end 指定。
* @param end the end *
* @param valueSerializer 序列化 * @param key the key
* @return the list * @param start the start
*/ * @param end the end
public List<Object> getList(String key, int start, int end, RedisSerializer<Object> valueSerializer) { * @param valueSerializer 序列化
byte[] rawKey = rawKey(key); * @return the list
return redisTemplate.execute(connection -> deserializeValues(connection.lRange(rawKey, start, end), valueSerializer), true); */
} public List<Object> getList(String key, int start, int end, RedisSerializer<Object> valueSerializer) {
byte[] rawKey = rawKey(key);
/** return redisTemplate.execute(connection -> deserializeValues(connection.lRange(rawKey, start, end), valueSerializer), true);
* redis List数据结构 : 批量存储 }
*
* @param key the key /**
* @param list the list * redis List数据结构 : 批量存储
* @return the long *
*/ * @param key the key
public Long leftPushAll(String key, List<String> list) { * @param list the list
return opsForList().leftPushAll(key, list); * @return the long
} */
public Long leftPushAll(String key, List<String> list) {
/** return opsForList().leftPushAll(key, list);
* redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index 之前或之后,默认之后。 }
*
* @param key the key /**
* @param index the index * redis List数据结构 : 将值 value 插入到列表 key 当中,位于值 index 之前或之后,默认之后。
* @param value the value *
*/ * @param key the key
public void insert(String key, long index, Object value) { * @param index the index
opsForList().set(key, index, value); * @param value the value
} */
public void insert(String key, long index, Object value) {
private byte[] rawKey(Object key) { opsForList().set(key, index, value);
Assert.notNull(key, "non null key required"); }
if (key instanceof byte[]) { private byte[] rawKey(Object key) {
return (byte[]) key; Assert.notNull(key, "non null key required");
}
RedisSerializer<Object> redisSerializer = (RedisSerializer<Object>)redisTemplate.getKeySerializer(); if (key instanceof byte[]) {
return redisSerializer.serialize(key); return (byte[]) key;
} }
private byte[] rawValue(Object value, RedisSerializer valueSerializer) { RedisSerializer<Object> redisSerializer = (RedisSerializer<Object>)redisTemplate.getKeySerializer();
if (value instanceof byte[]) { return redisSerializer.serialize(key);
return (byte[]) value; }
} private byte[] rawValue(Object value, RedisSerializer valueSerializer) {
if (value instanceof byte[]) {
return valueSerializer.serialize(value); return (byte[]) value;
} }
private List deserializeValues(List<byte[]> rawValues, RedisSerializer<Object> valueSerializer) { return valueSerializer.serialize(value);
if (valueSerializer == null) { }
return rawValues;
} private List deserializeValues(List<byte[]> rawValues, RedisSerializer<Object> valueSerializer) {
return SerializationUtils.deserialize(rawValues, valueSerializer); if (valueSerializer == null) {
} return rawValues;
}
private Object deserializeValue(byte[] value, RedisSerializer<Object> valueSerializer) { return SerializationUtils.deserialize(rawValues, valueSerializer);
if (valueSerializer == null) { }
return value;
} private Object deserializeValue(byte[] value, RedisSerializer<Object> valueSerializer) {
return valueSerializer.deserialize(value); if (valueSerializer == null) {
} return value;
} }
return valueSerializer.deserialize(value);
}
}
@@ -16,9 +16,9 @@ import org.springframework.data.redis.listener.RedisMessageListenerContainer;
public class RedisListenerConfig { public class RedisListenerConfig {
@Bean @Bean
@Primary @Primary
public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory connectionFactory) { public RedisMessageListenerContainer redisMessageListenerContainer(RedisConnectionFactory factory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer(); RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory); container.setConnectionFactory(factory);
return container; return container;
} }
} }
@@ -54,9 +54,10 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
} }
String accessValue = expiredKey.substring(expiredKey.indexOf(":") + 1); String accessValue = expiredKey.substring(expiredKey.indexOf(":") + 1);
// 分布式集群部署下防止一个过期被多个服务重复消费 // 分布式集群部署下防止一个过期被多个服务重复消费
String qc = redisRepository.getAndSet("qc:" + accessValue, "1"); String qc = "qc:" + accessValue;
if (StringUtils.isNotEmpty(qc) && "1".equals(qc)) { String oldLock = redisRepository.getAndSet(qc, "1");
log.debug("其他节点已经处理了该数据,次数跳过"); if (StringUtils.isNotEmpty(oldLock) && "1".equals(oldLock)) {
log.debug("其他节点已经处理了该数据,跳过");
return; return;
} }
byte[] accessBakKey = serializeKey(SecurityConstants.ACCESS_BAK + accessValue); byte[] accessBakKey = serializeKey(SecurityConstants.ACCESS_BAK + accessValue);
@@ -77,7 +78,7 @@ public class RedisKeyExpirationListener extends KeyExpirationEventMessageListene
} catch (Exception e) { } catch (Exception e) {
log.error(e.getMessage()); log.error(e.getMessage());
} finally { } finally {
conn.del(); conn.del(oldLock.getBytes());
conn.close(); conn.close();
} }