Redis教程

加redis锁

本文主要是介绍加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;
    }

 

这篇关于加redis锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!