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.
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: 6000Lock 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/lock4jSigned-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
IT Niuke
Focused on IT technology sharing, original and innovative content. IT Niuke, we grow together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
