Redis的事务提供了一种将多个命令请求打包,然后一次性、按顺序性地执行多个命令的机制。
在事务执行期间,服务器不会中断事务而去执行其它客户端的命令请求,它会将事务中的所有命令执行完毕,然后才去处理其它客户端的命令请求。
事务以MULTI命令开始,然后将多个命令放到事务当中,最后由EXEC命令将这个事务提交给服务器执行。
1.引入相关jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<version>2.7.0</version>
</dependency>
2.代码段
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.UUID;
/**
* @author lucifer
* @description TODO
* @date 2022-08-10
*/
@RestController
public class Controller {
@Autowired
RedisTemplate redisTemplate;
//写入缓存中,因为这里的模拟的是一个商品被多人抢,所以value值随便吧
@GetMapping("/test1")
public void test1(){
redisTemplate.opsForValue().set("item1",UUID.randomUUID().toString());
}
//模拟多人抢一个商品,并且只有一件
@GetMapping("/test")
public String test(){
//生成随机的userid(模拟多用户去抢一个商品)
String userid=UUID.randomUUID().toString();
//redis key 商品id 为了模拟写成1
String key="item"+1;
//如果redis中不存在抢这个商品的缓存,就代表抢失败
//商品独一份
if(!redisTemplate.hasKey(key)){
throw new RuntimeException("你没有抢到");
}
//执行redis的事务
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
//在使用multi()开始的事务期间观察给定的修改key
operations.watch(key);
//标记事务块的开始。 命令将被排队
operations.multi();
//设置key-value
operations.opsForValue().set(key,userid);
//如果任何被监视的key已被修改,则操作将失败
return operations.exec();
}
});
//删除 避免这个商品被其他人抢到了
redisTemplate.delete(key);
//todo....数据库操作
return "你抢到了";
}
}
3.测试
用50个线程并发去调用接口,模拟多人并发抢商品的功能;