stringboot + jedis + redis实现分布式锁

pom.xml配置


    redis.clients
    jedis
    2.9.0


    org.springframework.boot
    spring-boot-starter-data-redis

application.yml配置

redis:
      host: 20.74.51.205
      password: 123456
      port: 6379
      pool:
        max-idle: 100
        min-idle: 1
        max-active: 1000
        max-wait: -1
      timeout: 0

 config配置

package com.lock.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author 作者 小书生008
 * @create 2018-09-20 15:55
 **/
@Slf4j
@Configuration
@EnableAutoConfiguration
public class RedisConfig {
    @Value("${spring.redis.host}")
    private String hostName;
    @Value("${spring.redis.port}")
    private int port;
    @Value("${spring.redis.password}")
    private String password;
    @Value("${spring.redis.timeout}")
    private int timeout;

    @Bean
    public JedisPoolConfig getRedisConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }


    @Bean
    public JedisPool getJedisPool(){
        JedisPoolConfig config = getRedisConfig();
        JedisPool pool = new JedisPool(config,hostName,port,timeout,password);
        log.info("init JedisPool...");
        return  pool;
    }

    public String getHostName() {
        return hostName;
    }

    public void setHostName(String hostName) {
        this.hostName = hostName;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public int getTimeout() {
        return timeout;
    }

    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
}

 加锁和解锁

package com.lock.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Collections;
import java.util.UUID;

/**
 * @author 作者 小书生008
 * @create 2018-09-20 16:06
 **/
@Slf4j
@Component
public class RedisLock {

    private  final String LOCK_SUCCESS = "OK";
    private  final String SET_IF_NOT_EXIST = "NX";
    private  final String SET_WITH_EXPIRE_TIME = "PX";

    @Autowired
    private JedisPool jedisPool;

    // 同时在redis上创建相同的一个key 相同key 名称
    private String redislockKey = "redis_lock";

    @SuppressWarnings("deprecation")
    public Jedis getResource(){
        return jedisPool.getResource();
    }

    public  String getRedisLock(Long acquireTimeout, Long timeOut){
        Jedis jedis = null;
        try {
            //1.建立连接
            jedis = getResource();
            // 2.定义 redis 对应key 的value值( uuid) 作用 释放锁 随机生成value
            String uuid = UUID.randomUUID().toString();
            //3.定义在获取锁后的超时时间
            int expireLock = (int)(timeOut / 1000);
            //4.定义在获取锁之前的超时时间,用于在超时时间内循环重试获取锁
            long endTime = System.currentTimeMillis() + acquireTimeout;
            while (System.currentTimeMillis() < endTime) {
                String result = jedis.set(redislockKey, uuid, SET_IF_NOT_EXIST, SET_WITH_EXPIRE_TIME, expireLock);
                if (LOCK_SUCCESS.equals(result)) {
                    log.info("获取锁..." + Thread.currentThread().getName() + ",identifierValue:" + uuid);
                    return uuid;
                }
                log.info("未获取锁..." + Thread.currentThread().getName() + ",identifierValue:" + uuid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (jedis != null){
                jedis.close();
            }
        }
        return null;
    }


    public void unRedisLock(String uuid){
        if (null == uuid){
            return;
        }
        final Long RELEASE_SUCCESS = 1L;
        Jedis jedis = null;
        try {
            //建立连接
            jedis = getResource();
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            Object eval = jedis.eval(script, Collections.singletonList(redislockKey), Collections.singletonList(uuid));
            if (RELEASE_SUCCESS.equals(eval)){
                log.info("释放锁..." + Thread.currentThread().getName() + ",identifierValue:" + uuid);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != jedis){
                jedis.close();
            }
        }
    }
}

 

直接复制就可以使用,亲测,(小弟初来乍到,如有问题,还请多多指点)

你可能感兴趣的:(分布式锁)