Skip to content

Commit

Permalink
add different lock, add sleep, update readme
Browse files Browse the repository at this point in the history
  • Loading branch information
yennanliu committed Feb 17, 2024
1 parent a03165c commit 948273a
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 4 deletions.
7 changes: 6 additions & 1 deletion springBank/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,9 +121,14 @@ docker-compose restart

#---------------------------
# Macbook apple M1 chip
#---------------------------
#---------------------------

# run
docker-compose -f docker-compose-m1.yml up

# rebuild (use updated java code) and run
docker-compose -f docker-compose-m1.yml up --build

# restart
docker-compose -f docker-compose-m1.yml restart
```
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import com.yen.springBankApp.repository.BalanceRepository;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RReadWriteLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
Expand Down Expand Up @@ -84,12 +85,17 @@ public void deductBalance(DeductBalanceDto deductBalanceDto) {
log.info(">>> (BalanceServiceRedisson) deductBalance start ...");

// get lock
RLock lock = redissonClient.getLock("lock");
//RLock lock = redissonClient.getLock("lock");
RReadWriteLock rwLock = redissonClient.getReadWriteLock("rwLock");

// lock
lock.lock();
//lock.lock();
rwLock.writeLock();

try{
// sleep 10 sec
Thread.sleep(10000);

// 1) get stock amount
// set up "balance" as String type in Redis, with value = 5000
// https://github.com/yennanliu/SpringPlayground/blob/main/springBank/doc/pic/redis_key_setting.png
Expand All @@ -111,7 +117,8 @@ public void deductBalance(DeductBalanceDto deductBalanceDto) {
e.printStackTrace();
}finally {
// unlock
lock.unlock();
//lock.unlock();
rwLock.writeLock().unlock();
}
}

Expand Down Expand Up @@ -168,6 +175,9 @@ public void transferMysql(DeductBalanceDto deductBalanceDto) {
try{
// V2 : Mysql
if (balanceRepository.findById(1).isPresent() && balanceRepository.findById(2).isPresent()){

Thread.sleep(10000);

Balance balance1 = balanceRepository.findById(1).get();
Balance balance2 = balanceRepository.findById(2).get();
// update to DB
Expand Down

0 comments on commit 948273a

Please sign in to comment.