加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;
    }

 

posted @ 2021-12-30 11:24  君子笑而不语  阅读(42)  评论(0编辑  收藏  举报