加redis锁

 

package com.tj.qc.service.config.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 锁
 *
 * @author zyl
 * @date 2021/11/24
 */
@Component
public class RedisLock {
//    @Autowired
//    private RedisTemplate<String, String> redisTemplate;
    @Autowired private com.tj.common.redis.simple.RedisSimpleClient redisClient;

    public void lock(String key, Runnable runnable){
        try{
            if(lock(key)) {
                runnable.run();
            }
        }finally {
            unlock(key);
        }
    }

    private boolean lock(String key){
        if(!redisClient.exists("RLock:"+key)) {
            redisClient.setStr("RLock:"+key, "1");
            return true;
        }
        return false;
    }

    private void unlock(String key){
        redisClient.del("RLock:"+key);
    }
}

 

调用

@Autowired
    private RedisLock redisLock;
    /**
     * 创建时间格式排查
     * */
    @RequestMapping(value = "/test", method = RequestMethod.GET)
    @ResponseBody
    public String checkCreateTime(){
        redisLock.lock("lockWW", ()-> {
            System.err.println();
        });
        return nn;
    }

 

上一篇:sql server lock


下一篇:每日面试训练题6