Lock4j Distributed Lock Component: Features, Configuration, and Usage Guide

Lock4j is a Java distributed lock library supporting Spring AOP, RedisTemplate, Redisson, and Zookeeper, offering simple usage, configurable properties, annotation-driven locking, custom executors, key generators, and failure strategies, with detailed setup, code examples, and advanced customization instructions.

Architecture Digest
Architecture Digest
Architecture Digest
Lock4j Distributed Lock Component: Features, Configuration, and Usage Guide

Lock4j is a distributed lock component for Java, supporting Spring AOP‑based declarative and programmatic locking, and can work with RedisTemplate, Redisson, and Zookeeper.

Features

Simple to use, powerful, highly extensible.

Supports Redisson, RedisTemplate, Zookeeper, and can be mixed.

Preparation

Add one of the following Maven dependencies according to the desired implementation:

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>lock4j-redis-template-spring-boot-starter</artifactId>
  <version>2.2.4</version>
</dependency>

<dependency>
  <groupId>com.baomidou</groupId>
  <artifactId>lock4j-redisson-spring-boot-starter</artifactId>
  <version>2.2.4</version>
</dependency>

Configure Redis in application.yml (or application.properties) as follows:

spring:
  redis:
    database: 0
    host: 127.0.0.1
    port: 6379
    password:
    jedis:
      pool:
        max-active: 200
        max-wait: -1
        max-idle: 10
        min-idle: 0
    timeout: 6000

Annotation Attributes

package com.baomidou.lock.annotation;

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

Simple Usage

Example controller:

@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);
    }
}

Calling http://localhost:8080/mock/lockMethod?key=123 returns a successful lock response; if the lock cannot be acquired, a LockFailureException is thrown and can be handled globally.

Advanced Usage

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

Custom key builder:

@Component
public class CustomKeyBuilder extends DefaultLockKeyBuilder {
    public CustomKeyBuilder(BeanFactory beanFactory) {
        super(beanFactory);
    }
}

Custom lock‑failure strategy:

@Component
public class GrabLockFailureStrategy implements LockFailureStrategy {
    @Override
    public void onLockFailure(String key, Method method, Object[] arguments) {
        // custom handling
    }
}

Manual lock and release:

@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();
        } finally {
            lockTemplate.releaseLock(lock);
        }
    }
    private void doBusiness() {
        // TODO business logic
    }
}

This guide provides a complete overview of Lock4j, from basic concepts and configuration to advanced customization, enabling developers to integrate distributed locking into Spring Boot applications efficiently.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaBackend DevelopmentredisSpring Bootdistributed-lock
Architecture Digest
Written by

Architecture Digest

Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.

0 followers
Reader feedback

How this landed with the community

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.