函数式接口:有且只有一个方法抽象方法的接口,可以有其他的方法.
格式;intface in{
//有且只有一个抽象方法
//可以有其它默认方法,静态方法,私有方法…
}
@FunctionalInterface
interface ai {
public void show();
}
自己定义函数式接口:
demo1:
demo2:定义无参数无返回接口方法
定义一个函数式接口
@FunctionalInterface
public interface LockExecutor {
/**
* 执行任务函数式接口
*
*/
void execute();
}
定义一个通用执行方法:
/**
* 加锁执行方法
*
* @param lockKey 锁
* @param successExecutor 获取锁成功执行
* @param failExecutor 获取锁失败执行
*/
public static void run(String lockKey, LockExecutor successExecutor, LockExecutor failExecutor) {
String requestId = UUID.randomUUID().toString();
try {
if (tryGetDistributedLock(lockKey, requestId, LOCK_EXPIRE_TIME)) {
successExecutor.execute();
} else if (Objects.nonNull(failExecutor)) {
failExecutor.execute();
}
} catch (Exception e) {
log.error("调用任务失败:", e);
} finally {
releaseDistributedLock(lockKey, requestId);
}
}
调用执行方法:
LockRunner.run(CommonConstants.LEADS_CREATE_LOCK_PREFIX, mobiles, () -> doCreate(leadsCreateReqDTO), () -> {
throw new ServiceException("有相同的线索正在新增");
});
demo3:定义一个无参数有返回的接口(使用1.8自带的函数式接口)
@FunctionalInterface
public interface Supplier<T> {
/**
* Gets a result.
*
* @return a result
*/
T get();
}
定义通用方法:
/**
* 重试方法,
*
* @param successExecutor 成功后执行
* @param failExecutor 失败后执行
* @author
* @since 2021/3/8
*/
public static <T> T run(Integer errcode, Supplier<T> successExecutor, Supplier<T> failExecutor) {
if (Objects.equals(errcode, WecomErrEnums.ACCESS_TOKEN_EXPIRED.getValue())) {
WeComHelper.updateAccessToken(RedisConstants.ACCESS_TOKEN_ENTERPRISE);
WeComHelper.updateAccessToken(RedisConstants.ACCESS_TOKEN_ONE);
T result = successExecutor.get();
return result;
} else {
T result = failExecutor.get();
return result;
}
}
调用执行方法:
/**
* 根据code获取用户信息
*/
public static UserInfoByCodeRespDTO getUserInfoByCode(String code) {
UserInfoByCodeRespDTO userInfoByCodeResp = getUserInfoByCodeWecom(code);
if (!Objects.equals(userInfoByCodeResp.getErrcode(), WecomErrEnums.SUCCESS.getValue())) {
UserInfoByCodeRespDTO tryAgainResult = TryaginRunner.run(userInfoByCodeResp.getErrcode(), () -> getUserInfoByCodeWecom(code),
() -> {
throw new ServiceException(userInfoByCodeResp.getErrcode(), userInfoByCodeResp.getErrmsg());
});
return tryAgainResult;
}
return userInfoByCodeResp;
}
private static UserInfoByCodeRespDTO getUserInfoByCodeWecom(String code) {
try {
// 使用应用的token
String accessToken = getAccessTokenByRedis(RedisConstants.ACCESS_TOKEN_ONE);
String url = String.format(SwjConfig.get("userinfo_code_url"), accessToken, code);
log.info("参数:" + JsonHelper.toJsonString(code));
String responseStr = WebClientHelper.get(url);
log.info("根据code获取访问用户身份返回" + responseStr);
UserInfoByCodeRespDTO userInfoByCodeResp = JsonHelper.parseBean(responseStr, UserInfoByCodeRespDTO.class);
return userInfoByCodeResp;
} catch (Exception e) {
log.error("根据code获取访问用户身份出错", e);
throw new ServiceException("根据code获取访问用户身份出错");
}
}
除此外,jdk还自带了很多函数式接口,各种入参返回类型:函数式接口有