springboot整合redisson实现分布式锁

导入依赖

        <dependency>
            <groupId>org.redisson</groupId>
            <artifactId>redisson-spring-boot-starter</artifactId>
            <version>3.15.5</version>
        </dependency>

application.yml

spring:
  redis:
    host: localhost
    port: 6379
    database: 0
#    password: password
    timeout: 5000
    lettuce:
      pool:
        max-active: 8
        max-idle: 8
        min-idle: 0
        max-wait: -1ms
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/cs?characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
    username: root
    password: 123456
    driver-class-name: com.mysql.jdbc.Driver


redisson:
  codec: org.redisson.codec.JsonJacksonCodec


核心代码

	    RLock lock = redisson.getLock("myLock");
        lock.lock();//加锁
        try {
        	//业务代码
		 } finally {
            lock.unlock();//释放锁
        }

示例

package com.example.demo.service;


import com.example.demo.mapper.InventoryMapper;
import com.example.demo.pojo.Inventory;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class InventoryServiceImpl implements InventoryService {
    @Autowired
    private RedissonClient redisson;

    @Autowired
    private InventoryMapper inventoryMapper;

//传统方式使用 synchronized
    @Override
    public boolean lost() {
        RLock lock = redisson.getLock("myLock");
        lock.lock();//加锁
        try {
            Inventory inventory = inventoryMapper.selectById(1);//查询库存为1的库存数
            if (inventory.getNumber() > 0) {//有库存
                inventory.setNumber(inventory.getNumber() - 1);//库存-1
                int i = inventoryMapper.updateById(inventory);
                if (i > 0) {
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        } finally {
            lock.unlock();//释放锁
        }




    }
}

你可能感兴趣的:(java,spring,boot,java,spring)