最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot中四種AOP實戰(zhàn)應(yīng)用場景及代碼實現(xiàn)

 更新時間:2025年05月03日 07:55:42   作者:風象南  
面向切面編程(AOP)是Spring框架的核心功能之一,它通過預(yù)編譯和運行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護,在SpringBoot應(yīng)用中,AOP能夠幫助我們優(yōu)雅地解決橫切關(guān)注點問題,本文將介紹SpringBoot中4種AOP實戰(zhàn)應(yīng)用場景,需要的朋友可以參考下

引言

面向切面編程(AOP)是Spring框架的核心功能之一,它通過預(yù)編譯和運行期動態(tài)代理實現(xiàn)程序功能的統(tǒng)一維護。在SpringBoot應(yīng)用中,AOP能夠幫助我們優(yōu)雅地解決橫切關(guān)注點問題,如日志記錄、權(quán)限控制、性能監(jiān)控等,這些功能往往貫穿整個應(yīng)用但又不屬于業(yè)務(wù)核心邏輯。

本文將介紹SpringBoot中4種AOP實戰(zhàn)應(yīng)用場景,包括代碼實現(xiàn)、核心原理及實踐。

場景一:日志記錄與性能監(jiān)控

業(yè)務(wù)需求

在企業(yè)級應(yīng)用中,我們通常需要:

  • 記錄API請求的調(diào)用情況
  • 監(jiān)控方法執(zhí)行時間,發(fā)現(xiàn)性能瓶頸
  • 追蹤方法調(diào)用的入?yún)⒑头祷亟Y(jié)果

實現(xiàn)方案

@Aspect
@Component
@Slf4j
public class LoggingAspect {
    
    /**
     * 定義切點:所有controller包下的所有方法
     */
    @Pointcut("execution(* com.example.demo.controller.*.*(..))")
    public void controllerMethods() {}
    
    /**
     * 環(huán)繞通知:記錄請求日志和執(zhí)行時間
     */
    @Around("controllerMethods()")
    public Object logAroundControllers(ProceedingJoinPoint joinPoint) throws Throwable {
        // 獲取方法簽名
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String methodName = signature.getName();
        String className = signature.getDeclaringTypeName();
        
        // 記錄請求參數(shù)
        String params = Arrays.toString(joinPoint.getArgs());
        log.info("Request to {}.{} with params: {}", className, methodName, params);
        
        // 記錄開始時間
        long startTime = System.currentTimeMillis();
        
        // 執(zhí)行目標方法
        Object result;
        try {
            result = joinPoint.proceed();
            
            // 計算執(zhí)行時間
            long executionTime = System.currentTimeMillis() - startTime;
            
            // 記錄返回結(jié)果和執(zhí)行時間
            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ù)層方法切點
     */
    @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è)置的級別記錄日志
        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)
    }
}

擴展:MDC實現(xiàn)請求跟蹤

@Component
public class RequestIdFilter implements Filter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            // 為每個請求生成唯一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 {
            // 請求完成后清理MDC
            MDC.clear();
        }
    }
}

場景二:權(quán)限控制與安全增強

業(yè)務(wù)需求

在企業(yè)應(yīng)用中,權(quán)限控制是一個常見的需求:

  • 基于角色的接口訪問控制
  • 細粒度的操作權(quán)限控制
  • 對敏感數(shù)據(jù)訪問的記錄

實現(xiàn)方案

首先,創(chuàng)建自定義注解:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface RequiresPermission {
    /**
     * 所需權(quán)限編碼數(shù)組,滿足其中任一即可
     */
    String[] value() default {};
    
    /**
     * 權(quán)限邏輯類型:AND(同時具有所有權(quán)限), OR(滿足任一權(quán)限即可)
     */
    LogicalType logical() default LogicalType.OR;
    
    public enum LogicalType {
        AND, OR
    }
}

實現(xiàn)權(quán)限切面:

@Aspect
@Component
@Slf4j
public class PermissionAspect {
    
    @Autowired
    private UserService userService;
    
    /**
     * 定義切點:所有帶有@RequiresPermission注解的方法
     */
    @Pointcut("@annotation(com.example.demo.annotation.RequiresPermission)")
    public void permissionCheck() {}
    
    /**
     * 權(quán)限驗證前置通知
     */
    @Before("permissionCheck() && @annotation(requiresPermission)")
    public void checkPermission(JoinPoint joinPoint, RequiresPermission requiresPermission) {
        // 獲取當前用戶
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            throw new UnauthorizedException("用戶未登錄或會話已過期");
        }
        
        // 獲取用戶權(quán)限列表
        Set<String> userPermissions = userService.getUserPermissions(currentUser.getId());
        
        // 獲取注解中要求的權(quán)限
        String[] requiredPermissions = requiresPermission.value();
        RequiresPermission.LogicalType logicalType = requiresPermission.logical();
        
        // 權(quán)限校驗
        boolean hasPermission = false;
        
        if (logicalType == RequiresPermission.LogicalType.OR) {
            // 滿足任一權(quán)限即可
            for (String permission : requiredPermissions) {
                if (userPermissions.contains(permission)) {
                    hasPermission = true;
                    break;
                }
            }
        } else {
            // 必須同時滿足所有權(quán)限
            hasPermission = true;
            for (String permission : requiredPermissions) {
                if (!userPermissions.contains(permission)) {
                    hasPermission = false;
                    break;
                }
            }
        }
        
        if (!hasPermission) {
            log.warn("用戶 {} 嘗試訪問未授權(quán)資源: {}.{}", 
                    currentUser.getUsername(),
                    joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName());
            
            throw new ForbiddenException("權(quán)限不足,無法執(zhí)行該操作");
        }
        
        // 記錄敏感操作
        log.info("用戶 {} 執(zhí)行了需授權(quán)操作: {}.{}", 
                currentUser.getUsername(), 
                joinPoint.getSignature().getDeclaringTypeName(),
                joinPoint.getSignature().getName());
    }
    
    /**
     * 定義切點:帶有@RequiresRole注解的方法
     */
    @Pointcut("@annotation(com.example.demo.annotation.RequiresRole)")
    public void roleCheck() {}
    
    /**
     * 角色檢查前置通知
     */
    @Before("roleCheck() && @annotation(requiresRole)")
    public void checkRole(JoinPoint joinPoint, RequiresRole requiresRole) {
        // 獲取當前用戶
        User currentUser = getCurrentUser();
        if (currentUser == null) {
            throw new UnauthorizedException("用戶未登錄或會話已過期");
        }
        
        // 獲取用戶角色
        Set<String> userRoles = userService.getUserRoles(currentUser.getId());
        
        // 獲取注解中要求的角色
        String[] requiredRoles = requiresRole.value();
        
        // 角色校驗
        boolean hasRole = false;
        for (String role : requiredRoles) {
            if (userRoles.contains(role)) {
                hasRole = true;
                break;
            }
        }
        
        if (!hasRole) {
            log.warn("用戶 {} 嘗試訪問未授權(quán)角色資源: {}.{}", 
                    currentUser.getUsername(),
                    joinPoint.getSignature().getDeclaringTypeName(),
                    joinPoint.getSignature().getName());
            
            throw new ForbiddenException("角色不足,無法執(zhí)行該操作");
        }
    }
    
    /**
     * 數(shù)據(jù)權(quán)限過濾切點:針對查詢方法
     */
    @Pointcut("execution(* com.example.demo.service.*.find*(..))")
    public void dataPermissionFilter() {}
    
    /**
     * 數(shù)據(jù)權(quán)限過濾通知
     */
    @Around("dataPermissionFilter()")
    public Object filterDataByPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        // 獲取當前用戶
        User currentUser = getCurrentUser();
        
        // 默認情況下執(zhí)行原方法
        Object result = joinPoint.proceed();
        
        // 如果是管理員,無需過濾數(shù)據(jù)
        if (userService.isAdmin(currentUser.getId())) {
            return result;
        }
        
        // 對查詢結(jié)果進行過濾
        if (result instanceof Collection) {
            Collection<?> collection = (Collection<?>) result;
            // 實現(xiàn)數(shù)據(jù)過濾邏輯...
        } else if (result instanceof Page) {
            Page<?> page = (Page<?>) result;
            // 實現(xiàn)分頁數(shù)據(jù)過濾...
        }
        
        return result;
    }
    
    /**
     * 獲取當前登錄用戶
     */
    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);
    }
}

場景三:自定義緩存實現(xiàn)

業(yè)務(wù)需求

緩存是提升應(yīng)用性能的關(guān)鍵手段,通過AOP可以實現(xiàn):

  • 自定義緩存策略,滿足特定業(yè)務(wù)需求
  • 細粒度的緩存控制
  • 靈活的緩存鍵生成和過期策略

實現(xiàn)方案

首先定義緩存注解:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Cacheable {
    /**
     * 緩存名稱
     */
    String cacheName();
    
    /**
     * 緩存鍵表達式,支持SpEL表達式
     */
    String key() default "";
    
    /**
     * 過期時間(秒)
     */
    long expireTime() default 300;
    
    /**
     * 是否使用方法參數(shù)作為緩存鍵的一部分
     */
    boolean useMethodParameters() default true;
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CacheEvict {
    /**
     * 緩存名稱
     */
    String cacheName();
    
    /**
     * 緩存鍵表達式
     */
    String key() default "";
    
    /**
     * 是否清除所有緩存
     */
    boolean allEntries() default false;
}

實現(xiàn)緩存切面:

@Aspect
@Component
@Slf4j
public class CacheAspect {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    @Autowired
    private CacheKeyGenerator keyGenerator;
    
    /**
     * 定義緩存獲取切點
     */
    @Pointcut("@annotation(com.example.demo.annotation.Cacheable)")
    public void cacheableOperation() {}
    
    /**
     * 定義緩存清除切點
     */
    @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(":");
        
        // 如果提供了自定義鍵表達式
        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表達式
 */
@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í)行表達式
        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);
    }
}

場景四:統(tǒng)一異常處理與重試機制

業(yè)務(wù)需求

在分布式系統(tǒng)或復(fù)雜業(yè)務(wù)場景中,我們常常需要:

  • 優(yōu)雅地處理異常
  • 對某些操作進行自動重試
  • 對關(guān)鍵操作進行冪等性保證

實現(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 {
    /**
     * 冪等鍵表達式
     */
    String key();
    
    /**
     * 過期時間(秒)
     */
    long expireSeconds() default 300;
}

實現(xiàn)異常處理和重試切面:

@Aspect
@Component
@Slf4j
public class RetryAspect {
    
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    
    /**
     * 定義可重試操作切點
     */
    @Pointcut("@annotation(com.example.demo.annotation.Retryable)")
    public void retryableOperation() {}
    
    /**
     * 定義冪等操作切點
     */
    @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í)行目標方法
                return joinPoint.proceed();
            } catch (Throwable t) {
                // 檢查是否是需要重試的異常類型
                boolean shouldRetry = false;
                for (Class<? extends Throwable> exceptionType : retryableExceptions) {
                    if (exceptionType.isInstance(t)) {
                        shouldRetry = true;
                        break;
                    }
                }
                
                // 如果不需要重試,或者達到最大重試次數(shù),則拋出異常
                if (!shouldRetry || attempts >= retryable.maxAttempts()) {
                    log.warn("Method {} failed after {} attempts: {}", 
                            joinPoint.getSignature().getName(), attempts, t.getMessage());
                    throw t;
                }
                
                // 計算重試等待時間
                long waitTime;
                if (strategy == Retryable.RetryStrategy.EXPONENTIAL) {
                    // 指數(shù)退避: 基礎(chǔ)時間 * 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());
                
                // 等待指定時間后重試
                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);
                
                // 標記為已處理
                redisTemplate.opsForValue().set(
                        lockKey, "COMPLETED", idempotent.expireSeconds(), TimeUnit.SECONDS);
                
                return result;
            } catch (Throwable t) {
                // 處理失敗,標記錯誤
                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("操作正在處理中,請勿重復(fù)提交");
            } else if (status != null && status.startsWith("ERROR:")) {
                // 之前處理出錯
                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)對象
                    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());
                    }
                }
                
                // 如果沒有找到結(jié)果或反序列化失敗,返回成功但無法提供上次結(jié)果的消息
                throw new OperationAlreadyCompletedException("操作已成功處理,但無法提供上次操作的結(jié)果");
            }
            
            // 狀態(tài)未知,拋出異常
            throw new OperationFailedException("操作狀態(tài)未知");
        }
    }
    
    /**
     * 解析冪等鍵表達式
     */
    private String resolveIdempotentKey(JoinPoint joinPoint, String keyExpression) {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        String[] paramNames = signature.getParameterNames();
        Object[] args = joinPoint.getArgs();
        
        // 創(chuàng)建表達式上下文
        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());
        
        // 解析表達式
        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;
    
    /**
     * 遠程支付處理,可能遇到網(wǎng)絡(luò)問題需要重試
     */
    @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)用遠程支付網(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));
        
        // 驗證訂單狀態(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;
    
    /**
     * 扣減庫存,需要在分布式環(huán)境下重試和冪等
     */
    @Retryable(
        value = {OptimisticLockException.class, StockInsufficientException.class},
        maxAttempts = 5,
        backoff = 500
    )
    @Idempotent(key = "'deduct:' + #orderId")
    public void deductStock(String orderId, List<OrderItem> items) {
        // 檢查是否存在庫存記錄
        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í)行庫存扣減
        for (OrderItem item : items) {
            stockRepository.deductStock(item.getProductId(), item.getQuantity());
        }
    }
}

結(jié)論

AOP是SpringBoot中一個強大的編程范式,通過這些模式,我們可以將橫切關(guān)注點與業(yè)務(wù)邏輯解耦,使代碼更加模塊化、可維護,同時提高系統(tǒng)的健壯性和安全性。

以上就是SpringBoot中四種AOP實戰(zhàn)應(yīng)用場景及代碼實現(xiàn)的詳細內(nèi)容,更多關(guān)于SpringBoot AOP應(yīng)用場景的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • 基于module-info.class的問題

    基于module-info.class的問題

    這篇文章主要介紹了基于module-info.class的問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • 利用Java讀取二進制文件實例詳解

    利用Java讀取二進制文件實例詳解

    這篇文章主要給大家介紹了利用Java讀取二進制文件的相關(guān)資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者使用java具有一定的參考學習價值,需要的朋友們下面跟著小編來一起學習學習吧。
    2017-08-08
  • Java多線程窗口售票問題實例

    Java多線程窗口售票問題實例

    這篇文章主要介紹了Java多線程窗口售票問題實例,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • Spring boot整合mybatis實現(xiàn)過程圖解

    Spring boot整合mybatis實現(xiàn)過程圖解

    這篇文章主要介紹了Spring boot整合mybatis實現(xiàn)過程圖解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-08-08
  • 使用Java 壓縮文件打包tar.gz 包的詳細教程

    使用Java 壓縮文件打包tar.gz 包的詳細教程

    本文帶領(lǐng)大家學習如何使用Java 壓縮文件打包tar.gz 包,主要通過 Apache compress 工具打包,通過示例代碼給大家介紹的非常詳細,感興趣的朋友跟隨小編一起看看吧
    2021-05-05
  • JAVA 中Spring的@Async用法總結(jié)

    JAVA 中Spring的@Async用法總結(jié)

    這篇文章主要介紹了JAVA 中Spring的@Async用法總結(jié)的相關(guān)資料,需要的朋友可以參考下
    2017-03-03
  • 淺談在JAVA項目中LOG4J的使用

    淺談在JAVA項目中LOG4J的使用

    下面小編就為大家?guī)硪黄獪\談在JAVA項目中LOG4J的使用。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2016-12-12
  • idea同步y(tǒng)api插件的詳細步驟

    idea同步y(tǒng)api插件的詳細步驟

    yapi是一個很好的接口文檔維護工具,其swagger功能,可將接口信息同步到y(tǒng)api平臺上,這篇文章主要介紹了idea同步y(tǒng)api插件,需要的朋友可以參考下
    2024-04-04
  • RabbitMQ集群實現(xiàn)消息的高可用性和負載均衡

    RabbitMQ集群實現(xiàn)消息的高可用性和負載均衡

    文章解釋了RabbitMQ集群的概念及其構(gòu)建目的,詳細闡述了其底層原理,包括Erlang/OTP的分布式基因、ErlangCookie認證和分布式進程管理,感興趣的朋友跟隨小編一起看看吧
    2026-04-04
  • Java ArrayList擴容機制原理深入分析

    Java ArrayList擴容機制原理深入分析

    在Java中,ArrayList是最常用的集合之一。它是一種容器,它的內(nèi)部定義了一個Object類型的數(shù)組elementData,因此可用于存儲任意類型的數(shù)據(jù)。我們知道,數(shù)組是長度恒定的。而ArrayList相當于是一個長度可變的動態(tài)數(shù)組,一起來看看的它的擴容機制
    2023-02-02

最新評論

景谷| 观塘区| 凤山县| 吉林市| 文昌市| 花莲县| 西平县| 阿勒泰市| 岑巩县| 丰台区| 双牌县| 榕江县| 灌阳县| 周宁县| 永泰县| 北流市| 寿宁县| 藁城市| 舟曲县| 和平县| 通许县| 吉林省| 洛南县| 惠安县| 综艺| 贺兰县| 毕节市| 马山县| 博爱县| 平山县| 江北区| 卢龙县| 江永县| 平谷区| 隆昌县| 大连市| 珠海市| 林口县| 云安县| 台安县| 谷城县|