SpringBoot中四種AOP實(shí)戰(zhàn)應(yīng)用場(chǎng)景及代碼實(shí)現(xiàn)
引言
面向切面編程(AOP)是Spring框架的核心功能之一,它通過(guò)預(yù)編譯和運(yùn)行期動(dòng)態(tài)代理實(shí)現(xiàn)程序功能的統(tǒng)一維護(hù)。在SpringBoot應(yīng)用中,AOP能夠幫助我們優(yōu)雅地解決橫切關(guān)注點(diǎn)問(wèn)題,如日志記錄、權(quán)限控制、性能監(jiān)控等,這些功能往往貫穿整個(gè)應(yīng)用但又不屬于業(yè)務(wù)核心邏輯。
本文將介紹SpringBoot中4種AOP實(shí)戰(zhàn)應(yīng)用場(chǎng)景,包括代碼實(shí)現(xiàn)、核心原理及實(shí)踐。
場(chǎng)景一:日志記錄與性能監(jiān)控
業(yè)務(wù)需求
在企業(yè)級(jí)應(yīng)用中,我們通常需要:
- 記錄API請(qǐng)求的調(diào)用情況
- 監(jiān)控方法執(zhí)行時(shí)間,發(fā)現(xiàn)性能瓶頸
- 追蹤方法調(diào)用的入?yún)⒑头祷亟Y(jié)果
實(shí)現(xiàn)方案
@Aspect
@Component
@Slf4j
public class LoggingAspect {
/**
* 定義切點(diǎn):所有controller包下的所有方法
*/
@Pointcut("execution(* com.example.demo.controller.*.*(..))")
public void controllerMethods() {}
/**
* 環(huán)繞通知:記錄請(qǐng)求日志和執(zhí)行時(shí)間
*/
@Around("controllerMethods()")
public Object logAroundControllers(ProceedingJoinPoint joinPoint) throws Throwable {
// 獲取方法簽名
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getName();
String className = signature.getDeclaringTypeName();
// 記錄請(qǐng)求參數(shù)
String params = Arrays.toString(joinPoint.getArgs());
log.info("Request to {}.{} with params: {}", className, methodName, params);
// 記錄開(kāi)始時(shí)間
long startTime = System.currentTimeMillis();
// 執(zhí)行目標(biāo)方法
Object result;
try {
result = joinPoint.proceed();
// 計(jì)算執(zhí)行時(shí)間
long executionTime = System.currentTimeMillis() - startTime;
// 記錄返回結(jié)果和執(zhí)行時(shí)間
log.info("Response from {}.{} ({}ms): {}",
className, methodName, executionTime, result);
// 記錄慢方法
if (executionTime > 1000) {
log.warn("Slow execution detected! {}.{} took {}ms",
className, methodName, executionTime);
}
return result;
} catch (Exception e) {
// 記錄異常信息
log.error("Exception in {}.{}: {}", className, methodName, e.getMessage(), e);
throw e;
}
}
/**
* 定義服務(wù)層方法切點(diǎn)
*/
@Pointcut("execution(* com.example.demo.service.*.*(..))")
public void serviceMethods() {}
/**
* 記錄服務(wù)層方法的關(guān)鍵調(diào)用
*/
@Before("serviceMethods() && @annotation(logMethod)")
public void logServiceMethod(JoinPoint joinPoint, LogMethod logMethod) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getName();
// 獲取參數(shù)名
String[] paramNames = signature.getParameterNames();
Object[] args = joinPoint.getArgs();
StringBuilder logMessage = new StringBuilder();
logMessage.append("Executing ").append(methodName).append(" with params: {");
for (int i = 0; i < paramNames.length; i++) {
logMessage.append(paramNames[i]).append("=").append(args[i]);
if (i < paramNames.length - 1) {
logMessage.append(", ");
}
}
logMessage.append("}");
// 根據(jù)注解設(shè)置的級(jí)別記錄日志
switch (logMethod.level()) {
case DEBUG:
log.debug(logMessage.toString());
break;
case INFO:
log.info(logMessage.toString());
break;
case WARN:
log.warn(logMessage.toString());
break;
case ERROR:
log.error(logMessage.toString());
break;
}
}
}
/**
* 自定義日志注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface LogMethod {
LogLevel level() default LogLevel.INFO;
public enum LogLevel {
DEBUG, INFO, WARN, ERROR
}
}
使用示例
@Service
public class UserService {
@LogMethod(level = LogMethod.LogLevel.INFO)
public User findById(Long id) {
// 業(yè)務(wù)邏輯
return userRepository.findById(id).orElse(null);
}
@LogMethod(level = LogMethod.LogLevel.WARN)
public void updateUserStatus(Long userId, String status) {
// 更新用戶狀態(tài)
}
}
擴(kuò)展:MDC實(shí)現(xiàn)請(qǐng)求跟蹤
@Component
public class RequestIdFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
try {
// 為每個(gè)請(qǐng)求生成唯一ID
String requestId = UUID.randomUUID().toString().replace("-", "");
MDC.put("requestId", requestId);
if (request instanceof HttpServletRequest) {
HttpServletRequest httpRequest = (HttpServletRequest) request;
// 記錄用戶信息
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.isAuthenticated()) {
MDC.put("userId", auth.getName());
}
MDC.put("remoteAddr", httpRequest.getRemoteAddr());
}
chain.doFilter(request, response);
} finally {
// 請(qǐng)求完成后清理MDC
MDC.clear();
}
}
}
場(chǎng)景二:權(quán)限控制與安全增強(qiáng)
業(yè)務(wù)需求
在企業(yè)應(yīng)用中,權(quán)限控制是一個(gè)常見(jiàn)的需求:
- 基于角色的接口訪問(wèn)控制
- 細(xì)粒度的操作權(quán)限控制
- 對(duì)敏感數(shù)據(jù)訪問(wèn)的記錄
實(shí)現(xiàn)方案
首先,創(chuàng)建自定義注解:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequiresPermission {
/**
* 所需權(quán)限編碼數(shù)組,滿足其中任一即可
*/
String[] value() default {};
/**
* 權(quán)限邏輯類型:AND(同時(shí)具有所有權(quán)限), OR(滿足任一權(quán)限即可)
*/
LogicalType logical() default LogicalType.OR;
public enum LogicalType {
AND, OR
}
}
實(shí)現(xiàn)權(quán)限切面:
@Aspect
@Component
@Slf4j
public class PermissionAspect {
@Autowired
private UserService userService;
/**
* 定義切點(diǎn):所有帶有@RequiresPermission注解的方法
*/
@Pointcut("@annotation(com.example.demo.annotation.RequiresPermission)")
public void permissionCheck() {}
/**
* 權(quán)限驗(yàn)證前置通知
*/
@Before("permissionCheck() && @annotation(requiresPermission)")
public void checkPermission(JoinPoint joinPoint, RequiresPermission requiresPermission) {
// 獲取當(dāng)前用戶
User currentUser = getCurrentUser();
if (currentUser == null) {
throw new UnauthorizedException("用戶未登錄或會(huì)話已過(guò)期");
}
// 獲取用戶權(quán)限列表
Set<String> userPermissions = userService.getUserPermissions(currentUser.getId());
// 獲取注解中要求的權(quán)限
String[] requiredPermissions = requiresPermission.value();
RequiresPermission.LogicalType logicalType = requiresPermission.logical();
// 權(quán)限校驗(yàn)
boolean hasPermission = false;
if (logicalType == RequiresPermission.LogicalType.OR) {
// 滿足任一權(quán)限即可
for (String permission : requiredPermissions) {
if (userPermissions.contains(permission)) {
hasPermission = true;
break;
}
}
} else {
// 必須同時(shí)滿足所有權(quán)限
hasPermission = true;
for (String permission : requiredPermissions) {
if (!userPermissions.contains(permission)) {
hasPermission = false;
break;
}
}
}
if (!hasPermission) {
log.warn("用戶 {} 嘗試訪問(wèn)未授權(quán)資源: {}.{}",
currentUser.getUsername(),
joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName());
throw new ForbiddenException("權(quán)限不足,無(wú)法執(zhí)行該操作");
}
// 記錄敏感操作
log.info("用戶 {} 執(zhí)行了需授權(quán)操作: {}.{}",
currentUser.getUsername(),
joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName());
}
/**
* 定義切點(diǎn):帶有@RequiresRole注解的方法
*/
@Pointcut("@annotation(com.example.demo.annotation.RequiresRole)")
public void roleCheck() {}
/**
* 角色檢查前置通知
*/
@Before("roleCheck() && @annotation(requiresRole)")
public void checkRole(JoinPoint joinPoint, RequiresRole requiresRole) {
// 獲取當(dāng)前用戶
User currentUser = getCurrentUser();
if (currentUser == null) {
throw new UnauthorizedException("用戶未登錄或會(huì)話已過(guò)期");
}
// 獲取用戶角色
Set<String> userRoles = userService.getUserRoles(currentUser.getId());
// 獲取注解中要求的角色
String[] requiredRoles = requiresRole.value();
// 角色校驗(yàn)
boolean hasRole = false;
for (String role : requiredRoles) {
if (userRoles.contains(role)) {
hasRole = true;
break;
}
}
if (!hasRole) {
log.warn("用戶 {} 嘗試訪問(wèn)未授權(quán)角色資源: {}.{}",
currentUser.getUsername(),
joinPoint.getSignature().getDeclaringTypeName(),
joinPoint.getSignature().getName());
throw new ForbiddenException("角色不足,無(wú)法執(zhí)行該操作");
}
}
/**
* 數(shù)據(jù)權(quán)限過(guò)濾切點(diǎn):針對(duì)查詢方法
*/
@Pointcut("execution(* com.example.demo.service.*.find*(..))")
public void dataPermissionFilter() {}
/**
* 數(shù)據(jù)權(quán)限過(guò)濾通知
*/
@Around("dataPermissionFilter()")
public Object filterDataByPermission(ProceedingJoinPoint joinPoint) throws Throwable {
// 獲取當(dāng)前用戶
User currentUser = getCurrentUser();
// 默認(rèn)情況下執(zhí)行原方法
Object result = joinPoint.proceed();
// 如果是管理員,無(wú)需過(guò)濾數(shù)據(jù)
if (userService.isAdmin(currentUser.getId())) {
return result;
}
// 對(duì)查詢結(jié)果進(jìn)行過(guò)濾
if (result instanceof Collection) {
Collection<?> collection = (Collection<?>) result;
// 實(shí)現(xiàn)數(shù)據(jù)過(guò)濾邏輯...
} else if (result instanceof Page) {
Page<?> page = (Page<?>) result;
// 實(shí)現(xiàn)分頁(yè)數(shù)據(jù)過(guò)濾...
}
return result;
}
/**
* 獲取當(dāng)前登錄用戶
*/
private User getCurrentUser() {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication == null || !authentication.isAuthenticated()) {
return null;
}
Object principal = authentication.getPrincipal();
if (principal instanceof User) {
return (User) principal;
}
return null;
}
}
/**
* 自定義角色注解
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequiresRole {
String[] value();
}
使用示例
@RestController
@RequestMapping("/api/users")
public class UserController {
@Autowired
private UserService userService;
@GetMapping
@RequiresPermission("user:list")
public List<User> listUsers() {
return userService.findAll();
}
@GetMapping("/{id}")
@RequiresPermission("user:view")
public User getUser(@PathVariable Long id) {
return userService.findById(id);
}
@PostMapping
@RequiresPermission(value = {"user:create", "user:edit"}, logical = RequiresPermission.LogicalType.OR)
public User createUser(@RequestBody User user) {
return userService.save(user);
}
@DeleteMapping("/{id}")
@RequiresRole("ADMIN")
public void deleteUser(@PathVariable Long id) {
userService.delete(id);
}
@PutMapping("/{id}/status")
@RequiresPermission(value = {"user:edit", "user:manage"}, logical = RequiresPermission.LogicalType.AND)
public User updateUserStatus(@PathVariable Long id, @RequestParam String status) {
return userService.updateStatus(id, status);
}
}
場(chǎng)景三:自定義緩存實(shí)現(xiàn)
業(yè)務(wù)需求
緩存是提升應(yīng)用性能的關(guān)鍵手段,通過(guò)AOP可以實(shí)現(xiàn):
- 自定義緩存策略,滿足特定業(yè)務(wù)需求
- 細(xì)粒度的緩存控制
- 靈活的緩存鍵生成和過(guò)期策略
實(shí)現(xiàn)方案
首先定義緩存注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cacheable {
/**
* 緩存名稱
*/
String cacheName();
/**
* 緩存鍵表達(dá)式,支持SpEL表達(dá)式
*/
String key() default "";
/**
* 過(guò)期時(shí)間(秒)
*/
long expireTime() default 300;
/**
* 是否使用方法參數(shù)作為緩存鍵的一部分
*/
boolean useMethodParameters() default true;
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CacheEvict {
/**
* 緩存名稱
*/
String cacheName();
/**
* 緩存鍵表達(dá)式
*/
String key() default "";
/**
* 是否清除所有緩存
*/
boolean allEntries() default false;
}
實(shí)現(xiàn)緩存切面:
@Aspect
@Component
@Slf4j
public class CacheAspect {
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private CacheKeyGenerator keyGenerator;
/**
* 定義緩存獲取切點(diǎn)
*/
@Pointcut("@annotation(com.example.demo.annotation.Cacheable)")
public void cacheableOperation() {}
/**
* 定義緩存清除切點(diǎn)
*/
@Pointcut("@annotation(com.example.demo.annotation.CacheEvict)")
public void cacheEvictOperation() {}
/**
* 緩存環(huán)繞通知
*/
@Around("cacheableOperation() && @annotation(cacheable)")
public Object handleCacheable(ProceedingJoinPoint joinPoint, Cacheable cacheable) throws Throwable {
// 生成緩存鍵
String cacheKey = generateCacheKey(joinPoint, cacheable.cacheName(), cacheable.key(), cacheable.useMethodParameters());
// 檢查緩存中是否已有數(shù)據(jù)
Boolean hasKey = redisTemplate.hasKey(cacheKey);
if (Boolean.TRUE.equals(hasKey)) {
Object cachedValue = redisTemplate.opsForValue().get(cacheKey);
log.debug("Cache hit for key: {}", cacheKey);
return cachedValue;
}
// 緩存未命中,執(zhí)行方法獲取結(jié)果
log.debug("Cache miss for key: {}", cacheKey);
Object result = joinPoint.proceed();
// 將結(jié)果存入緩存
if (result != null) {
redisTemplate.opsForValue().set(cacheKey, result, cacheable.expireTime(), TimeUnit.SECONDS);
log.debug("Stored in cache with key: {}, expire time: {}s", cacheKey, cacheable.expireTime());
}
return result;
}
/**
* 緩存清除前置通知
*/
@Before("cacheEvictOperation() && @annotation(cacheEvict)")
public void handleCacheEvict(JoinPoint joinPoint, CacheEvict cacheEvict) {
if (cacheEvict.allEntries()) {
// 清除該緩存名稱下的所有條目
String cachePattern = cacheEvict.cacheName() + ":*";
Set<String> keys = redisTemplate.keys(cachePattern);
if (keys != null && !keys.isEmpty()) {
redisTemplate.delete(keys);
log.debug("Cleared all cache entries with pattern: {}", cachePattern);
}
} else {
// 清除指定鍵的緩存
String cacheKey = generateCacheKey(joinPoint, cacheEvict.cacheName(), cacheEvict.key(), true);
redisTemplate.delete(cacheKey);
log.debug("Cleared cache with key: {}", cacheKey);
}
}
/**
* 生成緩存鍵
*/
private String generateCacheKey(JoinPoint joinPoint, String cacheName, String keyExpression, boolean useParams) {
StringBuilder keyBuilder = new StringBuilder(cacheName).append(":");
// 如果提供了自定義鍵表達(dá)式
if (StringUtils.hasText(keyExpression)) {
String evaluatedKey = keyGenerator.generateKey(keyExpression, joinPoint);
keyBuilder.append(evaluatedKey);
} else if (useParams) {
// 使用方法簽名和參數(shù)作為鍵
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getName();
keyBuilder.append(methodName);
// 添加參數(shù)
Object[] args = joinPoint.getArgs();
if (args != null && args.length > 0) {
for (Object arg : args) {
if (arg != null) {
keyBuilder.append(":").append(arg.hashCode());
} else {
keyBuilder.append(":null");
}
}
}
} else {
// 僅使用方法名
keyBuilder.append(joinPoint.getSignature().getName());
}
return keyBuilder.toString();
}
}
/**
* 緩存鍵生成器,支持SpEL表達(dá)式
*/
@Component
public class CacheKeyGenerator {
private final ExpressionParser parser = new SpelExpressionParser();
private final StandardEvaluationContext context = new StandardEvaluationContext();
public String generateKey(String expression, JoinPoint joinPoint) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Object[] args = joinPoint.getArgs();
String[] parameterNames = signature.getParameterNames();
// 設(shè)置方法參數(shù)為上下文變量
for (int i = 0; i < parameterNames.length; i++) {
context.setVariable(parameterNames[i], args[i]);
}
// 添加額外的元數(shù)據(jù)
context.setVariable("method", method.getName());
context.setVariable("class", method.getDeclaringClass().getSimpleName());
context.setVariable("target", joinPoint.getTarget());
// 執(zhí)行表達(dá)式
Expression exp = parser.parseExpression(expression);
return exp.getValue(context, String.class);
}
}
Redis配置
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
// 使用Jackson2JsonRedisSerializer序列化值
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
// 設(shè)置鍵的序列化方式為字符串
template.setKeySerializer(new StringRedisSerializer());
// 值使用JSON序列化
template.setValueSerializer(jackson2JsonRedisSerializer);
// Hash鍵也使用字符串
template.setHashKeySerializer(new StringRedisSerializer());
// Hash值使用JSON序列化
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
使用示例
@Service
public class ProductService {
@Autowired
private ProductRepository productRepository;
@Cacheable(cacheName = "products", expireTime = 3600)
public Product getById(Long id) {
return productRepository.findById(id).orElse(null);
}
@Cacheable(cacheName = "products", key = "'list:category:' + #categoryId", expireTime = 1800)
public List<Product> getByCategory(Long categoryId) {
return productRepository.findByCategoryId(categoryId);
}
@CacheEvict(cacheName = "products", allEntries = true)
public Product save(Product product) {
return productRepository.save(product);
}
@CacheEvict(cacheName = "products", key = "'list:category:' + #product.categoryId")
public void deleteProductFromCategory(Product product) {
productRepository.delete(product);
}
}
場(chǎng)景四:統(tǒng)一異常處理與重試機(jī)制
業(yè)務(wù)需求
在分布式系統(tǒng)或復(fù)雜業(yè)務(wù)場(chǎng)景中,我們常常需要:
- 優(yōu)雅地處理異常
- 對(duì)某些操作進(jìn)行自動(dòng)重試
- 對(duì)關(guān)鍵操作進(jìn)行冪等性保證
實(shí)現(xiàn)方案
首先定義重試和異常處理注解:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Retryable {
/**
* 最大重試次數(shù)
*/
int maxAttempts() default 3;
/**
* 重試間隔(毫秒)
*/
long backoff() default 1000;
/**
* 指定捕獲的異常類型
*/
Class<? extends Throwable>[] value() default {Exception.class};
/**
* 重試策略
*/
RetryStrategy strategy() default RetryStrategy.FIXED;
/**
* 重試策略枚舉
*/
enum RetryStrategy {
/**
* 固定間隔
*/
FIXED,
/**
* 指數(shù)退避
*/
EXPONENTIAL
}
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Idempotent {
/**
* 冪等鍵表達(dá)式
*/
String key();
/**
* 過(guò)期時(shí)間(秒)
*/
long expireSeconds() default 300;
}
實(shí)現(xiàn)異常處理和重試切面:
@Aspect
@Component
@Slf4j
public class RetryAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
/**
* 定義可重試操作切點(diǎn)
*/
@Pointcut("@annotation(com.example.demo.annotation.Retryable)")
public void retryableOperation() {}
/**
* 定義冪等操作切點(diǎn)
*/
@Pointcut("@annotation(com.example.demo.annotation.Idempotent)")
public void idempotentOperation() {}
/**
* 重試環(huán)繞通知
*/
@Around("retryableOperation() && @annotation(retryable)")
public Object handleRetry(ProceedingJoinPoint joinPoint, Retryable retryable) throws Throwable {
int attempts = 0;
Class<? extends Throwable>[] retryableExceptions = retryable.value();
Retryable.RetryStrategy strategy = retryable.strategy();
while (true) {
attempts++;
try {
// 執(zhí)行目標(biāo)方法
return joinPoint.proceed();
} catch (Throwable t) {
// 檢查是否是需要重試的異常類型
boolean shouldRetry = false;
for (Class<? extends Throwable> exceptionType : retryableExceptions) {
if (exceptionType.isInstance(t)) {
shouldRetry = true;
break;
}
}
// 如果不需要重試,或者達(dá)到最大重試次數(shù),則拋出異常
if (!shouldRetry || attempts >= retryable.maxAttempts()) {
log.warn("Method {} failed after {} attempts: {}",
joinPoint.getSignature().getName(), attempts, t.getMessage());
throw t;
}
// 計(jì)算重試等待時(shí)間
long waitTime;
if (strategy == Retryable.RetryStrategy.EXPONENTIAL) {
// 指數(shù)退避: 基礎(chǔ)時(shí)間 * 2^(嘗試次數(shù)-1)
waitTime = retryable.backoff() * (long) Math.pow(2, attempts - 1);
} else {
// 固定間隔
waitTime = retryable.backoff();
}
log.info("Retrying {} (attempt {}/{}) after {} ms due to: {}",
joinPoint.getSignature().getName(),
attempts,
retryable.maxAttempts(),
waitTime,
t.getMessage());
// 等待指定時(shí)間后重試
Thread.sleep(waitTime);
}
}
}
/**
* 冪等性環(huán)繞通知
*/
@Around("idempotentOperation() && @annotation(idempotent)")
public Object handleIdempotent(ProceedingJoinPoint joinPoint, Idempotent idempotent) throws Throwable {
// 解析冪等鍵
String idempotentKey = resolveIdempotentKey(joinPoint, idempotent.key());
String lockKey = "idempotent:" + idempotentKey;
// 嘗試設(shè)置分布式鎖
Boolean success = redisTemplate.opsForValue().setIfAbsent(
lockKey, "PROCESSING", idempotent.expireSeconds(), TimeUnit.SECONDS);
if (Boolean.TRUE.equals(success)) {
try {
// 獲取鎖成功,執(zhí)行業(yè)務(wù)邏輯
Object result = joinPoint.proceed();
// 將結(jié)果存入Redis
String resultKey = "result:" + lockKey;
redisTemplate.opsForValue().set(
resultKey, new ObjectMapper().writeValueAsString(result),
idempotent.expireSeconds(), TimeUnit.SECONDS);
// 標(biāo)記為已處理
redisTemplate.opsForValue().set(
lockKey, "COMPLETED", idempotent.expireSeconds(), TimeUnit.SECONDS);
return result;
} catch (Throwable t) {
// 處理失敗,標(biāo)記錯(cuò)誤
redisTemplate.opsForValue().set(
lockKey, "ERROR:" + t.getMessage(), idempotent.expireSeconds(), TimeUnit.SECONDS);
throw t;
}
} else {
// 獲取鎖失敗,表示操作正在處理或已處理
String status = redisTemplate.opsForValue().get(lockKey);
if ("PROCESSING".equals(status)) {
// 還在處理中
throw new ConcurrentOperationException("操作正在處理中,請(qǐng)勿重復(fù)提交");
} else if (status != null && status.startsWith("ERROR:")) {
// 之前處理出錯(cuò)
throw new OperationFailedException("操作處理失敗: " + status.substring(6));
} else if ("COMPLETED".equals(status)) {
// 已完成,嘗試返回之前的結(jié)果
String resultKey = "result:" + lockKey;
String resultJson = redisTemplate.opsForValue().get(resultKey);
if (resultJson != null) {
// 將JSON反序列化為響應(yīng)對(duì)象
Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
Class<?> returnType = method.getReturnType();
try {
return new ObjectMapper().readValue(resultJson, returnType);
} catch (Exception e) {
log.error("Failed to deserialize cached result: {}", e.getMessage());
}
}
// 如果沒(méi)有找到結(jié)果或反序列化失敗,返回成功但無(wú)法提供上次結(jié)果的消息
throw new OperationAlreadyCompletedException("操作已成功處理,但無(wú)法提供上次操作的結(jié)果");
}
// 狀態(tài)未知,拋出異常
throw new OperationFailedException("操作狀態(tài)未知");
}
}
/**
* 解析冪等鍵表達(dá)式
*/
private String resolveIdempotentKey(JoinPoint joinPoint, String keyExpression) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String[] paramNames = signature.getParameterNames();
Object[] args = joinPoint.getArgs();
// 創(chuàng)建表達(dá)式上下文
StandardEvaluationContext context = new StandardEvaluationContext();
// 添加方法參數(shù)
for (int i = 0; i < paramNames.length; i++) {
context.setVariable(paramNames[i], args[i]);
}
// 添加類名和方法名
context.setVariable("method", signature.getMethod().getName());
context.setVariable("class", signature.getDeclaringType().getSimpleName());
// 解析表達(dá)式
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(keyExpression);
return expression.getValue(context, String.class);
}
}
// 自定義異常類
public class ConcurrentOperationException extends RuntimeException {
public ConcurrentOperationException(String message) {
super(message);
}
}
public class OperationFailedException extends RuntimeException {
public OperationFailedException(String message) {
super(message);
}
}
public class OperationAlreadyCompletedException extends RuntimeException {
public OperationAlreadyCompletedException(String message) {
super(message);
}
}
使用示例
@Service
public class PaymentService {
@Autowired
private PaymentGateway paymentGateway;
@Autowired
private OrderRepository orderRepository;
/**
* 遠(yuǎn)程支付處理,可能遇到網(wǎng)絡(luò)問(wèn)題需要重試
*/
@Retryable(
value = {ConnectException.class, TimeoutException.class, PaymentGatewayException.class},
maxAttempts = 3,
backoff = 2000,
strategy = Retryable.RetryStrategy.EXPONENTIAL
)
public PaymentResult processPayment(String orderId, BigDecimal amount) {
log.info("Processing payment for order {} with amount {}", orderId, amount);
// 調(diào)用遠(yuǎn)程支付網(wǎng)關(guān)
return paymentGateway.processPayment(orderId, amount);
}
/**
* 訂單退款,需要保證冪等性
*/
@Idempotent(key = "'refund:' + #orderId", expireSeconds = 3600)
public RefundResult refundOrder(String orderId) {
Order order = orderRepository.findById(orderId)
.orElseThrow(() -> new OrderNotFoundException("Order not found: " + orderId));
// 驗(yàn)證訂單狀態(tài)
if (!"PAID".equals(order.getStatus())) {
throw new InvalidOrderStatusException("Cannot refund order with status: " + order.getStatus());
}
// 調(diào)用支付網(wǎng)關(guān)退款
RefundResult result = paymentGateway.refund(order.getPaymentId(), order.getTotalAmount());
// 更新訂單狀態(tài)
order.setStatus("REFUNDED");
order.setRefundTime(LocalDateTime.now());
orderRepository.save(order);
return result;
}
}
@Service
public class StockService {
@Autowired
private StockRepository stockRepository;
/**
* 扣減庫(kù)存,需要在分布式環(huán)境下重試和冪等
*/
@Retryable(
value = {OptimisticLockException.class, StockInsufficientException.class},
maxAttempts = 5,
backoff = 500
)
@Idempotent(key = "'deduct:' + #orderId")
public void deductStock(String orderId, List<OrderItem> items) {
// 檢查是否存在庫(kù)存記錄
for (OrderItem item : items) {
Stock stock = stockRepository.findByProductId(item.getProductId());
if (stock == null) {
throw new ProductNotFoundException("Product not found: " + item.getProductId());
}
if (stock.getAvailable() < item.getQuantity()) {
throw new StockInsufficientException(
"Insufficient stock for product: " + item.getProductId() +
", requested: " + item.getQuantity() +
", available: " + stock.getAvailable());
}
}
// 執(zhí)行庫(kù)存扣減
for (OrderItem item : items) {
stockRepository.deductStock(item.getProductId(), item.getQuantity());
}
}
}
結(jié)論
AOP是SpringBoot中一個(gè)強(qiáng)大的編程范式,通過(guò)這些模式,我們可以將橫切關(guān)注點(diǎn)與業(yè)務(wù)邏輯解耦,使代碼更加模塊化、可維護(hù),同時(shí)提高系統(tǒng)的健壯性和安全性。
以上就是SpringBoot中四種AOP實(shí)戰(zhàn)應(yīng)用場(chǎng)景及代碼實(shí)現(xiàn)的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot AOP應(yīng)用場(chǎng)景的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Spring boot整合mybatis實(shí)現(xiàn)過(guò)程圖解
這篇文章主要介紹了Spring boot整合mybatis實(shí)現(xiàn)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08
使用Java 壓縮文件打包tar.gz 包的詳細(xì)教程
本文帶領(lǐng)大家學(xué)習(xí)如何使用Java 壓縮文件打包tar.gz 包,主要通過(guò) Apache compress 工具打包,通過(guò)示例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2021-05-05
RabbitMQ集群實(shí)現(xiàn)消息的高可用性和負(fù)載均衡
文章解釋了RabbitMQ集群的概念及其構(gòu)建目的,詳細(xì)闡述了其底層原理,包括Erlang/OTP的分布式基因、ErlangCookie認(rèn)證和分布式進(jìn)程管理,感興趣的朋友跟隨小編一起看看吧2026-04-04
Java ArrayList擴(kuò)容機(jī)制原理深入分析
在Java中,ArrayList是最常用的集合之一。它是一種容器,它的內(nèi)部定義了一個(gè)Object類型的數(shù)組elementData,因此可用于存儲(chǔ)任意類型的數(shù)據(jù)。我們知道,數(shù)組是長(zhǎng)度恒定的。而ArrayList相當(dāng)于是一個(gè)長(zhǎng)度可變的動(dòng)態(tài)數(shù)組,一起來(lái)看看的它的擴(kuò)容機(jī)制2023-02-02

