高并发之商品秒杀系统

一基于redis

利用redis的乐观锁,实现秒杀系统的数据同步(基于watch实现),

用户一:

复制代码
import redis

conn = redis.Redis(host='127.0.0.1',port=6379)

# conn.set('count',1000)

with conn.pipeline() as pipe:

    # 先监视,自己的值没有被修改过
    conn.watch('count')

    # 事务开始
    pipe.multi()
    old_count = conn.get('count')
    count = int(old_count)
    input('我考虑一下')
    if count > 0:  # 有库存
        pipe.set('count', count - 1)

    # 执行,把所有命令一次性推送过去
    pipe.execute()
    ret = pipe.execute()
    print(type(ret))
    print(ret)
复制代码

用户二:

复制代码
import redis

conn = redis.Redis(host='127.0.0.1',port=6379)

with conn.pipeline() as pipe:

    # 先监视,自己的值没有被修改过
    conn.watch('count')

    # 事务开始
    pipe.multi()
    old_count = conn.get('count')
    count = int(old_count)
    if count > 0:  # 有库存
        pipe.set('count', count - 1)

    # 执行,把所有命令一次性推送过去
    ret=pipe.execute()
    print(type(ret))
复制代码

注:windows下如果数据被修改了,不会抛异常,只是返回结果的列表为空,mac和linux会直接抛异常

秒杀系统核心逻辑测试,创建100个线程并发秒杀

import redis
from threading import Thread

def choose(name, conn):
    # conn.set('count',10)
    with conn.pipeline() as pipe:
        # 先监视,自己的值没有被修改过
        conn.watch('count')
        # 事务开始
        pipe.multi()
        old_count = conn.get('count')
        count = int(old_count)
        # input('我考虑一下')
        # time.sleep(random.randint(1, 2))
        if count > 0:  # 有库存
            pipe.set('count', count - 1)

        # 执行,把所有命令一次性推送过去
        ret = pipe.execute()
        print(ret)
        if len(ret) > 0:
            print('第%s个人抢购成功' % name)
        else:
            print('第%s个人抢购失败' % name)


if __name__ == '__main__':
    conn = redis.Redis(host='127.0.0.1', port=6379)
    for i in range(100):

        t = Thread(target=choose, args=(i, conn))
        t.start()
View Code

二 基于mysql

一乐观锁


 总是认为不会产生并发问题,每次去取数据的时候总认为不会有其他线程对数据进行修改,因此不会上锁,但是在更新时会判断其他线程在这之前有没有对数据进行修改,一般会使用版本号机制或CAS操作实现。

 version方式:一般是在数据表中加上一个数据版本号version字段,表示数据被修改的次数,当数据被修改时,version值会加一。当线程A要更新数据值时,在读取数据的同时也会读取version值,在提交更新时,若刚才读取到的version值为当前数据库中的version值相等时才更新,否则重试更新操作,直到更新成功。

核心SQL代码:

update table set x=x+1, version=version+1 where id=#{id} and version=#{version};  


 CAS操作方式:即compare and swap 或者 compare and set,涉及到三个操作数,数据所在的内存值,预期值,新值。当需要更新时,判断当前内存值与之前取到的值是否相等,若相等,则用新值更新,若失败则重试,一般情况下是一个自旋操作,即不断的重试。

二悲观锁


 总是假设最坏的情况,每次取数据时都认为其他线程会修改,所以都会加锁(读锁、写锁、行锁等),当其他线程想要访问数据时,都需要阻塞挂起。可以依靠数据库实现,如行锁、读锁和写锁等,都是在操作之前加锁,在Java中,synchronized的思想也是悲观锁。

原文地址:https://www.cnblogs.com/bubu99/p/14774506.html