SpringBoot Redission分布式锁

Redission 文档

1.Redis连接配置

application.properties 配置文件中增加配置。

#1、单机模式
redisson.address=redis://10.7.5.16:6379
#redisson.password=

2. Redission属性配置

RedissonProperties.java 属性配置文件


package com.jeiker.redisson.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

/**
 * Description: 配置属性
 * User: jeikerxiao
 * Date: 2020-07-27 11:36
 */
@Data
@ConfigurationProperties(prefix = "redisson")
public class RedissonProperties {

    private int timeout = 3000;

    private String address;

    private String password;

    private int connectionPoolSize = 64;

    private int connectionMinimumIdleSize=10;

    private int slaveConnectionPoolSize = 250;

    private int masterConnectionPoolSize = 250;

    private String[] sentinelAddresses;

    private String masterName;
}

3. Redission自动配置类

Redission 自动装配类

RedissonAutoConfiguration.java

package com.jeiker.redisson.config;

import com.jeiker.redisson.service.DistributedLocker;
import com.jeiker.redisson.service.RedissonDistributedLocker;
import com.jeiker.redisson.util.RedissLockUtil;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SentinelServersConfig;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Description: 自动配置类
 * User: jeikerxiao
 * Date: 2020-07-27 11:38
 */
@Configuration
@ConditionalOnClass(Config.class)
@EnableConfigurationProperties(RedissonProperties.class)
public class RedissonAutoConfiguration {

    @Autowired
    private RedissonProperties redssionProperties;

    /**
     * 单机模式自动装配
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="redisson.address")
    RedissonClient redissonSingle() {
        Config config = new Config();
        SingleServerConfig serverConfig = config.useSingleServer()
                .setAddress(redssionProperties.getAddress())
                .setTimeout(redssionProperties.getTimeout())
                .setConnectionPoolSize(redssionProperties.getConnectionPoolSize())
                .setConnectionMinimumIdleSize(redssionProperties.getConnectionMinimumIdleSize());

        if(StringUtils.isNotBlank(redssionProperties.getPassword())) {
            serverConfig.setPassword(redssionProperties.getPassword());
        }

        return Redisson.create(config);
    }

    /**
     * 哨兵模式自动装配
     * @return
     */
    @Bean
    @ConditionalOnProperty(name="redisson.master-name")
    RedissonClient redissonSentinel() {
        Config config = new Config();
        SentinelServersConfig serverConfig = config.useSentinelServers().addSentinelAddress(redssionProperties.getSentinelAddresses())
                .setMasterName(redssionProperties.getMasterName())
                .setTimeout(redssionProperties.getTimeout())
                .setMasterConnectionPoolSize(redssionProperties.getMasterConnectionPoolSize())
                .setSlaveConnectionPoolSize(redssionProperties.getSlaveConnectionPoolSize());

        if(StringUtils.isNotBlank(redssionProperties.getPassword())) {
            serverConfig.setPassword(redssionProperties.getPassword());
        }
        return Redisson.create(config);
    }


    /**
     * 装配locker类,并将实例注入到RedissLockUtil中
     * @return
     */
    @Bean
    DistributedLocker distributedLocker(RedissonClient redissonSingle) {
        RedissonDistributedLocker locker = new RedissonDistributedLocker();
        locker.setRedissonClient(redissonSingle);
        RedissLockUtil.setLocker(locker);
        return locker;
    }

}

4.分布式锁接口

DistributedLocker.java

package com.jeiker.redisson.service;

import java.util.concurrent.TimeUnit;

/**
 * Description: 分布式锁接口
 * User: jeikerxiao
 * Date: 2020-07-27 13:52
 */
public interface DistributedLocker {

    /**
     * 加锁(默认30秒)
     */
    void lock(String lockKey);

    /**
     * 加锁
     */
    void unlock(String lockKey);

    /**
     * 加锁
     * @param timeout 单位:秒
     */
    void lock(String lockKey, int timeout);

    /**
     * 加锁
     * @param unit 时间单位
     * @param timeout 时间值
     */
    void lock(String lockKey, TimeUnit unit , int timeout);

}


5.分布式锁实现

RedissonDistributedLocker.java

package com.jeiker.redisson.service;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * Description: 分布式锁实现
 * User: jeikerxiao
 * Date: 2020-07-27 13:52
 */
public class RedissonDistributedLocker implements DistributedLocker {

    private RedissonClient redissonClient;

    @Override
    public void lock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock();
    }

    @Override
    public void unlock(String lockKey) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.unlock();
    }

    @Override
    public void lock(String lockKey, int leaseTime) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(leaseTime, TimeUnit.SECONDS);
    }

    @Override
    public void lock(String lockKey, TimeUnit unit ,int timeout) {
        RLock lock = redissonClient.getLock(lockKey);
        lock.lock(timeout, unit);
    }

    public void setRedissonClient(RedissonClient redissonClient) {
        this.redissonClient = redissonClient;
    }
}


6.分布式锁工具类

package com.jeiker.redisson.util;

import com.jeiker.redisson.service.DistributedLocker;

import java.util.concurrent.TimeUnit;

/**
 * Description: redis分布式锁工具类
 * User: jeikerxiao
 * Date: 2020-07-27 13:53
 */
public class RedissLockUtil {

    private static DistributedLocker redissLock;

    public static void setLocker(DistributedLocker locker) {
        redissLock = locker;
    }

    /**
     * 加锁
     */
    public static void lock(String lockKey) {
        redissLock.lock(lockKey);
    }

    /**
     * 解锁
     */
    public static void unlock(String lockKey) {
        redissLock.unlock(lockKey);
    }

    /**
     * 带超时的锁
     *
     * @param lockKey
     * @param timeout 超时时间   单位:秒
     */
    public static void lock(String lockKey, int timeout) {
        redissLock.lock(lockKey, timeout);
    }

    /**
     * 带超时的锁
     *
     * @param lockKey
     * @param unit    时间单位
     * @param timeout 超时时间
     */
    public static void lock(String lockKey, TimeUnit unit, int timeout) {
        redissLock.lock(lockKey, unit, timeout);
    }

}

7.单元测试

RedissLockUtilTest.java

package com.jeiker.redisson.util;

import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.concurrent.TimeUnit;

import static org.junit.jupiter.api.Assertions.*;

/**
 * Description: spring-boot-redisson
 * User: jeikerxiao
 * Date: 2020-07-27 14:11
 */
@SpringBootTest
class RedissLockUtilTest {

    @Test
    void lock() throws InterruptedException {
        // 默认30秒
        RedissLockUtil.lock("test:LockKey1");
    }

    @Test
    void unlock() throws InterruptedException {
        // 默认30秒
        RedissLockUtil.lock("test:LockKey1");
        Thread.sleep(10*1000);
        RedissLockUtil.unlock("test:LockKey1");
    }

    @Test
    void testLock() {
        // timeout 10秒
        RedissLockUtil.lock("test:LockKey2", 20);
    }

    @Test
    void testLock1() {
        RedissLockUtil.lock("test:LockKey3", TimeUnit.DAYS, 1);
    }
}

你可能感兴趣的:(Spring,Boot)