A Powerful Distributed Lock Framework: Introducing Lock4j

This guide introduces Lock4j, a versatile distributed‑lock component for Java that works with Spring AOP and supports RedisTemplate, Redisson, and Zookeeper, and walks through its features, configuration, annotation attributes, basic usage, and advanced customization options.

IT Niuke
IT Niuke
IT Niuke
A Powerful Distributed Lock Framework: Introducing Lock4j

Overview

Lock4j provides distributed locking via Spring AOP (declarative) and programmatic APIs. It supports three back‑ends— RedisTemplate, Redisson, and Zookeeper —which can be mixed or extended.

Dependencies

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

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

Redis Configuration Example

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

Lock Annotation Definition

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

@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 repeatedly yields:

{
    "success": true,
    "message": "操作成功!",
    "code": 200,
    "result": "123",
    "timestamp": 1678866083211
}

If the lock cannot be obtained, Lock4j throws

com.baomidou.lock.exception.LockFailureException: request failed,please retry it.

. A global exception handler can translate this to:

{
    "success": false,
    "message": "操作失败,request failed,please retry it.",
    "code": 500,
    "result": null,
    "timestamp": 1678866034929
}

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

Specify the executor on the annotation:

@Lock4j(executor = CustomRedissonLockExecutor.class)

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 logic
    }
}

The default 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
    }
}

Reference

Gitee repository:

https://gitee.com/baomidou/lock4j
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.

JavaRedisZookeeperSpring BootDistributed LockRedissonLock4j
IT Niuke
Written by

IT Niuke

Focused on IT technology sharing, original and innovative content. IT Niuke, we grow together.

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.