分布式锁:满足分布式系统或集群模式下多进程可见并且互斥的锁。
跨机器进程间数据同步问题
我们用第三种 悲观锁
加入依赖
<!-- redis分布式锁 --> <dependency> <groupId>com.baomidou</groupId> <artifactId>lock4j-redisson-spring-boot-starter</artifactId> <version>2.2.2</version> </dependency>
核心代码
package com.study.task; import com.baomidou.lock.LockInfo; import com.baomidou.lock.LockTemplate; import com.baomidou.lock.executor.RedissonLockExecutor; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.annotation.Resource; import java.util.UUID; @Component @Slf4j @EnableScheduling public class ProductTask { @Resource private LockTemplate lockTemplate; @Scheduled(cron = "0/1 0/5 * * * ?") public void productTackStart() { //get lock LockInfo lockInfo = null; try { String key = UUID.randomUUID() + ""; log.info("开始加锁------------key:{}", key); lockInfo = lockTemplate.lock(key, 5000L, 100L, RedissonLockExecutor.class); //对象转json,可以在使用任意一种方法,google/mybatis/alibaba都有封装 ObjectMapper Obj = new ObjectMapper(); String jsonStr = Obj.writeValueAsString(lockInfo); log.info("lockInfo:{}", jsonStr); log.info("定时任务开始-------"); //业务代码入口 } catch (Exception e) { log.error("异常:", e); } finally { //解锁 if (null == lockInfo) { log.info("--------lockInfo is null"); return; } boolean releaseLock = lockTemplate.releaseLock(lockInfo); log.info("-----releaseLock:{}", releaseLock); } } }
简化版
//get lock LockInfo lockInfo = null; try { lockInfo = this.lockTemplate.lock(BRAND_KEY_LOCK, 5000L, 0L, RedissonLockExecutor.class);#BRAND_KEY_LOCK定义为唯一的key //业务 Integer updateBrand = this.updateBrand(brandPageReq, now, mchBrand); log.info("updateBrand:{}", updateBrand); } catch (Exception e) { log.error("修改品牌:", e); } finally { this.lockTemplate.releaseLock(lockInfo); }