当前位置: 代码网 > it编程>数据库>Redis > redis事务如何解决超卖问题

redis事务如何解决超卖问题

2024年11月05日 Redis 我要评论
redis事务解决超卖问题redis的事务提供了一种将多个命令请求打包,然后一次性、按顺序性地执行多个命令的机制。在事务执行期间,服务器不会中断事务而去执行其它客户端的命令请求,它会将事务中的所有命令

redis事务解决超卖问题

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个线程并发去调用接口,模拟多人并发抢商品的功能;

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com