Redis事物
事物的开启与取消
- 开启事物 multi
- 执行事物 exec 设定事务的结束位置,同时执行事务。与multi成对出现,成对使用
- 取消事物 discard 终止当前事务的定义,发生在multi之后,exec之前
事物锁
对 key 添加监视锁,在执行exec前如果key发生了变化,终止事务执行
- watch key1 [key2……]
取消对所有 key 的监视
- unwatch
使用 setnx 设置一个公共锁
-
setnx lock-key value
利用setnx命令的返回值特征,有值则返回设置失败,无值则返回设置成功
对于返回设置成功的,拥有控制权,进行下一步的具体业务操作
对于返回设置失败的,不具有控制权,排队或等待 -
del key 释放锁
-
expire lock-key second 设置锁的到期时间
-
pexpire lock-key milliseconds 设置锁的到期时间
Redssion
public RedissonClient redisson() {
Config config = new Config();
SingleServerConfig singleServerConfig = config.useSingleServer();
singleServerConfig.setAddress("redis://" + host + ":" + port);
singleServerConfig.setTimeout(timeout);
singleServerConfig.setDatabase(database);
if (password != null && !"".equals(password)) { //有密码
singleServerConfig.setPassword(password);
}
return Redisson.create(config);
}
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.7.5</version>
</dependency>