首页 > 技术文章 > 多节点部署定时任务时的锁机制(redis)

sunAnqing 2022-04-13 11:05 原文

一、方法

package redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class DistributeLock {
    @Resource
    private RedisTemplate<String, String> redisTemplate;
    protected static final Logger logger = LoggerFactory.getLogger(DistributeLock.class);

    public boolean getLock(String lockId, long millisecond) {
        Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, "lock", millisecond, TimeUnit.MILLISECONDS);
        logger.info("当前redis锁 =" + lockId + "====" + success);
        return success != null && success;
    }
}

二、调用

package com.ndsoft.single.redis;

import org.springframework.scheduling.annotation.Scheduled;

import javax.annotation.Resource;

public class TestSync {
    @Resource
    private DistributeLock distributeLock;

    @Scheduled(cron = " 0/5 * * * * ?")
    public void testSync() {
        boolean testLock = distributeLock.getLock("testLock", 10000);
        if (testLock) {
            // 业务代码
        }
    }
}

 

推荐阅读