Redis 事务可以一次执行多个命令, 并且带有以下两个重要的保证:
- 事务是一个单独的隔离操作:事务中的所有命令都会序列化、按顺序地执行。事务在执行的过程中,不会被其他客户端发送来的命令请求所打断。
- 事务是一个原子操作:事务中的命令要么全部被执行,要么全部都不执行。
一个事务从开始到执行会经历以下三个阶段:
a. 开始事务。
b. 命令入队。
c. 执行事务。
redis集群对象JedisCluster不支持事务,但是,集群里边的每个节点支持事务。
以下是一个事务的例子, 它先以 MULTI 开始一个事务, 然后将多个命令入队到事务中, 最后由 EXEC 命令触发事务, 一并执行事务中的所有命令:
redis 127.0.0.1:6379> MULTI
OK
redis 127.0.0.1:6379> SET book-name "Mastering C++ in 21 days"
QUEUED
redis 127.0.0.1:6379> GET book-name
QUEUED
redis 127.0.0.1:6379> SADD tag "C++" "Programming" "Mastering Series"
QUEUED
redis 127.0.0.1:6379> SMEMBERS tag
QUEUED
redis 127.0.0.1:6379> EXEC
1) OK
2) "Mastering C++ in 21 days"
3) (integer) 3
4) 1) "Mastering Series"
2) "C++"
3) "Programming"
SpringBoot操作Redis事务
public void setString(String key, Object object) {
stringRedisTemplate.setEnableTransactionSupport(true);
// 开启事务
stringRedisTemplate.multi();
try {
// 如果是String 类型
String value = (String) object;
stringRedisTemplate.opsForValue().set(key, value);
} catch (Exception e) {
// 回滚
stringRedisTemplate.discard();
} finally {
// 提交
stringRedisTemplate.exec();
}
}
AOP实现Redis 注解事务
Redis 事务注解
/**
* Redis 事务注解
* @author xiaoming
* @Date 2019/11/7
*/
@Target(value = ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface ExtRedisTranscation {
}
aop 实现
@Component
@Aspect
public class AopRedisTransaction {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@AfterThrowing("execution(* com.xiaoming.service.*.*(..))")
public void afterThrowing(){
System.out.println("程序已经回滚");
stringRedisTemplate.discard();
}
@Around("execution(* com.xiaoming.service.*.*(..))")
public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
Method method = signature.getMethod();
ExtRedisTranscation annotation = method.getAnnotation(ExtRedisTranscation.class);
if (annotation != null) {
System.out.println("开启事务");
//开启事务权限
stringRedisTemplate.setEnableTransactionSupport(true);
stringRedisTemplate.multi();
Object proceed = proceedingJoinPoint.proceed();
stringRedisTemplate.exec();
System.out.println("提交事务");
return proceed;
}
return proceedingJoinPoint.proceed();
}
}
service 中使用
@ExtRedisTranscation
public void setString(String key, Object object, Long time){
String value = (String) object;
stringRedisTemplate.opsForValue().set(key, value);
/*//开启事务权限
stringRedisTemplate.setEnableTransactionSupport(true);
//开启事务
stringRedisTemplate.multi();
try {
String value = (String) object;
stringRedisTemplate.opsForValue().set(key, value);
} catch (Exception e) {
//事务回滚
stringRedisTemplate.discard();
} finally {
//提交事务
stringRedisTemplate.exec();
}*/
}