Java-Interview-Advanced/docs/distributed-system/highly-concurrent-distribut...

27 lines
1.3 KiB
Markdown
Executable File
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

分段加锁
有好多同学出去面试,聊到分布式锁这块,都被人考察分布式锁能不能抗高并发的问题了
对某个商品下单,对一个分布式锁每秒突然有上万请求过来,都要进行加锁,此时怎么办呢?可能就会导致你
比如你的苹果库存有10000个此时你在数据库中创建10个库存字段
一个表里有10个库存字段stock_01stock_02每个库存字段里放1000个库存
此时这个库存的分布式锁对应10个keyproduct_1_stock_01product_1_stock_02
请求过来之后你从10个key随机选择一个key去加锁就可以了每秒过来1万个请求此时他们会对10个库存分段key加锁每个key就1000个请求每台服务器就1000个请求而已
万一说某个库存分段仅仅剩余10个库存了此时我下订单要买20个苹果合并扣减库存你对product_1_stock_5加锁了此时查询对应的数据库中的库存此时库存是10个不够买20个苹果
你可以尝试去锁product_1_stock_1再查询他的库存可能有30个
此时你就可以下订单锁定库存的时候就对product_1_stock_5锁定10个库存对product_1_stock1锁定10个库存锁定了20个库存
分段加锁 + 合并扣减