数据库事务中的redis增改模板
if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { //redis增改操作 } }); } else { //redis增改操作 }
完整的封装代码
import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.*; import org.springframework.data.redis.core.script.DefaultRedisScript; import org.springframework.data.redis.serializer.RedisSerializer; import org.springframework.data.redis.support.atomic.RedisAtomicLong; import org.springframework.stereotype.Component; import org.springframework.transaction.support.TransactionSynchronizationAdapter; import org.springframework.transaction.support.TransactionSynchronizationManager; import javax.annotation.Resource; import java.util.*; import java.util.concurrent.TimeUnit; /** * redis操作工具 * * @author */ @Component @Slf4j public class RedisUtils { @Resource(name = "RedisTemplatePropr") private RedisTemplate redisTemplate; /** * 获取SpringDataRedis访问模板,操作String类型数据 * * @return */ public RedisTemplate<String, String> getRedisTemplateOpsString() { return redisTemplate; } /** * 获取SpringDataRedis访问模板,操作任意Object对象类型数据 * * @return */ private RedisTemplate<String, Object> getRedisTemplateOpsObject() { return redisTemplate; } /** * 获取SpringDataRedis访问模板,操作Map<String, String>类型数据 * * @return */ private RedisTemplate<String, Map<String, String>> getRedisTemplateOpsMap() { return redisTemplate; } public Cursor scan(String pattern, int limit) { ScanOptions options = ScanOptions.scanOptions().match(pattern).count(limit).build(); RedisSerializer<String> redisSerializer = (RedisSerializer<String>) getRedisTemplateOpsString().getKeySerializer(); return (Cursor) getRedisTemplateOpsString().executeWithStickyConnection(new RedisCallback() { @Override public Object doInRedis(RedisConnection redisConnection) throws DataAccessException { return new ConvertingCursor<>(redisConnection.scan(options), redisSerializer::deserialize); } }); } /** * 本地调用,存储String类型数据到缓存服务器,不设置有效期,永久有效 * * @param key * @param value * @return */ public void setString(String key, String value) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsString().opsForValue().set(key, value); } }); } else { getRedisTemplateOpsString().opsForValue().set(key, value); } } public boolean setString(String key, String value, long time) { try { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { if (time > 0) { getRedisTemplateOpsString().opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { setString(key, value); } } }); } else { if (time > 0) { getRedisTemplateOpsString().opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { setString(key, value); } } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * 本地调用,存储Hash类型数据到缓存服务器,设置有效期 * * @param key * @param fieldMap * @param timeout * @param unit */ public void setHashString(String key, Map<String, Object> fieldMap, long timeout, TimeUnit unit) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForHash().putAll(key, fieldMap); getRedisTemplateOpsObject().expire(key, timeout, unit); } }); } else { getRedisTemplateOpsObject().opsForHash().putAll(key, fieldMap); getRedisTemplateOpsObject().expire(key, timeout, unit); } } /** * 本地调用,存储Hash类型数据到缓存服务器,设置有效期 * * @param key * @param fieldMap */ public void setHashString(String key, Map<String, Object> fieldMap) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForHash().putAll(key, fieldMap); } }); } else { getRedisTemplateOpsObject().opsForHash().putAll(key, fieldMap); } } /** * 删除存储Hash元素 * * @param key * @param mapKey */ public void deleteHashString(String key, String mapKey) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForHash().delete(key, mapKey); } }); } else { getRedisTemplateOpsObject().opsForHash().delete(key, mapKey); } } /** * 本地调用,存储Hash类型部分数据到缓存服务器,设置有效期 * * @param key * @param field * @param value */ public void setHashPartString(String key, String field, Object value) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForHash().put(key, field, value); } }); } else { getRedisTemplateOpsObject().opsForHash().put(key, field, value); } } /** * 本地调用,存储Hash类型部分数据到缓存服务器,设置有效期 * * @param key * @param field * @param value * @param timeout * @param unit */ public void setHashPartString(String key, String field, Object value, long timeout, TimeUnit unit) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForHash().put(key, field, value); getRedisTemplateOpsObject().expire(key, timeout, unit); } }); } else { getRedisTemplateOpsObject().opsForHash().put(key, field, value); getRedisTemplateOpsObject().expire(key, timeout, unit); } } /** * 本地调用,根据key查询Hash类型数据 * * @param key */ public Map<String, Object> getHashString(String key) { Map<Object, Object> keys = getRedisTemplateOpsObject().opsForHash().entries(key); Map<String, Object> resMap = new HashMap<>(); for (Map.Entry<Object, Object> map : keys.entrySet()) { resMap.put((String) map.getKey(), map.getValue()); } return resMap; } /** * 本地调用,存储Map<String, String>类型数据到缓存服务器,不设置有效期,永久有效 * * @param key * @param value * @return */ public void setMapOfString(String key, Map<String, String> value) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsMap().opsForValue().set(key, value); } }); } else { getRedisTemplateOpsMap().opsForValue().set(key, value); } } /** * 本地调用,存储Map<String, String>类型数据到缓存服务器,设置有效期 * * @param key * @param value * @param timeout * @param unit */ public void setMapOfString(String key, Map<String, String> value, long timeout, TimeUnit unit) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsMap().opsForValue().set(key, value, timeout, unit); } }); } else { getRedisTemplateOpsMap().opsForValue().set(key, value, timeout, unit); } } /** * 本地调用,存储任意对象类型数据到缓存服务器,不设置有效期,永久有效 * * @param key * @param value * @return */ public void setObject(String key, Object value) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForValue().set(key, value); } }); } else { getRedisTemplateOpsObject().opsForValue().set(key, value); } } /** * 本地调用,存储任意对象类型数据到缓存服务器,设置有效期 * * @param key * @param value * @param timeout * @param unit */ public void setObject(String key, Object value, long timeout, TimeUnit unit) { getRedisTemplateOpsObject().opsForValue().set(key, value, timeout, unit); } /** * 本地调用,从缓存服务器获取String类型数据 * * @param key * @return */ public String getString(String key) { return getRedisTemplateOpsString().opsForValue().get(key); } /** * 本地调用,从缓存服务器获取Map<String, String>类型数据 * * @param key * @return */ public Map<String, String> getMapOfString(String key) { return getRedisTemplateOpsMap().opsForValue().get(key); } /** * set类型 * 获取集合剩余元素个数 * * @param key * @return size */ public long getSetSize(String key) { return getRedisTemplateOpsObject().opsForSet().size(key); } /** * 本地调用,从缓存服务器获取任意Object对象类型数据 * * @param key * @return */ public Object getObject(String key) { return getRedisTemplateOpsObject().opsForValue().get(key); } /** * 本地调用,从缓存服务器删除数据 * * @param key */ public void delete(String key) { if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { getRedisTemplateOpsObject().opsForValue().getOperations().delete(key); } }); } else { getRedisTemplateOpsObject().opsForValue().getOperations().delete(key); } } public void deleteKeys(String key) { Set<String> keys = getRedisTemplateOpsObject().opsForValue().getOperations().keys(key); if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { for (String s : keys) { if (!s.contains("sync")) { delete(s); } } } }); } else { for (String s : keys) { if (!s.contains("sync")) { delete(s); } } } } /** * 本地调用,从缓存服务器删除数据 * * @param key */ public void deleteHashKey(String key) { Set<Object> keys = getRedisTemplateOpsObject().opsForHash().keys(key); if (keys == null || keys.size() == 0) { return; } if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { for (Object hashKey : keys) { getRedisTemplateOpsObject().opsForHash().delete(key, hashKey); } } }); } else { for (Object hashKey : keys) { getRedisTemplateOpsObject().opsForHash().delete(key, hashKey); } } } /** * 本地调用,校验数据是否在缓存服务器上已存在 * * @param key * @return */ public boolean exists(String key) { boolean exists = false; long size = getRedisTemplateOpsObject().opsForValue().size(key); if (size > 0) { exists = true; } return exists; } /** * 本地调用,校验数据是否在缓存服务器上已存在 * * @param key * @return */ public boolean existsKey(String key) { return getRedisTemplateOpsObject().hasKey(key); } /** * 本地调用,校验Hash数据是否在缓存服务器上已存在 * * @param key * @return */ public boolean existsHashKey(String key) { boolean exists = false; long size = getRedisTemplateOpsObject().opsForHash().size(key); if (size > 0) { exists = true; } return exists; } /** * 获取key的剩余有效时间 * * @param key * @param timeUnit * @return */ public Long getTTL(String key, TimeUnit timeUnit) { return getRedisTemplateOpsObject().getExpire(key, timeUnit); } /** * 递增 * * @param key 键 * @param delta 要增加几(大于0) * @return */ public long incr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } final long[] result = new long[1]; if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { result[0] = getRedisTemplateOpsObject().opsForValue().increment(key, delta); } }); } else { result[0] = getRedisTemplateOpsObject().opsForValue().increment(key, delta); } return result[0]; } /** * 递减 * * @param key 键 * @param delta 要减少几(小于0) * @return */ public long decr(String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } final long[] result = new long[1]; if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { result[0] = getRedisTemplateOpsObject().opsForValue().increment(key, delta); } }); } else { result[0] = getRedisTemplateOpsObject().opsForValue().increment(key, delta); } return result[0]; } /** * 设置key和value值并设置时间如果key已经存在则返回false,如果不存在则返回true * * @param key * @param value * @return */ public boolean setIfAbsent(String key, String value, long timeout, TimeUnit unit) { final boolean[] result = new boolean[1]; if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { result[0] = getRedisTemplateOpsObject().opsForValue().setIfAbsent(key, value, timeout, unit); } }); } else { result[0] = getRedisTemplateOpsObject().opsForValue().setIfAbsent(key, value, timeout, unit); } return result[0]; } public Boolean unlock(String key, String value) { String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end"; DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class); Long execute = (Long) redisTemplate.execute(redisScript, Collections.singletonList(key), value); // 解锁成功"unlock success" return execute != null && execute != 0; } /** * 设置key和value值并设置时间如果key已经存在则返回false,如果不存在则返回true * * @param key * @param value * @return */ public boolean setIfAbsent(String key, String value) { final boolean[] result = new boolean[1]; if (TransactionSynchronizationManager.isActualTransactionActive()) { TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() { public void afterCommit() { result[0] = getRedisTemplateOpsObject().opsForValue().setIfAbsent(key, value); } }); } else { result[0] = getRedisTemplateOpsObject().opsForValue().setIfAbsent(key, value); } return result[0] ; } }