封装工具类UtilProcess
UtilProcess主要是使用函数式变成,提高代码的可读性、扩展性,用于处理方法内部异常捕获和接入第三方异常日志记录平台,同时还兼容了分布式锁,可根据业务以及开发需要,灵活调用不同的方法。话不多说,上代码
引入jar包
<dependency>
<groupId>org.redisson</groupId>
<artifactId>redisson</artifactId>
<version>3.17.4</version> <!-- 按照最新版本替换 -->
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.22</version> <!-- 按照最新版本替换 -->
<scope>provided</scope>
</dependency>
UtilProcess类
@Slf4j
public class UtilProcess {
@Autowired
private static RedissonClient redissonClient;
/**
* 主处理方法,支持执行逻辑并返回结果,带分布式锁。
*
* @param methodName 方法名(用于日志记录)
* @param cls 类名
* @param func 执行逻辑的函数接口
* @param lockName 分布式锁名称
* @param <T> 返回结果的类型
* @return 执行结果
*/
public static <T> T mainProcess(String methodName, String cls, Func<T> func, String lockName) {
RLock lock = redissonClient.getLock(lockName);
return executeWithLock(methodName, cls, func, lock);
}
/**
* 主处理方法,支持执行逻辑并返回结果,不带分布式锁。
*
* @param methodName 方法名(用于日志记录)
* @param cls 类名
* @param func 执行逻辑的函数接口
* @param <T> 返回结果的类型
* @return 执行结果
*/
public static <T> T mainProcess(String methodName, String cls, Func<T> func) {
try {
return func.execute();
}catch (Exception e) {
logError(cls, methodName, e);
throw new RuntimeException("执行方法异常", e);
}
}
/**
* 加分布式锁处理
* @param methodName
* @param cls
* @param func
* @param lock
* @return
* @param <T>
*/
private static <T> T executeWithLock(String methodName, String cls, Func<T> func, RLock lock) {
try {
boolean lockAcquired = lock.tryLock(10, 30, TimeUnit.SECONDS);
if (lockAcquired) {
try {
return func.execute();
} finally {
lock.unlock();
}
} else {
throw new RuntimeException("加锁失败:" + lock.getName());
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
logError(methodName, cls , e);
throw new RuntimeException("等待锁时被中断", e);
} catch (Exception e) {
logError(methodName, cls , e);
throw new RuntimeException("执行方法异常", e);
}
}
/**
* 接入日志平台
* @param methodName
* @param cls
* @param e
*/
private static void logError(String methodName, String cls, Exception e) {
//接入日志平台
log.error("类 " + cls + " 中的方法 " + methodName + " 执行过程中发生异常: " + e.getMessage(), e);
}
@FunctionalInterface
interface Func<T> {
T execute();
}
}
测试类
public class TestUtilProcess {
public static void main(String[] args) {
TestUtilProcess test = new TestUtilProcess();
test.testA();
test.getUserInfo("1001");
}
public void testA() {
UtilProcess.mainProcess("testA", "TestUtilProcess", () -> {
int i = 0;
int result = i / 0;
System.out.println(result);
return null;
});
}
public User getUserInfo(String userId) {
return UtilProcess.mainProcess("getUserInfo", "TestUtilProcess", () -> {
List<User> users =new ArrayList<>();
users.add(new User("1001", "李四", 12));
users.add(new User("1002", "张三", 12));
User res = users.stream().filter(e -> e.getUserId().equals(userId)).findFirst().orElse(null);
return res;
}, "");
}
}