Backend Development 6 min read

Guide to Using Lock4j Distributed Lock Component in Spring Boot

This article introduces the Lock4j distributed lock library, explains its features, shows how to add Maven dependencies, configure Redis, use the @Lock4j annotation for simple and advanced locking scenarios, and provides custom executor, key builder, and failure‑strategy examples for Spring Boot applications.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Guide to Using Lock4j Distributed Lock Component in Spring Boot

Introduction Lock4j is a distributed lock component that supports multiple back‑ends such as RedisTemplate , Redisson and Zookeeper , offering both declarative (Spring AOP) and programmatic lock usage.

Features - Simple to use, powerful, and highly extensible. - Supports mixing redisson , redisTemplate , and zookeeper back‑ends.

Preparation before Use

Add Dependencies

com.baomidou
lock4j-redis-template-spring-boot-starter
2.2.4
com.baomidou
lock4j-redisson-spring-boot-starter
2.2.4

Add Redis Configuration

spring:
  redis:
    database: 0
    # Redis server address
    host: 127.0.0.1
    # Redis server port
    port: 6379
    # Password (empty by default)
    password:
    jedis:
      pool:
        max-active: 200
        max-wait: -1
        max-idle: 10
        min-idle: 0
        timeout: 6000

Annotation Attribute Description

package com.baomidou.lock.annotation;

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface Lock4j {
    String name() default "";
    Class
executor() default LockExecutor.class;
    String[] keys() default {""};
    long expire() default -1L;
    long acquireTimeout() default -1L;
    boolean autoRelease() default true;
}

Simple Usage

@RestController
@RequestMapping("/mock")
public class MockController {
    @GetMapping("/lockMethod")
    @Lock4j(keys = {"#key"}, acquireTimeout = 1000, expire = 10000)
    public Result lockMethod(@RequestParam String key) {
        ThreadUtil.sleep(5000);
        return Result.OK(key);
    }
}

Access http://localhost:8080/mock/lockMethod?key=123 repeatedly. When the lock is acquired, the response is: {"success":true,"message":"操作成功!","code":200,"result":"123","timestamp":1678866083211} . If the lock cannot be obtained, Lock4j throws com.baomidou.lock.exception.LockFailureException , which can be handled globally to return an error JSON.

Advanced Usage

Custom Executor

/**
 * Custom distributed lock executor
 */
@Component
public class CustomRedissonLockExecutor extends AbstractLockExecutor {
    @Override
    public Object acquire(String lockKey, String lockValue, long expire, long acquireTimeout) {
        return null;
    }

    @Override
    public boolean releaseLock(String key, String value, Object lockInstance) {
        return false;
    }
}

Specify the executor on the annotation: @Lock4j(executor = CustomRedissonLockExecutor.class) .

Custom Key Builder

/**
 * Custom lock key generator
 */
@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {
    public CustomKeyBuilder(BeanFactory beanFactory) {
        super(beanFactory);
    }
}

Custom Lock Failure Strategy

/**
 * Custom strategy when lock acquisition fails
 */
@Component
public class GrabLockFailureStrategy implements LockFailureStrategy {
    @Override
    public void onLockFailure(String key, Method method, Object[] arguments) {
        // custom handling logic
    }
}

The default failure strategy is com.baomidou.lock.DefaultLockFailureStrategy .

Manual Lock and Unlock

@Service
public class LockServiceImpl implements LockService {
    @Autowired
    private LockTemplate lockTemplate;

    @Override
    public void lock(String resourceKey) {
        LockInfo lock = lockTemplate.lock(resourceKey, 10000L, 2000L, CustomRedissonLockExecutor.class);
        if (lock == null) {
            throw new FrameworkException("业务处理中,请稍后再试...");
        }
        try {
            doBusiness();
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lockTemplate.releaseLock(lock);
        }
    }

    private void doBusiness() {
        // TODO business logic
    }
}

The article concludes with a source reference and a promotional note for a backend‑focused technical community.

javaRedisZookeeperSpring BootDistributed LockRedissonLock4j
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.