活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

全面掌握AntiX系统开发框架的高级特性与最佳实践通过真实项目案例学习如何充分发挥框架优势构建稳定高效的企业级应用系统

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-2 20:50:01 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在当今快速发展的软件开发领域,选择合适的开发框架对于构建高效、稳定且可维护的企业级应用系统至关重要。AntiX系统开发框架作为一个现代化的企业级开发解决方案,提供了一套全面的工具和功能,帮助开发团队快速构建高性能、可扩展的应用程序。本文将深入探讨AntiX框架的高级特性、最佳实践,并通过真实项目案例展示如何充分利用该框架的优势,构建稳定高效的企业级应用系统。

AntiX框架概述

AntiX是一个全栈企业级开发框架,旨在简化复杂业务应用的开发过程。它采用模块化设计,提供了从前端到后端的完整解决方案,使开发团队能够专注于业务逻辑而非底层技术细节。

核心架构

AntiX框架基于分层架构设计,主要包括以下几个核心组件:

1. 表示层:提供用户界面和交互功能
2. 业务逻辑层:处理核心业务规则和流程
3. 数据访问层:管理与数据库的交互
4. 基础设施层:提供横切关注点支持,如安全性、事务管理等

主要特点

• 高性能:采用优化的执行引擎和缓存机制,确保应用响应迅速
• 可扩展性:支持水平扩展和微服务架构,适应业务增长需求
• 开发效率:提供丰富的代码生成工具和模板,加速开发过程
• 易于维护:清晰的架构设计和完善的文档支持,降低维护成本

AntiX框架的高级特性

1. 依赖注入与控制反转

AntiX框架提供了强大的依赖注入(DI)和控制反转(IoC)容器,使组件之间的耦合度降到最低,提高代码的可测试性和可维护性。
  1. // 定义服务接口
  2. public interface UserService {
  3.     User getUserById(Long id);
  4.     void saveUser(User user);
  5. }
  6. // 实现服务
  7. @Service
  8. public class UserServiceImpl implements UserService {
  9.     private final UserRepository userRepository;
  10.    
  11.     // 通过构造函数注入依赖
  12.     @Autowired
  13.     public UserServiceImpl(UserRepository userRepository) {
  14.         this.userRepository = userRepository;
  15.     }
  16.    
  17.     @Override
  18.     public User getUserById(Long id) {
  19.         return userRepository.findById(id).orElse(null);
  20.     }
  21.    
  22.     @Override
  23.     @Transactional
  24.     public void saveUser(User user) {
  25.         userRepository.save(user);
  26.     }
  27. }
  28. // 在控制器中使用服务
  29. @RestController
  30. @RequestMapping("/api/users")
  31. public class UserController {
  32.     private final UserService userService;
  33.    
  34.     @Autowired
  35.     public UserController(UserService userService) {
  36.         this.userService = userService;
  37.     }
  38.    
  39.     @GetMapping("/{id}")
  40.     public ResponseEntity<User> getUser(@PathVariable Long id) {
  41.         User user = userService.getUserById(id);
  42.         return ResponseEntity.ok(user);
  43.     }
  44. }
复制代码

2. 面向切面编程(AOP)

AntiX框架支持面向切面编程,允许开发者将横切关注点(如日志、安全、事务等)与业务逻辑分离,提高代码的模块化程度。
  1. // 定义切面
  2. @Aspect
  3. @Component
  4. public class LoggingAspect {
  5.    
  6.     private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
  7.    
  8.     // 定义切入点
  9.     @Pointcut("execution(* com.example.antix.service.*.*(..))")
  10.     public void serviceMethods() {}
  11.    
  12.     // 前置通知
  13.     @Before("serviceMethods()")
  14.     public void logMethodCall(JoinPoint joinPoint) {
  15.         String methodName = joinPoint.getSignature().getName();
  16.         logger.info("Entering method: {}", methodName);
  17.     }
  18.    
  19.     // 后置通知
  20.     @AfterReturning(pointcut = "serviceMethods()", returning = "result")
  21.     public void logMethodReturn(JoinPoint joinPoint, Object result) {
  22.         String methodName = joinPoint.getSignature().getName();
  23.         logger.info("Exiting method: {} with result: {}", methodName, result);
  24.     }
  25.    
  26.     // 异常通知
  27.     @AfterThrowing(pointcut = "serviceMethods()", throwing = "exception")
  28.     public void logMethodException(JoinPoint joinPoint, Throwable exception) {
  29.         String methodName = joinPoint.getSignature().getName();
  30.         logger.error("Exception in method: {}: {}", methodName, exception.getMessage());
  31.     }
  32. }
复制代码

3. 高级数据访问与ORM集成

AntiX框架提供了强大的数据访问层,支持多种数据库和ORM框架,如Hibernate、MyBatis等,并提供了简化的API和高级查询功能。
  1. // 定义实体
  2. @Entity
  3. @Table(name = "users")
  4. public class User {
  5.     @Id
  6.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  7.     private Long id;
  8.    
  9.     @Column(nullable = false)
  10.     private String username;
  11.    
  12.     @Column(nullable = false)
  13.     private String email;
  14.    
  15.     @Column(nullable = false)
  16.     private String password;
  17.    
  18.     // getters and setters
  19. }
  20. // 定义Repository接口
  21. public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
  22.    
  23.     // 自定义查询方法
  24.     User findByUsername(String username);
  25.    
  26.     @Query("SELECT u FROM User u WHERE u.email = :email")
  27.     User findByEmail(@Param("email") String email);
  28.    
  29.     // 使用规范进行动态查询
  30.     default List<User> findUsersByCriteria(String username, String email) {
  31.         return findAll((Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
  32.             List<Predicate> predicates = new ArrayList<>();
  33.             
  34.             if (StringUtils.hasText(username)) {
  35.                 predicates.add(cb.like(root.get("username"), "%" + username + "%"));
  36.             }
  37.             
  38.             if (StringUtils.hasText(email)) {
  39.                 predicates.add(cb.like(root.get("email"), "%" + email + "%"));
  40.             }
  41.             
  42.             return cb.and(predicates.toArray(new Predicate[0]));
  43.         });
  44.     }
  45. }
复制代码

4. 事件驱动架构支持

AntiX框架内置了事件驱动架构支持,允许组件之间通过事件进行松耦合通信,提高系统的可扩展性和灵活性。
  1. // 定义事件
  2. public class UserCreatedEvent {
  3.     private final User user;
  4.     private final LocalDateTime createdAt;
  5.    
  6.     public UserCreatedEvent(User user) {
  7.         this.user = user;
  8.         this.createdAt = LocalDateTime.now();
  9.     }
  10.    
  11.     // getters
  12. }
  13. // 定义事件发布者
  14. @Service
  15. public class UserServiceImpl implements UserService {
  16.     private final UserRepository userRepository;
  17.     private final ApplicationEventPublisher eventPublisher;
  18.    
  19.     @Autowired
  20.     public UserServiceImpl(UserRepository userRepository, ApplicationEventPublisher eventPublisher) {
  21.         this.userRepository = userRepository;
  22.         this.eventPublisher = eventPublisher;
  23.     }
  24.    
  25.     @Override
  26.     @Transactional
  27.     public void saveUser(User user) {
  28.         userRepository.save(user);
  29.         // 发布事件
  30.         eventPublisher.publishEvent(new UserCreatedEvent(user));
  31.     }
  32. }
  33. // 定义事件监听器
  34. @Component
  35. public class UserEventListener {
  36.    
  37.     private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class);
  38.    
  39.     @EventListener
  40.     public void handleUserCreatedEvent(UserCreatedEvent event) {
  41.         User user = event.getUser();
  42.         logger.info("User created: {} at {}", user.getUsername(), event.getCreatedAt());
  43.         
  44.         // 执行其他业务逻辑,如发送欢迎邮件等
  45.         sendWelcomeEmail(user);
  46.     }
  47.    
  48.     private void sendWelcomeEmail(User user) {
  49.         // 邮件发送逻辑
  50.     }
  51. }
复制代码

5. 高级缓存机制

AntiX框架提供了强大的缓存支持,包括本地缓存和分布式缓存,帮助提高应用性能。
  1. // 启用缓存
  2. @Configuration
  3. @EnableCaching
  4. public class CacheConfig {
  5.    
  6.     @Bean
  7.     public CacheManager cacheManager() {
  8.         // 使用Redis作为分布式缓存
  9.         RedisCacheManager.Builder builder = RedisCacheManager.builder(redisConnectionFactory())
  10.                 .cacheDefaults(cacheConfiguration())
  11.                 .withInitialCacheConfigurations(getCacheConfigurations());
  12.         
  13.         return builder.build();
  14.     }
  15.    
  16.     @Bean
  17.     public RedisConnectionFactory redisConnectionFactory() {
  18.         return new LettuceConnectionFactory();
  19.     }
  20.    
  21.     private RedisCacheConfiguration cacheConfiguration() {
  22.         return RedisCacheConfiguration.defaultCacheConfig()
  23.                 .entryTtl(Duration.ofMinutes(30))
  24.                 .disableCachingNullValues()
  25.                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  26.     }
  27.    
  28.     private Map<String, RedisCacheConfiguration> getCacheConfigurations() {
  29.         Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
  30.         
  31.         // 用户缓存,TTL为1小时
  32.         cacheConfigurations.put("users", RedisCacheConfiguration.defaultCacheConfig()
  33.                 .entryTtl(Duration.ofHours(1))
  34.                 .disableCachingNullValues());
  35.         
  36.         // 产品缓存,TTL为2小时
  37.         cacheConfigurations.put("products", RedisCacheConfiguration.defaultCacheConfig()
  38.                 .entryTtl(Duration.ofHours(2))
  39.                 .disableCachingNullValues());
  40.         
  41.         return cacheConfigurations;
  42.     }
  43. }
  44. // 在服务中使用缓存
  45. @Service
  46. public class UserServiceImpl implements UserService {
  47.     private final UserRepository userRepository;
  48.    
  49.     @Autowired
  50.     public UserServiceImpl(UserRepository userRepository) {
  51.         this.userRepository = userRepository;
  52.     }
  53.    
  54.     @Override
  55.     @Cacheable(value = "users", key = "#id")
  56.     public User getUserById(Long id) {
  57.         return userRepository.findById(id).orElse(null);
  58.     }
  59.    
  60.     @Override
  61.     @CacheEvict(value = "users", key = "#user.id")
  62.     public void saveUser(User user) {
  63.         userRepository.save(user);
  64.     }
  65.    
  66.     @Override
  67.     @CacheEvict(value = "users", allEntries = true)
  68.     public void clearUserCache() {
  69.         // 清除所有用户缓存
  70.     }
  71. }
复制代码

6. 安全框架集成

AntiX框架提供了全面的安全支持,包括认证、授权、加密等功能,保护企业应用免受安全威胁。
  1. // 安全配置
  2. @Configuration
  3. @EnableWebSecurity
  4. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  5.    
  6.     @Autowired
  7.     private UserDetailsService userDetailsService;
  8.    
  9.     @Bean
  10.     public PasswordEncoder passwordEncoder() {
  11.         return new BCryptPasswordEncoder();
  12.     }
  13.    
  14.     @Override
  15.     protected void configure(AuthenticationManagerBuilder auth) throws Exception {
  16.         auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
  17.     }
  18.    
  19.     @Override
  20.     protected void configure(HttpSecurity http) throws Exception {
  21.         http
  22.             .csrf().disable()
  23.             .authorizeRequests()
  24.                 .antMatchers("/api/public/**").permitAll()
  25.                 .antMatchers("/api/admin/**").hasRole("ADMIN")
  26.                 .antMatchers("/api/user/**").hasAnyRole("USER", "ADMIN")
  27.                 .anyRequest().authenticated()
  28.             .and()
  29.             .sessionManagement()
  30.                 .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  31.             .and()
  32.             .addFilter(new JwtAuthenticationFilter(authenticationManager()))
  33.             .addFilter(new JwtAuthorizationFilter(authenticationManager()));
  34.     }
  35. }
  36. // JWT认证过滤器
  37. public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
  38.    
  39.     private final AuthenticationManager authenticationManager;
  40.    
  41.     public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
  42.         this.authenticationManager = authenticationManager;
  43.         setFilterProcessesUrl("/api/login");
  44.     }
  45.    
  46.     @Override
  47.     public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
  48.             throws AuthenticationException {
  49.         try {
  50.             UserCredentials credentials = new ObjectMapper()
  51.                     .readValue(request.getInputStream(), UserCredentials.class);
  52.             
  53.             return authenticationManager.authenticate(
  54.                     new UsernamePasswordAuthenticationToken(
  55.                             credentials.getUsername(),
  56.                             credentials.getPassword(),
  57.                             new ArrayList<>())
  58.             );
  59.         } catch (IOException e) {
  60.             throw new RuntimeException(e);
  61.         }
  62.     }
  63.    
  64.     @Override
  65.     protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
  66.             FilterChain chain, Authentication auth) throws IOException, ServletException {
  67.         String token = Jwts.builder()
  68.                 .setSubject(((User) auth.getPrincipal()).getUsername())
  69.                 .setExpiration(new Date(System.currentTimeMillis() + 864_000_000)) // 10天
  70.                 .signWith(SignatureAlgorithm.HS512, "SecretKey".getBytes())
  71.                 .compact();
  72.         
  73.         response.addHeader("Authorization", "Bearer " + token);
  74.     }
  75. }
  76. // 方法级安全
  77. @Service
  78. public class OrderServiceImpl implements OrderService {
  79.    
  80.     @PreAuthorize("hasRole('ADMIN') or #order.userId == authentication.principal.id")
  81.     public Order getOrder(Order order) {
  82.         // 获取订单逻辑
  83.     }
  84.    
  85.     @PostAuthorize("returnObject.userId == authentication.principal.id")
  86.     public Order findOrderById(Long orderId) {
  87.         // 查找订单逻辑
  88.     }
  89. }
复制代码

AntiX框架的最佳实践

1. 项目结构组织

良好的项目结构是构建可维护应用的基础。以下是AntiX框架推荐的项目结构:
  1. project-root/
  2. ├── src/
  3. │   ├── main/
  4. │   │   ├── java/
  5. │   │   │   └── com/
  6. │   │   │       └── example/
  7. │   │   │           └── application/
  8. │   │   │               ├── Application.java
  9. │   │   │               ├── config/
  10. │   │   │               │   ├── SecurityConfig.java
  11. │   │   │               │   ├── CacheConfig.java
  12. │   │   │               │   └── DatabaseConfig.java
  13. │   │   │               ├── controller/
  14. │   │   │               │   ├── UserController.java
  15. │   │   │               │   └── OrderController.java
  16. │   │   │               ├── service/
  17. │   │   │               │   ├── UserService.java
  18. │   │   │               │   ├── UserServiceImpl.java
  19. │   │   │               │   ├── OrderService.java
  20. │   │   │               │   └── OrderServiceImpl.java
  21. │   │   │               ├── repository/
  22. │   │   │               │   ├── UserRepository.java
  23. │   │   │               │   └── OrderRepository.java
  24. │   │   │               ├── model/
  25. │   │   │               │   ├── User.java
  26. │   │   │               │   └── Order.java
  27. │   │   │               ├── dto/
  28. │   │   │               │   ├── UserDto.java
  29. │   │   │               │   └── OrderDto.java
  30. │   │   │               ├── exception/
  31. │   │   │               │   ├── ResourceNotFoundException.java
  32. │   │   │               │   └── GlobalExceptionHandler.java
  33. │   │   │               └── util/
  34. │   │   │                   └── DateUtils.java
  35. │   │   └── resources/
  36. │   │       ├── application.properties
  37. │   │       ├── application-dev.properties
  38. │   │       ├── application-prod.properties
  39. │   │       └── static/
  40. │   │       └── templates/
  41. │   └── test/
  42. │       └── java/
  43. │           └── com/
  44. │               └── example/
  45. │                   └── application/
  46. │                       ├── service/
  47. │                       │   ├── UserServiceTest.java
  48. │                       │   └── OrderServiceTest.java
  49. │                       └── controller/
  50. │                           ├── UserControllerTest.java
  51. │                           └── OrderControllerTest.java
  52. ├── .gitignore
  53. ├── pom.xml
  54. └── README.md
复制代码

2. 配置管理

AntiX框架支持多种配置方式,推荐使用外部化配置,便于不同环境的部署和管理。
  1. # application.properties - 基础配置
  2. # 应用配置
  3. app.name=AntiX Application
  4. app.version=1.0.0
  5. # 服务器配置
  6. server.port=8080
  7. server.servlet.context-path=/api
  8. # 数据库配置
  9. spring.datasource.url=jdbc:mysql://localhost:3306/antix_db
  10. spring.datasource.username=root
  11. spring.datasource.password=password
  12. spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
  13. # JPA配置
  14. spring.jpa.hibernate.ddl-auto=update
  15. spring.jpa.show-sql=true
  16. spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
  17. spring.jpa.properties.hibernate.format_sql=true
  18. # 日志配置
  19. logging.level.root=INFO
  20. logging.level.com.example.application=DEBUG
  21. logging.file.name=logs/antix-application.log
  22. # 环境特定配置
  23. spring.profiles.active=dev
复制代码
  1. # application-dev.properties - 开发环境配置
  2. # 数据库配置
  3. spring.datasource.url=jdbc:mysql://localhost:3306/antix_db_dev
  4. spring.datasource.username=dev_user
  5. spring.datasource.password=dev_password
  6. # 日志配置
  7. logging.level.root=DEBUG
  8. logging.level.com.example.application=TRACE
  9. # 开发工具配置
  10. spring.devtools.restart.enabled=true
  11. spring.devtools.livereload.enabled=true
复制代码
  1. # application-prod.properties - 生产环境配置
  2. # 数据库配置
  3. spring.datasource.url=jdbc:mysql://prod-db-host:3306/antix_db_prod
  4. spring.datasource.username=prod_user
  5. spring.datasource.password=${DB_PASSWORD:}
  6. # 日志配置
  7. logging.level.root=WARN
  8. logging.level.com.example.application=INFO
  9. logging.file.name=/var/log/antix/antix-application.log
  10. # 性能配置
  11. server.tomcat.max-threads=200
  12. server.tomcat.min-spare-threads=20
复制代码

3. 异常处理

统一的异常处理可以提高应用的健壮性和用户体验。
  1. // 自定义异常类
  2. public class ResourceNotFoundException extends RuntimeException {
  3.     public ResourceNotFoundException(String message) {
  4.         super(message);
  5.     }
  6.    
  7.     public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) {
  8.         super(String.format("%s not found with %s: '%s'", resourceName, fieldName, fieldValue));
  9.     }
  10. }
  11. // 全局异常处理器
  12. @ControllerAdvice
  13. public class GlobalExceptionHandler {
  14.    
  15.     private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
  16.    
  17.     // 处理资源未找到异常
  18.     @ExceptionHandler(ResourceNotFoundException.class)
  19.     public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
  20.         ErrorResponse errorResponse = new ErrorResponse(
  21.                 HttpStatus.NOT_FOUND.value(),
  22.                 ex.getMessage(),
  23.                 System.currentTimeMillis()
  24.         );
  25.         
  26.         logger.error("Resource not found: {}", ex.getMessage());
  27.         return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
  28.     }
  29.    
  30.     // 处理验证异常
  31.     @ExceptionHandler(MethodArgumentNotValidException.class)
  32.     public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
  33.         List<String> errors = ex.getBindingResult()
  34.                 .getFieldErrors()
  35.                 .stream()
  36.                 .map(error -> error.getField() + ": " + error.getDefaultMessage())
  37.                 .collect(Collectors.toList());
  38.         
  39.         ErrorResponse errorResponse = new ErrorResponse(
  40.                 HttpStatus.BAD_REQUEST.value(),
  41.                 "Validation failed",
  42.                 errors,
  43.                 System.currentTimeMillis()
  44.         );
  45.         
  46.         logger.error("Validation error: {}", errors);
  47.         return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
  48.     }
  49.    
  50.     // 处理所有其他异常
  51.     @ExceptionHandler(Exception.class)
  52.     public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) {
  53.         ErrorResponse errorResponse = new ErrorResponse(
  54.                 HttpStatus.INTERNAL_SERVER_ERROR.value(),
  55.                 "An unexpected error occurred",
  56.                 System.currentTimeMillis()
  57.         );
  58.         
  59.         logger.error("Unexpected error: {}", ex.getMessage(), ex);
  60.         return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
  61.     }
  62. }
  63. // 错误响应DTO
  64. public class ErrorResponse {
  65.     private int status;
  66.     private String message;
  67.     private List<String> errors;
  68.     private long timestamp;
  69.    
  70.     // 构造函数、getters和setters
  71. }
复制代码

4. 测试策略

全面的测试是确保应用质量的关键。AntiX框架支持多种测试类型,包括单元测试、集成测试和端到端测试。
  1. // 单元测试示例
  2. @RunWith(MockitoJUnitRunner.class)
  3. public class UserServiceTest {
  4.    
  5.     @Mock
  6.     private UserRepository userRepository;
  7.    
  8.     @Mock
  9.     private UserMapper userMapper;
  10.    
  11.     @InjectMocks
  12.     private UserServiceImpl userService;
  13.    
  14.     @Test
  15.     public void testGetUserById() {
  16.         // 准备测试数据
  17.         User user = new User();
  18.         user.setId(1L);
  19.         user.setUsername("testuser");
  20.         user.setEmail("test@example.com");
  21.         
  22.         UserDto userDto = new UserDto();
  23.         userDto.setId(1L);
  24.         userDto.setUsername("testuser");
  25.         userDto.setEmail("test@example.com");
  26.         
  27.         // 模拟依赖行为
  28.         when(userRepository.findById(1L)).thenReturn(Optional.of(user));
  29.         when(userMapper.toDto(user)).thenReturn(userDto);
  30.         
  31.         // 调用测试方法
  32.         UserDto result = userService.getUserById(1L);
  33.         
  34.         // 验证结果
  35.         assertNotNull(result);
  36.         assertEquals(1L, result.getId().longValue());
  37.         assertEquals("testuser", result.getUsername());
  38.         assertEquals("test@example.com", result.getEmail());
  39.         
  40.         // 验证依赖调用
  41.         verify(userRepository).findById(1L);
  42.         verify(userMapper).toDto(user);
  43.     }
  44.    
  45.     @Test(expected = ResourceNotFoundException.class)
  46.     public void testGetUserByIdNotFound() {
  47.         // 模拟依赖行为
  48.         when(userRepository.findById(1L)).thenReturn(Optional.empty());
  49.         
  50.         // 调用测试方法,预期抛出异常
  51.         userService.getUserById(1L);
  52.         
  53.         // 验证依赖调用
  54.         verify(userRepository).findById(1L);
  55.         verify(userMapper, never()).toDto(any());
  56.     }
  57. }
  58. // 集成测试示例
  59. @RunWith(SpringRunner.class)
  60. @SpringBootTest
  61. @AutoConfigureMockMvc
  62. @Transactional
  63. public class UserControllerIntegrationTest {
  64.    
  65.     @Autowired
  66.     private MockMvc mockMvc;
  67.    
  68.     @Autowired
  69.     private UserRepository userRepository;
  70.    
  71.     @Test
  72.     public void testGetUserById() throws Exception {
  73.         // 准备测试数据
  74.         User user = new User();
  75.         user.setUsername("testuser");
  76.         user.setEmail("test@example.com");
  77.         user.setPassword("password");
  78.         user = userRepository.save(user);
  79.         
  80.         // 执行测试请求
  81.         mockMvc.perform(get("/api/users/{id}", user.getId()))
  82.                 .andExpect(status().isOk())
  83.                 .andExpect(jsonPath("$.id").value(user.getId()))
  84.                 .andExpect(jsonPath("$.username").value("testuser"))
  85.                 .andExpect(jsonPath("$.email").value("test@example.com"));
  86.     }
  87.    
  88.     @Test
  89.     public void testCreateUser() throws Exception {
  90.         // 准备测试数据
  91.         String userJson = "{"username":"newuser","email":"newuser@example.com","password":"password"}";
  92.         
  93.         // 执行测试请求
  94.         mockMvc.perform(post("/api/users")
  95.                 .contentType(MediaType.APPLICATION_JSON)
  96.                 .content(userJson))
  97.                 .andExpect(status().isCreated())
  98.                 .andExpect(jsonPath("$.username").value("newuser"))
  99.                 .andExpect(jsonPath("$.email").value("newuser@example.com"));
  100.         
  101.         // 验证数据库中的数据
  102.         User savedUser = userRepository.findByUsername("newuser");
  103.         assertNotNull(savedUser);
  104.         assertEquals("newuser@example.com", savedUser.getEmail());
  105.     }
  106. }
复制代码

5. 性能优化

性能优化是构建高效企业级应用的关键。以下是AntiX框架中的一些性能优化策略:
  1. // 使用缓存优化查询性能
  2. @Service
  3. public class ProductServiceImpl implements ProductService {
  4.    
  5.     private final ProductRepository productRepository;
  6.    
  7.     @Autowired
  8.     public ProductServiceImpl(ProductRepository productRepository) {
  9.         this.productRepository = productRepository;
  10.     }
  11.    
  12.     @Override
  13.     @Cacheable(value = "products", key = "#id")
  14.     public Product getProductById(Long id) {
  15.         return productRepository.findById(id).orElse(null);
  16.     }
  17.    
  18.     @Override
  19.     @Cacheable(value = "products", key = "'category:' + #category")
  20.     public List<Product> getProductsByCategory(String category) {
  21.         return productRepository.findByCategory(category);
  22.     }
  23.    
  24.     @Override
  25.     @Caching(
  26.         put = @CachePut(value = "products", key = "#product.id"),
  27.         evict = @CacheEvict(value = "products", key = "'category:' + #product.category")
  28.     )
  29.     public Product updateProduct(Product product) {
  30.         return productRepository.save(product);
  31.     }
  32. }
  33. // 使用异步处理提高吞吐量
  34. @Service
  35. public class NotificationServiceImpl implements NotificationService {
  36.    
  37.     private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
  38.    
  39.     @Override
  40.     @Async
  41.     public void sendEmail(String to, String subject, String body) {
  42.         // 模拟发送邮件的耗时操作
  43.         try {
  44.             Thread.sleep(1000);
  45.             logger.info("Email sent to {} with subject: {}", to, subject);
  46.         } catch (InterruptedException e) {
  47.             Thread.currentThread().interrupt();
  48.         }
  49.     }
  50.    
  51.     @Override
  52.     @Async("taskExecutor")
  53.     public Future<String> sendSms(String phoneNumber, String message) {
  54.         // 模拟发送短信的耗时操作
  55.         try {
  56.             Thread.sleep(500);
  57.             String result = "SMS sent to " + phoneNumber;
  58.             logger.info(result);
  59.             return new AsyncResult<>(result);
  60.         } catch (InterruptedException e) {
  61.             Thread.currentThread().interrupt();
  62.             return new AsyncResult<>("Failed to send SMS due to interruption");
  63.         }
  64.     }
  65. }
  66. // 配置异步任务执行器
  67. @Configuration
  68. @EnableAsync
  69. public class AsyncConfig implements AsyncConfigurer {
  70.    
  71.     @Override
  72.     public Executor getAsyncExecutor() {
  73.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  74.         executor.setCorePoolSize(5);
  75.         executor.setMaxPoolSize(10);
  76.         executor.setQueueCapacity(25);
  77.         executor.setThreadNamePrefix("AntiX-Async-");
  78.         executor.initialize();
  79.         return executor;
  80.     }
  81.    
  82.     @Bean(name = "taskExecutor")
  83.     public Executor taskExecutor() {
  84.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  85.         executor.setCorePoolSize(10);
  86.         executor.setMaxPoolSize(20);
  87.         executor.setQueueCapacity(50);
  88.         executor.setThreadNamePrefix("AntiX-Task-");
  89.         executor.initialize();
  90.         return executor;
  91.     }
  92. }
复制代码

真实项目案例分析

案例1:电子商务平台

某大型零售企业需要构建一个高性能、高可用的电子商务平台,支持每日百万级别的用户访问和交易处理。平台需要包括商品管理、订单处理、用户管理、支付集成等核心功能。

1. 高并发处理:特别是在促销活动期间,系统需要处理大量并发请求
2. 数据一致性:确保订单、库存和支付数据的一致性
3. 系统扩展性:随着业务增长,系统需要能够水平扩展
4. 用户体验:确保页面加载速度和交易流程的流畅性
  1. // 商品服务
  2. @SpringBootApplication
  3. @EnableDiscoveryClient
  4. @EnableCaching
  5. public class ProductServiceApplication {
  6.     public static void main(String[] args) {
  7.         SpringApplication.run(ProductServiceApplication.class, args);
  8.     }
  9. }
  10. // 订单服务
  11. @SpringBootApplication
  12. @EnableDiscoveryClient
  13. @EnableCaching
  14. public class OrderServiceApplication {
  15.     public static void main(String[] args) {
  16.         SpringApplication.run(OrderServiceApplication.class, args);
  17.     }
  18. }
  19. // 用户服务
  20. @SpringBootApplication
  21. @EnableDiscoveryClient
  22. @EnableCaching
  23. public class UserServiceApplication {
  24.     public static void main(String[] args) {
  25.         SpringApplication.run(UserServiceApplication.class, args);
  26.     }
  27. }
复制代码
  1. // 使用分布式锁处理高并发场景
  2. @Service
  3. public class InventoryServiceImpl implements InventoryService {
  4.    
  5.     private final InventoryRepository inventoryRepository;
  6.     private final RedisTemplate<String, String> redisTemplate;
  7.    
  8.     @Autowired
  9.     public InventoryServiceImpl(InventoryRepository inventoryRepository, RedisTemplate<String, String> redisTemplate) {
  10.         this.inventoryRepository = inventoryRepository;
  11.         this.redisTemplate = redisTemplate;
  12.     }
  13.    
  14.     @Override
  15.     @Transactional
  16.     public boolean reduceInventory(Long productId, int quantity) {
  17.         String lockKey = "inventory_lock:" + productId;
  18.         String requestId = UUID.randomUUID().toString();
  19.         
  20.         try {
  21.             // 获取分布式锁
  22.             boolean locked = acquireLock(lockKey, requestId, 10);
  23.             if (!locked) {
  24.                 throw new BusinessException("Failed to acquire lock for product: " + productId);
  25.             }
  26.             
  27.             // 检查库存
  28.             Inventory inventory = inventoryRepository.findByProductId(productId);
  29.             if (inventory == null || inventory.getQuantity() < quantity) {
  30.                 return false;
  31.             }
  32.             
  33.             // 减少库存
  34.             inventory.setQuantity(inventory.getQuantity() - quantity);
  35.             inventoryRepository.save(inventory);
  36.             
  37.             return true;
  38.         } finally {
  39.             // 释放锁
  40.             releaseLock(lockKey, requestId);
  41.         }
  42.     }
  43.    
  44.     private boolean acquireLock(String lockKey, String requestId, int expireTime) {
  45.         return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS));
  46.     }
  47.    
  48.     private boolean releaseLock(String lockKey, String requestId) {
  49.         String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
  50.         DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
  51.         Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId);
  52.         return result != null && result == 1;
  53.     }
  54. }
复制代码
  1. // 订单创建事件
  2. public class OrderCreatedEvent {
  3.     private final Order order;
  4.     private final LocalDateTime createdAt;
  5.    
  6.     public OrderCreatedEvent(Order order) {
  7.         this.order = order;
  8.         this.createdAt = LocalDateTime.now();
  9.     }
  10.    
  11.     // getters
  12. }
  13. // 订单服务发布事件
  14. @Service
  15. public class OrderServiceImpl implements OrderService {
  16.    
  17.     private final OrderRepository orderRepository;
  18.     private final ApplicationEventPublisher eventPublisher;
  19.    
  20.     @Autowired
  21.     public OrderServiceImpl(OrderRepository orderRepository, ApplicationEventPublisher eventPublisher) {
  22.         this.orderRepository = orderRepository;
  23.         this.eventPublisher = eventPublisher;
  24.     }
  25.    
  26.     @Override
  27.     @Transactional
  28.     public Order createOrder(Order order) {
  29.         // 保存订单
  30.         order = orderRepository.save(order);
  31.         
  32.         // 发布订单创建事件
  33.         eventPublisher.publishEvent(new OrderCreatedEvent(order));
  34.         
  35.         return order;
  36.     }
  37. }
  38. // 库存服务监听事件
  39. @Service
  40. public class InventoryEventListener {
  41.    
  42.     private final InventoryService inventoryService;
  43.    
  44.     @Autowired
  45.     public InventoryEventListener(InventoryService inventoryService) {
  46.         this.inventoryService = inventoryService;
  47.     }
  48.    
  49.     @EventListener
  50.     @Async
  51.     public void handleOrderCreatedEvent(OrderCreatedEvent event) {
  52.         Order order = event.getOrder();
  53.         
  54.         // 减少库存
  55.         for (OrderItem item : order.getItems()) {
  56.             boolean success = inventoryService.reduceInventory(item.getProductId(), item.getQuantity());
  57.             if (!success) {
  58.                 // 库存不足,处理回滚逻辑
  59.                 throw new InsufficientInventoryException("Insufficient inventory for product: " + item.getProductId());
  60.             }
  61.         }
  62.     }
  63. }
  64. // 支付服务监听事件
  65. @Service
  66. public class PaymentEventListener {
  67.    
  68.     private final PaymentService paymentService;
  69.    
  70.     @Autowired
  71.     public PaymentEventListener(PaymentService paymentService) {
  72.         this.paymentService = paymentService;
  73.     }
  74.    
  75.     @EventListener
  76.     @Async
  77.     public void handleOrderCreatedEvent(OrderCreatedEvent event) {
  78.         Order order = event.getOrder();
  79.         
  80.         // 处理支付
  81.         PaymentResult result = paymentService.processPayment(order);
  82.         if (!result.isSuccess()) {
  83.             // 支付失败,处理回滚逻辑
  84.             throw new PaymentFailedException("Payment failed for order: " + order.getId());
  85.         }
  86.     }
  87. }
复制代码
  1. // 商品缓存配置
  2. @Configuration
  3. @EnableCaching
  4. public class CacheConfig {
  5.    
  6.     @Bean
  7.     public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
  8.         RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
  9.                 .entryTtl(Duration.ofMinutes(30))
  10.                 .disableCachingNullValues()
  11.                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  12.         
  13.         // 商品缓存配置
  14.         RedisCacheConfiguration productCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
  15.                 .entryTtl(Duration.ofHours(1))
  16.                 .disableCachingNullValues()
  17.                 .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
  18.         
  19.         Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
  20.         cacheConfigurations.put("products", productCacheConfig);
  21.         
  22.         return RedisCacheManager.builder(redisConnectionFactory)
  23.                 .cacheDefaults(defaultConfig)
  24.                 .withInitialCacheConfigurations(cacheConfigurations)
  25.                 .build();
  26.     }
  27. }
  28. // 商品服务实现
  29. @Service
  30. public class ProductServiceImpl implements ProductService {
  31.    
  32.     private final ProductRepository productRepository;
  33.    
  34.     @Autowired
  35.     public ProductServiceImpl(ProductRepository productRepository) {
  36.         this.productRepository = productRepository;
  37.     }
  38.    
  39.     @Override
  40.     @Cacheable(value = "products", key = "#id")
  41.     public Product getProductById(Long id) {
  42.         return productRepository.findById(id).orElse(null);
  43.     }
  44.    
  45.     @Override
  46.     @Cacheable(value = "products", key = "'category:' + #category + ':page:' + #page + ':size:' + #size")
  47.     public Page<Product> getProductsByCategory(String category, int page, int size) {
  48.         Pageable pageable = PageRequest.of(page, size, Sort.by("name").ascending());
  49.         return productRepository.findByCategory(category, pageable);
  50.     }
  51.    
  52.     @Override
  53.     @Caching(
  54.         put = @CachePut(value = "products", key = "#product.id"),
  55.         evict = {
  56.             @CacheEvict(value = "products", key = "'category:' + #product.category + ':page:*'"),
  57.             @CacheEvict(value = "products", key = "'featured'")
  58.         }
  59.     )
  60.     public Product updateProduct(Product product) {
  61.         return productRepository.save(product);
  62.     }
  63.    
  64.     @Override
  65.     @CacheEvict(value = "products", allEntries = true)
  66.     public void refreshProductCache() {
  67.         // 清除所有产品缓存
  68.     }
  69. }
复制代码

通过使用AntiX框架,该电子商务平台成功实现了以下目标:

1. 高并发处理能力:系统能够平稳处理每秒5000+的请求峰值,促销活动期间无宕机情况
2. 数据一致性:通过分布式事务和事件驱动架构,确保了订单、库存和支付数据的一致性
3. 系统扩展性:采用微服务架构,各服务可独立扩展,系统整体吞吐量提升了3倍
4. 用户体验提升:页面加载时间从平均3秒减少到800毫秒,用户转化率提高了25%

案例2:金融风控系统

一家大型金融机构需要构建一个实时风控系统,用于检测和预防金融交易中的欺诈行为。系统需要能够实时分析大量交易数据,识别可疑模式,并采取相应措施。

1. 实时数据处理:需要在毫秒级别处理大量交易数据
2. 复杂规则引擎:需要实现灵活且高效的风控规则
3. 高可用性:系统需要7x24小时不间断运行
4. 数据安全:确保敏感金融数据的安全性和合规性
  1. // 交易事件处理器
  2. @Service
  3. public class TransactionEventHandler {
  4.    
  5.     private final RiskRuleEngine ruleEngine;
  6.     private final AlertService alertService;
  7.     private final TransactionRepository transactionRepository;
  8.    
  9.     @Autowired
  10.     public TransactionEventHandler(RiskRuleEngine ruleEngine, AlertService alertService,
  11.                                  TransactionRepository transactionRepository) {
  12.         this.ruleEngine = ruleEngine;
  13.         this.alertService = alertService;
  14.         this.transactionRepository = transactionRepository;
  15.     }
  16.    
  17.     @EventListener
  18.     @Async("transactionProcessor")
  19.     public void handleTransactionEvent(TransactionEvent event) {
  20.         Transaction transaction = event.getTransaction();
  21.         
  22.         // 保存交易记录
  23.         transactionRepository.save(transaction);
  24.         
  25.         // 执行风控规则
  26.         RiskAssessmentResult result = ruleEngine.assessRisk(transaction);
  27.         
  28.         // 根据风险等级采取相应措施
  29.         if (result.getRiskLevel() == RiskLevel.HIGH) {
  30.             // 高风险交易,阻止并生成警报
  31.             blockTransaction(transaction);
  32.             alertService.createHighRiskAlert(transaction, result);
  33.         } else if (result.getRiskLevel() == RiskLevel.MEDIUM) {
  34.             // 中等风险交易,需要人工审核
  35.             alertService.createMediumRiskAlert(transaction, result);
  36.         }
  37.         
  38.         // 更新交易状态
  39.         updateTransactionStatus(transaction, result);
  40.     }
  41.    
  42.     private void blockTransaction(Transaction transaction) {
  43.         // 阻止交易的逻辑
  44.         transaction.setStatus(TransactionStatus.BLOCKED);
  45.         transactionRepository.save(transaction);
  46.     }
  47.    
  48.     private void updateTransactionStatus(Transaction transaction, RiskAssessmentResult result) {
  49.         // 更新交易状态的逻辑
  50.         if (transaction.getStatus() != TransactionStatus.BLOCKED) {
  51.             transaction.setStatus(TransactionStatus.COMPLETED);
  52.             transaction.setRiskScore(result.getScore());
  53.             transactionRepository.save(transaction);
  54.         }
  55.     }
  56. }
  57. // 配置异步任务处理器
  58. @Configuration
  59. @EnableAsync
  60. public class AsyncConfig {
  61.    
  62.     @Bean(name = "transactionProcessor")
  63.     public Executor transactionProcessor() {
  64.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  65.         executor.setCorePoolSize(10);
  66.         executor.setMaxPoolSize(50);
  67.         executor.setQueueCapacity(1000);
  68.         executor.setThreadNamePrefix("TransactionProcessor-");
  69.         executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
  70.         executor.initialize();
  71.         return executor;
  72.     }
  73. }
复制代码
  1. // 风控规则接口
  2. public interface RiskRule {
  3.     String getName();
  4.     RiskAssessmentResult evaluate(Transaction transaction);
  5. }
  6. // 规则引擎实现
  7. @Service
  8. public class RiskRuleEngineImpl implements RiskRuleEngine {
  9.    
  10.     private final List<RiskRule> rules;
  11.    
  12.     @Autowired
  13.     public RiskRuleEngineImpl(List<RiskRule> rules) {
  14.         this.rules = rules;
  15.     }
  16.    
  17.     @Override
  18.     public RiskAssessmentResult assessRisk(Transaction transaction) {
  19.         int totalScore = 0;
  20.         List<String> triggeredRules = new ArrayList<>();
  21.         
  22.         // 执行所有规则
  23.         for (RiskRule rule : rules) {
  24.             RiskAssessmentResult result = rule.evaluate(transaction);
  25.             if (result.getScore() > 0) {
  26.                 totalScore += result.getScore();
  27.                 triggeredRules.add(rule.getName());
  28.             }
  29.         }
  30.         
  31.         // 确定风险等级
  32.         RiskLevel riskLevel = determineRiskLevel(totalScore);
  33.         
  34.         return new RiskAssessmentResult(totalScore, riskLevel, triggeredRules);
  35.     }
  36.    
  37.     private RiskLevel determineRiskLevel(int score) {
  38.         if (score >= 80) {
  39.             return RiskLevel.HIGH;
  40.         } else if (score >= 50) {
  41.             return RiskLevel.MEDIUM;
  42.         } else {
  43.             return RiskLevel.LOW;
  44.         }
  45.     }
  46. }
  47. // 示例规则:大额交易检测
  48. @Component
  49. public class LargeAmountRule implements RiskRule {
  50.    
  51.     private static final int THRESHOLD = 10000; // 10,000元
  52.     private static final int SCORE = 30;
  53.    
  54.     @Override
  55.     public String getName() {
  56.         return "LargeAmountRule";
  57.     }
  58.    
  59.     @Override
  60.     public RiskAssessmentResult evaluate(Transaction transaction) {
  61.         if (transaction.getAmount().compareTo(BigDecimal.valueOf(THRESHOLD)) > 0) {
  62.             return new RiskAssessmentResult(SCORE, RiskLevel.MEDIUM, Collections.singletonList(getName()));
  63.         }
  64.         return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
  65.     }
  66. }
  67. // 示例规则:异常地点检测
  68. @Component
  69. public class UnusualLocationRule implements RiskRule {
  70.    
  71.     private final UserLocationHistoryRepository locationHistoryRepository;
  72.    
  73.     @Autowired
  74.     public UnusualLocationRule(UserLocationHistoryRepository locationHistoryRepository) {
  75.         this.locationHistoryRepository = locationHistoryRepository;
  76.     }
  77.    
  78.     @Override
  79.     public String getName() {
  80.         return "UnusualLocationRule";
  81.     }
  82.    
  83.     @Override
  84.     public RiskAssessmentResult evaluate(Transaction transaction) {
  85.         // 获取用户历史交易地点
  86.         List<String> usualLocations = locationHistoryRepository.findFrequentLocations(transaction.getUserId());
  87.         
  88.         // 检查当前交易地点是否在常见地点中
  89.         if (!usualLocations.contains(transaction.getLocation())) {
  90.             return new RiskAssessmentResult(40, RiskLevel.MEDIUM, Collections.singletonList(getName()));
  91.         }
  92.         return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
  93.     }
  94. }
  95. // 示例规则:高频交易检测
  96. @Component
  97. public class HighFrequencyRule implements RiskRule {
  98.    
  99.     private final TransactionRepository transactionRepository;
  100.    
  101.     @Autowired
  102.     public HighFrequencyRule(TransactionRepository transactionRepository) {
  103.         this.transactionRepository = transactionRepository;
  104.     }
  105.    
  106.     @Override
  107.     public String getName() {
  108.         return "HighFrequencyRule";
  109.     }
  110.    
  111.     @Override
  112.     public RiskAssessmentResult evaluate(Transaction transaction) {
  113.         // 检查过去1小时内的交易次数
  114.         LocalDateTime oneHourAgo = LocalDateTime.now().minusHours(1);
  115.         int transactionCount = transactionRepository.countByUserIdAndTimeAfter(
  116.             transaction.getUserId(), oneHourAgo);
  117.         
  118.         // 如果过去1小时内交易超过5次,认为是高频交易
  119.         if (transactionCount > 5) {
  120.             return new RiskAssessmentResult(50, RiskLevel.HIGH, Collections.singletonList(getName()));
  121.         }
  122.         return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
  123.     }
  124. }
复制代码
  1. // 健康检查端点
  2. @RestController
  3. @RequestMapping("/api/health")
  4. public class HealthCheckController {
  5.    
  6.     private final DatabaseHealthIndicator databaseHealthIndicator;
  7.     private final RedisHealthIndicator redisHealthIndicator;
  8.     private final KafkaHealthIndicator kafkaHealthIndicator;
  9.    
  10.     @Autowired
  11.     public HealthCheckController(DatabaseHealthIndicator databaseHealthIndicator,
  12.                                RedisHealthIndicator redisHealthIndicator,
  13.                                KafkaHealthIndicator kafkaHealthIndicator) {
  14.         this.databaseHealthIndicator = databaseHealthIndicator;
  15.         this.redisHealthIndicator = redisHealthIndicator;
  16.         this.kafkaHealthIndicator = kafkaHealthIndicator;
  17.     }
  18.    
  19.     @GetMapping
  20.     public ResponseEntity<Map<String, Object>> health() {
  21.         Map<String, Object> healthStatus = new HashMap<>();
  22.         
  23.         // 检查数据库状态
  24.         Health dbHealth = databaseHealthIndicator.health();
  25.         healthStatus.put("database", dbHealth.getStatus());
  26.         
  27.         // 检查Redis状态
  28.         Health redisHealth = redisHealthIndicator.health();
  29.         healthStatus.put("redis", redisHealth.getStatus());
  30.         
  31.         // 检查Kafka状态
  32.         Health kafkaHealth = kafkaHealthIndicator.health();
  33.         healthStatus.put("kafka", kafkaHealth.getStatus());
  34.         
  35.         // 确定整体状态
  36.         Status overallStatus = Status.UP;
  37.         for (Object status : healthStatus.values()) {
  38.             if (status != Status.UP) {
  39.                 overallStatus = Status.DOWN;
  40.                 break;
  41.             }
  42.         }
  43.         
  44.         healthStatus.put("status", overallStatus);
  45.         healthStatus.put("timestamp", System.currentTimeMillis());
  46.         
  47.         HttpStatus httpStatus = overallStatus == Status.UP ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE;
  48.         return ResponseEntity.status(httpStatus).body(healthStatus);
  49.     }
  50. }
  51. // 数据库健康指示器
  52. @Component
  53. public class DatabaseHealthIndicator implements HealthIndicator {
  54.    
  55.     private final DataSource dataSource;
  56.    
  57.     @Autowired
  58.     public DatabaseHealthIndicator(DataSource dataSource) {
  59.         this.dataSource = dataSource;
  60.     }
  61.    
  62.     @Override
  63.     public Health health() {
  64.         try (Connection connection = dataSource.getConnection()) {
  65.             if (connection.isValid(1)) {
  66.                 return Health.up().withDetail("database", "Available").build();
  67.             } else {
  68.                 return Health.down().withDetail("database", "Connection is not valid").build();
  69.             }
  70.         } catch (SQLException e) {
  71.             return Health.down().withException(e).build();
  72.         }
  73.     }
  74. }
  75. // Redis健康指示器
  76. @Component
  77. public class RedisHealthIndicator implements HealthIndicator {
  78.    
  79.     private final RedisConnectionFactory redisConnectionFactory;
  80.    
  81.     @Autowired
  82.     public RedisHealthIndicator(RedisConnectionFactory redisConnectionFactory) {
  83.         this.redisConnectionFactory = redisConnectionFactory;
  84.     }
  85.    
  86.     @Override
  87.     public Health health() {
  88.         try {
  89.             RedisConnection connection = redisConnectionFactory.getConnection();
  90.             String info = connection.info();
  91.             connection.close();
  92.             
  93.             return Health.up().withDetail("redis", "Available").build();
  94.         } catch (Exception e) {
  95.             return Health.down().withException(e).build();
  96.         }
  97.     }
  98. }
  99. // 断路器模式实现
  100. @Service
  101. public class ExternalRiskServiceProxy {
  102.    
  103.     private final ExternalRiskService externalRiskService;
  104.     private final CircuitBreaker circuitBreaker;
  105.    
  106.     @Autowired
  107.     public ExternalRiskServiceProxy(ExternalRiskService externalRiskService) {
  108.         this.externalRiskService = externalRiskService;
  109.         
  110.         // 配置断路器
  111.         CircuitBreakerConfig config = CircuitBreakerConfig.custom()
  112.                 .failureRateThreshold(50)
  113.                 .waitDurationInOpenState(Duration.ofSeconds(30))
  114.                 .ringBufferSizeInHalfOpenState(10)
  115.                 .ringBufferSizeInClosedState(100)
  116.                 .build();
  117.         
  118.         this.circuitBreaker = CircuitBreaker.of("externalRiskService", config);
  119.     }
  120.    
  121.     public RiskData getExternalRiskData(String userId) {
  122.         return circuitBreaker.executeSupplier(() -> externalRiskService.getRiskData(userId));
  123.     }
  124. }
复制代码
  1. // 数据加密服务
  2. @Service
  3. public class EncryptionServiceImpl implements EncryptionService {
  4.    
  5.     private final String encryptionKey;
  6.    
  7.     @Autowired
  8.     public EncryptionServiceImpl(@Value("${app.encryption.key}") String encryptionKey) {
  9.         this.encryptionKey = encryptionKey;
  10.     }
  11.    
  12.     @Override
  13.     public String encrypt(String data) {
  14.         try {
  15.             Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
  16.             SecretKeySpec keySpec = new SecretKeySpec(encryptionKey.getBytes(), "AES");
  17.             GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, new byte[12]);
  18.             
  19.             cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
  20.             byte[] encryptedData = cipher.doFinal(data.getBytes());
  21.             
  22.             return Base64.getEncoder().encodeToString(encryptedData);
  23.         } catch (Exception e) {
  24.             throw new EncryptionException("Failed to encrypt data", e);
  25.         }
  26.     }
  27.    
  28.     @Override
  29.     public String decrypt(String encryptedData) {
  30.         try {
  31.             Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
  32.             SecretKeySpec keySpec = new SecretKeySpec(encryptionKey.getBytes(), "AES");
  33.             GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, new byte[12]);
  34.             
  35.             cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
  36.             byte[] decodedData = Base64.getDecoder().decode(encryptedData);
  37.             byte[] decryptedData = cipher.doFinal(decodedData);
  38.             
  39.             return new String(decryptedData);
  40.         } catch (Exception e) {
  41.             throw new EncryptionException("Failed to decrypt data", e);
  42.         }
  43.     }
  44. }
  45. // 敏感数据处理器
  46. @Aspect
  47. @Component
  48. public class SensitiveDataAspect {
  49.    
  50.     private final EncryptionService encryptionService;
  51.    
  52.     @Autowired
  53.     public SensitiveDataAspect(EncryptionService encryptionService) {
  54.         this.encryptionService = encryptionService;
  55.     }
  56.    
  57.     @Around("@annotation(SensitiveData)")
  58.     public Object handleSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
  59.         Object result = joinPoint.proceed();
  60.         
  61.         // 处理返回结果中的敏感数据
  62.         if (result instanceof Transaction) {
  63.             Transaction transaction = (Transaction) result;
  64.             // 加密敏感字段
  65.             if (transaction.getCardNumber() != null) {
  66.                 transaction.setCardNumber(encryptionService.encrypt(transaction.getCardNumber()));
  67.             }
  68.             if (transaction.getAccountNumber() != null) {
  69.                 transaction.setAccountNumber(encryptionService.encrypt(transaction.getAccountNumber()));
  70.             }
  71.         }
  72.         
  73.         return result;
  74.     }
  75. }
  76. // 审计日志服务
  77. @Service
  78. public class AuditLogServiceImpl implements AuditLogService {
  79.    
  80.     private final AuditLogRepository auditLogRepository;
  81.    
  82.     @Autowired
  83.     public AuditLogServiceImpl(AuditLogRepository auditLogRepository) {
  84.         this.auditLogRepository = auditLogRepository;
  85.     }
  86.    
  87.     @Override
  88.     @Async
  89.     public void logAction(String userId, String action, String details) {
  90.         AuditLog auditLog = new AuditLog();
  91.         auditLog.setUserId(userId);
  92.         auditLog.setAction(action);
  93.         auditLog.setDetails(details);
  94.         auditLog.setTimestamp(LocalDateTime.now());
  95.         
  96.         auditLogRepository.save(auditLog);
  97.     }
  98.    
  99.     @Override
  100.     public Page<AuditLog> getAuditLogs(String userId, LocalDateTime startTime, LocalDateTime endTime,
  101.                                       Pageable pageable) {
  102.         if (startTime != null && endTime != null) {
  103.             return auditLogRepository.findByUserIdAndTimestampBetween(userId, startTime, endTime, pageable);
  104.         } else if (startTime != null) {
  105.             return auditLogRepository.findByUserIdAndTimestampAfter(userId, startTime, pageable);
  106.         } else if (endTime != null) {
  107.             return auditLogRepository.findByUserIdAndTimestampBefore(userId, endTime, pageable);
  108.         } else {
  109.             return auditLogRepository.findByUserId(userId, pageable);
  110.         }
  111.     }
  112. }
复制代码

通过使用AntiX框架,该金融风控系统成功实现了以下目标:

1. 实时处理能力:系统能够在100毫秒内完成交易风险评估,支持每秒10000+的交易处理量
2. 灵活的规则引擎:实现了可插拔的风控规则,新规则可在不重启系统的情况下动态加载
3. 高可用性:系统实现了99.99%的可用性,全年非计划停机时间不超过52分钟
4. 数据安全合规:所有敏感数据均加密存储,系统通过了金融行业的安全合规审计

构建稳定高效企业级应用的策略

1. 架构设计原则

AntiX框架支持领域驱动设计方法,帮助开发团队构建与业务领域紧密匹配的应用架构。
  1. // 值对象 - 金额
  2. public class Money {
  3.     private final BigDecimal amount;
  4.     private final Currency currency;
  5.    
  6.     public Money(BigDecimal amount, Currency currency) {
  7.         if (amount == null || currency == null) {
  8.             throw new IllegalArgumentException("Amount and currency cannot be null");
  9.         }
  10.         if (amount.compareTo(BigDecimal.ZERO) < 0) {
  11.             throw new IllegalArgumentException("Amount cannot be negative");
  12.         }
  13.         
  14.         this.amount = amount;
  15.         this.currency = currency;
  16.     }
  17.    
  18.     // 业务方法
  19.     public Money add(Money other) {
  20.         if (!this.currency.equals(other.currency)) {
  21.             throw new IllegalArgumentException("Cannot add money with different currencies");
  22.         }
  23.         return new Money(this.amount.add(other.amount), this.currency);
  24.     }
  25.    
  26.     public Money subtract(Money other) {
  27.         if (!this.currency.equals(other.currency)) {
  28.             throw new IllegalArgumentException("Cannot subtract money with different currencies");
  29.         }
  30.         BigDecimal newAmount = this.amount.subtract(other.amount);
  31.         if (newAmount.compareTo(BigDecimal.ZERO) < 0) {
  32.             throw new IllegalArgumentException("Insufficient funds");
  33.         }
  34.         return new Money(newAmount, this.currency);
  35.     }
  36.    
  37.     // getters
  38. }
  39. // 聚合根 - 订单
  40. @Entity
  41. @Table(name = "orders")
  42. public class Order {
  43.     @Id
  44.     @GeneratedValue(strategy = GenerationType.IDENTITY)
  45.     private Long id;
  46.    
  47.     @Embedded
  48.     private OrderId orderId;
  49.    
  50.     @Embedded
  51.     private CustomerId customerId;
  52.    
  53.     @ElementCollection
  54.     @CollectionTable(name = "order_items", joinColumns = @JoinColumn(name = "order_id"))
  55.     private List<OrderItem> items = new ArrayList<>();
  56.    
  57.     @Embedded
  58.     private Money totalAmount;
  59.    
  60.     @Enumerated(EnumType.STRING)
  61.     private OrderStatus status;
  62.    
  63.     @CreationTimestamp
  64.     private LocalDateTime createdAt;
  65.    
  66.     @UpdateTimestamp
  67.     private LocalDateTime updatedAt;
  68.    
  69.     // 业务方法
  70.     public void addItem(Product product, int quantity) {
  71.         if (status != OrderStatus.NEW) {
  72.             throw new IllegalStateException("Cannot add items to an order that is not in NEW status");
  73.         }
  74.         
  75.         OrderItem item = new OrderItem(product.getId(), product.getName(), product.getPrice(), quantity);
  76.         items.add(item);
  77.         recalculateTotal();
  78.     }
  79.    
  80.     public void removeItem(Long productId) {
  81.         if (status != OrderStatus.NEW) {
  82.             throw new IllegalStateException("Cannot remove items from an order that is not in NEW status");
  83.         }
  84.         
  85.         items.removeIf(item -> item.getProductId().equals(productId));
  86.         recalculateTotal();
  87.     }
  88.    
  89.     public void confirm() {
  90.         if (items.isEmpty()) {
  91.             throw new IllegalStateException("Cannot confirm an empty order");
  92.         }
  93.         this.status = OrderStatus.CONFIRMED;
  94.     }
  95.    
  96.     public void cancel() {
  97.         if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED) {
  98.             throw new IllegalStateException("Cannot cancel an order that has been shipped or delivered");
  99.         }
  100.         this.status = OrderStatus.CANCELLED;
  101.     }
  102.    
  103.     private void recalculateTotal() {
  104.         BigDecimal total = items.stream()
  105.                 .map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
  106.                 .reduce(BigDecimal.ZERO, BigDecimal::add);
  107.         
  108.         this.totalAmount = new Money(total, items.get(0).getUnitPrice().getCurrency());
  109.     }
  110.    
  111.     // getters
  112. }
  113. // 仓储接口
  114. public interface OrderRepository {
  115.     Order save(Order order);
  116.     Optional<Order> findById(OrderId orderId);
  117.     List<Order> findByCustomerId(CustomerId customerId);
  118. }
  119. // 仓储实现
  120. @Repository
  121. public class OrderRepositoryImpl implements OrderRepository {
  122.    
  123.     @PersistenceContext
  124.     private EntityManager entityManager;
  125.    
  126.     @Override
  127.     public Order save(Order order) {
  128.         if (order.getId() == null) {
  129.             entityManager.persist(order);
  130.             return order;
  131.         } else {
  132.             return entityManager.merge(order);
  133.         }
  134.     }
  135.    
  136.     @Override
  137.     public Optional<Order> findById(OrderId orderId) {
  138.         try {
  139.             Order order = entityManager.createQuery(
  140.                     "SELECT o FROM Order o WHERE o.orderId = :orderId", Order.class)
  141.                     .setParameter("orderId", orderId)
  142.                     .getSingleResult();
  143.             return Optional.of(order);
  144.         } catch (NoResultException e) {
  145.             return Optional.empty();
  146.         }
  147.     }
  148.    
  149.     @Override
  150.     public List<Order> findByCustomerId(CustomerId customerId) {
  151.         return entityManager.createQuery(
  152.                 "SELECT o FROM Order o WHERE o.customerId = :customerId", Order.class)
  153.                 .setParameter("customerId", customerId)
  154.                 .getResultList();
  155.     }
  156. }
  157. // 应用服务
  158. @Service
  159. @Transactional
  160. public class OrderApplicationService {
  161.    
  162.     private final OrderRepository orderRepository;
  163.     private final ProductRepository productRepository;
  164.     private final OrderEventPublisher eventPublisher;
  165.    
  166.     @Autowired
  167.     public OrderApplicationService(OrderRepository orderRepository,
  168.                                  ProductRepository productRepository,
  169.                                  OrderEventPublisher eventPublisher) {
  170.         this.orderRepository = orderRepository;
  171.         this.productRepository = productRepository;
  172.         this.eventPublisher = eventPublisher;
  173.     }
  174.    
  175.     public OrderId createOrder(CustomerId customerId) {
  176.         Order order = new Order(OrderId.generate(), customerId);
  177.         orderRepository.save(order);
  178.         
  179.         // 发布订单创建事件
  180.         eventPublisher.publishOrderCreatedEvent(order);
  181.         
  182.         return order.getOrderId();
  183.     }
  184.    
  185.     public void addProductToOrder(OrderId orderId, ProductId productId, int quantity) {
  186.         Order order = orderRepository.findById(orderId)
  187.                 .orElseThrow(() -> new OrderNotFoundException(orderId));
  188.         
  189.         Product product = productRepository.findById(productId)
  190.                 .orElseThrow(() -> new ProductNotFoundException(productId));
  191.         
  192.         order.addItem(product, quantity);
  193.         orderRepository.save(order);
  194.         
  195.         // 发布订单更新事件
  196.         eventPublisher.publishOrderUpdatedEvent(order);
  197.     }
  198.    
  199.     public void confirmOrder(OrderId orderId) {
  200.         Order order = orderRepository.findById(orderId)
  201.                 .orElseThrow(() -> new OrderNotFoundException(orderId));
  202.         
  203.         order.confirm();
  204.         orderRepository.save(order);
  205.         
  206.         // 发布订单确认事件
  207.         eventPublisher.publishOrderConfirmedEvent(order);
  208.     }
  209. }
复制代码

AntiX框架支持构建微服务架构,使应用能够模块化、可扩展且易于维护。
  1. // 用户服务API
  2. @FeignClient(name = "user-service", path = "/api/users")
  3. public interface UserServiceClient {
  4.    
  5.     @GetMapping("/{id}")
  6.     ResponseEntity<UserDto> getUserById(@PathVariable("id") Long id);
  7.    
  8.     @GetMapping("/search")
  9.     ResponseEntity<List<UserDto>> searchUsers(@RequestParam("query") String query);
  10.    
  11.     @PostMapping
  12.     ResponseEntity<UserDto> createUser(@RequestBody UserCreateDto userCreateDto);
  13.    
  14.     @PutMapping("/{id}")
  15.     ResponseEntity<UserDto> updateUser(@PathVariable("id") Long id, @RequestBody UserUpdateDto userUpdateDto);
  16.    
  17.     @DeleteMapping("/{id}")
  18.     ResponseEntity<Void> deleteUser(@PathVariable("id") Long id);
  19. }
  20. // 产品服务API
  21. @FeignClient(name = "product-service", path = "/api/products")
  22. public interface ProductServiceClient {
  23.    
  24.     @GetMapping("/{id}")
  25.     ResponseEntity<ProductDto> getProductById(@PathVariable("id") Long id);
  26.    
  27.     @GetMapping("/category/{category}")
  28.     ResponseEntity<List<ProductDto>> getProductsByCategory(@PathVariable("category") String category);
  29.    
  30.     @GetMapping("/search")
  31.     ResponseEntity<Page<ProductDto>> searchProducts(@RequestParam("query") String query,
  32.                                                    @RequestParam("page") int page,
  33.                                                    @RequestParam("size") int size);
  34.    
  35.     @PostMapping
  36.     ResponseEntity<ProductDto> createProduct(@RequestBody ProductCreateDto productCreateDto);
  37.    
  38.     @PutMapping("/{id}")
  39.     ResponseEntity<ProductDto> updateProduct(@PathVariable("id") Long id, @RequestBody ProductUpdateDto productUpdateDto);
  40.    
  41.     @DeleteMapping("/{id}")
  42.     ResponseEntity<Void> deleteProduct(@PathVariable("id") Long id);
  43. }
  44. // 订单服务实现
  45. @Service
  46. public class OrderServiceImpl implements OrderService {
  47.    
  48.     private final OrderRepository orderRepository;
  49.     private final UserServiceClient userServiceClient;
  50.     private final ProductServiceClient productServiceClient;
  51.     private final OrderEventPublisher eventPublisher;
  52.    
  53.     @Autowired
  54.     public OrderServiceImpl(OrderRepository orderRepository,
  55.                           UserServiceClient userServiceClient,
  56.                           ProductServiceClient productServiceClient,
  57.                           OrderEventPublisher eventPublisher) {
  58.         this.orderRepository = orderRepository;
  59.         this.userServiceClient = userServiceClient;
  60.         this.productServiceClient = productServiceClient;
  61.         this.eventPublisher = eventPublisher;
  62.     }
  63.    
  64.     @Override
  65.     @Transactional
  66.     public OrderDto createOrder(Long userId, List<OrderItemCreateDto> items) {
  67.         // 验证用户存在
  68.         ResponseEntity<UserDto> userResponse = userServiceClient.getUserById(userId);
  69.         if (!userResponse.getStatusCode().is2xxSuccessful() || userResponse.getBody() == null) {
  70.             throw new UserNotFoundException(userId);
  71.         }
  72.         
  73.         // 创建订单
  74.         Order order = new Order();
  75.         order.setUserId(userId);
  76.         order.setStatus(OrderStatus.NEW);
  77.         order.setCreatedAt(LocalDateTime.now());
  78.         
  79.         // 添加订单项
  80.         for (OrderItemCreateDto itemDto : items) {
  81.             // 验证产品存在
  82.             ResponseEntity<ProductDto> productResponse = productServiceClient.getProductById(itemDto.getProductId());
  83.             if (!productResponse.getStatusCode().is2xxSuccessful() || productResponse.getBody() == null) {
  84.                 throw new ProductNotFoundException(itemDto.getProductId());
  85.             }
  86.             
  87.             ProductDto product = productResponse.getBody();
  88.             OrderItem item = new OrderItem();
  89.             item.setProductId(product.getId());
  90.             item.setProductName(product.getName());
  91.             item.setUnitPrice(product.getPrice());
  92.             item.setQuantity(itemDto.getQuantity());
  93.             item.setTotalPrice(product.getPrice().multiply(BigDecimal.valueOf(itemDto.getQuantity())));
  94.             
  95.             order.addItem(item);
  96.         }
  97.         
  98.         // 计算总金额
  99.         order.calculateTotal();
  100.         
  101.         // 保存订单
  102.         order = orderRepository.save(order);
  103.         
  104.         // 发布订单创建事件
  105.         eventPublisher.publishOrderCreatedEvent(order);
  106.         
  107.         // 转换为DTO并返回
  108.         return convertToDto(order);
  109.     }
  110.    
  111.     @Override
  112.     public OrderDto getOrderById(Long id) {
  113.         Order order = orderRepository.findById(id)
  114.                 .orElseThrow(() -> new OrderNotFoundException(id));
  115.         
  116.         return convertToDto(order);
  117.     }
  118.    
  119.     @Override
  120.     public Page<OrderDto> getOrdersByUserId(Long userId, int page, int size) {
  121.         Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
  122.         Page<Order> orders = orderRepository.findByUserId(userId, pageable);
  123.         
  124.         return orders.map(this::convertToDto);
  125.     }
  126.    
  127.     private OrderDto convertToDto(Order order) {
  128.         OrderDto dto = new OrderDto();
  129.         dto.setId(order.getId());
  130.         dto.setUserId(order.getUserId());
  131.         dto.setStatus(order.getStatus());
  132.         dto.setTotalAmount(order.getTotalAmount());
  133.         dto.setItems(order.getItems().stream()
  134.                 .map(this::convertItemToDto)
  135.                 .collect(Collectors.toList()));
  136.         dto.setCreatedAt(order.getCreatedAt());
  137.         dto.setUpdatedAt(order.getUpdatedAt());
  138.         
  139.         return dto;
  140.     }
  141.    
  142.     private OrderItemDto convertItemToDto(OrderItem item) {
  143.         OrderItemDto dto = new OrderItemDto();
  144.         dto.setProductId(item.getProductId());
  145.         dto.setProductName(item.getProductName());
  146.         dto.setUnitPrice(item.getUnitPrice());
  147.         dto.setQuantity(item.getQuantity());
  148.         dto.setTotalPrice(item.getTotalPrice());
  149.         
  150.         return dto;
  151.     }
  152. }
  153. // 服务网关配置
  154. @Configuration
  155. public class GatewayConfig {
  156.    
  157.     @Bean
  158.     public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
  159.         return builder.routes()
  160.                 .route("user-service", r -> r.path("/api/users/**")
  161.                         .uri("lb://user-service"))
  162.                 .route("product-service", r -> r.path("/api/products/**")
  163.                         .uri("lb://product-service"))
  164.                 .route("order-service", r -> r.path("/api/orders/**")
  165.                         .uri("lb://order-service"))
  166.                 .build();
  167.     }
  168. }
复制代码

2. 性能优化策略
  1. // 多级缓存配置
  2. @Configuration
  3. @EnableCaching
  4. public class CacheConfig {
  5.    
  6.     @Bean
  7.     public CacheManager cacheManager() {
  8.         CompositeCacheManager cacheManager = new CompositeCacheManager(
  9.                 caffeineCacheManager(),
  10.                 redisCacheManager()
  11.         );
  12.         cacheManager.setFallbackToNoOpCache(false);
  13.         return cacheManager;
  14.     }
  15.    
  16.     @Bean
  17.     public CaffeineCacheManager caffeineCacheManager() {
  18.         CaffeineCacheManager cacheManager = new CaffeineCacheManager();
  19.         cacheManager.setCaffeine(Caffeine.newBuilder()
  20.                 .initialCapacity(100)
  21.                 .maximumSize(1000)
  22.                 .expireAfterWrite(5, TimeUnit.MINUTES));
  23.         return cacheManager;
  24.     }
  25.    
  26.     @Bean
  27.     public RedisCacheManager redisCacheManager() {
  28.         RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
  29.                 .entryTtl(Duration.ofHours(1))
  30.                 .disableCachingNullValues()
  31.                 .serializeValuesWith(RedisSerializationContext.SerializationPair
  32.                         .fromSerializer(new GenericJackson2JsonRedisSerializer()));
  33.         
  34.         return RedisCacheManager.builder(redisConnectionFactory())
  35.                 .cacheDefaults(config)
  36.                 .build();
  37.     }
  38.    
  39.     @Bean
  40.     public RedisConnectionFactory redisConnectionFactory() {
  41.         return new LettuceConnectionFactory();
  42.     }
  43. }
  44. // 缓存使用示例
  45. @Service
  46. public class ProductServiceImpl implements ProductService {
  47.    
  48.     private final ProductRepository productRepository;
  49.    
  50.     @Autowired
  51.     public ProductServiceImpl(ProductRepository productRepository) {
  52.         this.productRepository = productRepository;
  53.     }
  54.    
  55.     @Override
  56.     @Cacheable(value = "products", key = "#id", unless = "#result == null")
  57.     public Product getProductById(Long id) {
  58.         return productRepository.findById(id).orElse(null);
  59.     }
  60.    
  61.     @Override
  62.     @Cacheable(value = "products", key = "'category:' + #category + ':page:' + #page + ':size:' + #size")
  63.     public Page<Product> getProductsByCategory(String category, int page, int size) {
  64.         Pageable pageable = PageRequest.of(page, size);
  65.         return productRepository.findByCategory(category, pageable);
  66.     }
  67.    
  68.     @Override
  69.     @Caching(
  70.         put = @CachePut(value = "products", key = "#product.id"),
  71.         evict = {
  72.             @CacheEvict(value = "products", key = "'category:' + #product.category + ':page:*'"),
  73.             @CacheEvict(value = "products", key = "'featured'")
  74.         }
  75.     )
  76.     public Product updateProduct(Product product) {
  77.         return productRepository.save(product);
  78.     }
  79.    
  80.     @Override
  81.     @CacheEvict(value = "products", allEntries = true)
  82.     public void refreshProductCache() {
  83.         // 清除所有产品缓存
  84.     }
  85. }
复制代码
  1. // 异步服务配置
  2. @Configuration
  3. @EnableAsync
  4. public class AsyncConfig implements AsyncConfigurer {
  5.    
  6.     @Override
  7.     public Executor getAsyncExecutor() {
  8.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
  9.         executor.setCorePoolSize(5);
  10.         executor.setMaxPoolSize(10);
  11.         executor.setQueueCapacity(25);
  12.         executor.setThreadNamePrefix("AntiX-Async-");
  13.         executor.initialize();
  14.         return executor;
  15.     }
  16.    
  17.     @Override
  18.     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  19.         return new CustomAsyncExceptionHandler();
  20.     }
  21. }
  22. // 自定义异步异常处理器
  23. public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
  24.    
  25.     private static final Logger logger = LoggerFactory.getLogger(CustomAsyncExceptionHandler.class);
  26.    
  27.     @Override
  28.     public void handleUncaughtException(Throwable ex, Method method, Object... params) {
  29.         logger.error("Exception in async method: {}", method.getName(), ex);
  30.         
  31.         // 可以在这里添加通知逻辑,如发送邮件、短信等
  32.     }
  33. }
  34. // 异步服务实现
  35. @Service
  36. public class NotificationServiceImpl implements NotificationService {
  37.    
  38.     private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
  39.    
  40.     @Override
  41.     @Async
  42.     public void sendEmail(String to, String subject, String body) {
  43.         try {
  44.             // 模拟发送邮件的耗时操作
  45.             Thread.sleep(1000);
  46.             logger.info("Email sent to {} with subject: {}", to, subject);
  47.         } catch (InterruptedException e) {
  48.             Thread.currentThread().interrupt();
  49.         }
  50.     }
  51.    
  52.     @Override
  53.     @Async("taskExecutor")
  54.     public Future<String> sendSms(String phoneNumber, String message) {
  55.         try {
  56.             // 模拟发送短信的耗时操作
  57.             Thread.sleep(500);
  58.             String result = "SMS sent to " + phoneNumber;
  59.             logger.info(result);
  60.             return new AsyncResult<>(result);
  61.         } catch (InterruptedException e) {
  62.             Thread.currentThread().interrupt();
  63.             return new AsyncResult<>("Failed to send SMS due to interruption");
  64.         }
  65.     }
  66.    
  67.     @Override
  68.     @Async
  69.     public void sendPushNotification(String userId, String title, String message) {
  70.         try {
  71.             // 模拟发送推送通知的耗时操作
  72.             Thread.sleep(300);
  73.             logger.info("Push notification sent to user {} with title: {}", userId, title);
  74.         } catch (InterruptedException e) {
  75.             Thread.currentThread().interrupt();
  76.         }
  77.     }
  78. }
复制代码
  1. // 数据库配置
  2. @Configuration
  3. @EnableJpaRepositories(basePackages = "com.example.antix.repository")
  4. @EnableTransactionManagement
  5. public class DatabaseConfig {
  6.    
  7.     @Bean
  8.     @Primary
  9.     @ConfigurationProperties(prefix = "spring.datasource")
  10.     public DataSource dataSource() {
  11.         return DataSourceBuilder.create().type(HikariDataSource.class).build();
  12.     }
  13.    
  14.     @Bean
  15.     public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
  16.         LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
  17.         em.setDataSource(dataSource());
  18.         em.setPackagesToScan("com.example.antix.model");
  19.         
  20.         HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
  21.         em.setJpaVendorAdapter(vendorAdapter);
  22.         
  23.         Properties properties = new Properties();
  24.         properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
  25.         properties.setProperty("hibernate.show_sql", "false");
  26.         properties.setProperty("hibernate.format_sql", "false");
  27.         properties.setProperty("hibernate.hbm2ddl.auto", "none");
  28.         properties.setProperty("hibernate.jdbc.batch_size", "30");
  29.         properties.setProperty("hibernate.order_inserts", "true");
  30.         properties.setProperty("hibernate.order_updates", "true");
  31.         properties.setProperty("hibernate.jdbc.fetch_size", "100");
  32.         properties.setProperty("hibernate.cache.use_second_level_cache", "true");
  33.         properties.setProperty("hibernate.cache.use_query_cache", "true");
  34.         properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
  35.         properties.setProperty("hibernate.cache.provider_configuration_file_resource_path", "classpath:ehcache.xml");
  36.         
  37.         em.setJpaProperties(properties);
  38.         
  39.         return em;
  40.     }
  41.    
  42.     @Bean
  43.     public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
  44.         JpaTransactionManager transactionManager = new JpaTransactionManager();
  45.         transactionManager.setEntityManagerFactory(entityManagerFactory);
  46.         return transactionManager;
  47.     }
  48. }
  49. // 批量操作示例
  50. @Service
  51. public class ProductBatchServiceImpl implements ProductBatchService {
  52.    
  53.     private final ProductRepository productRepository;
  54.     private final EntityManager entityManager;
  55.    
  56.     @Autowired
  57.     public ProductBatchServiceImpl(ProductRepository productRepository, EntityManager entityManager) {
  58.         this.productRepository = productRepository;
  59.         this.entityManager = entityManager;
  60.     }
  61.    
  62.     @Override
  63.     @Transactional
  64.     public void batchInsertProducts(List<Product> products) {
  65.         final int batchSize = 30;
  66.         
  67.         for (int i = 0; i < products.size(); i++) {
  68.             Product product = products.get(i);
  69.             entityManager.persist(product);
  70.             
  71.             if (i > 0 && i % batchSize == 0) {
  72.                 // 刷新并清除会话,避免内存溢出
  73.                 entityManager.flush();
  74.                 entityManager.clear();
  75.             }
  76.         }
  77.         
  78.         // 刷新剩余的记录
  79.         entityManager.flush();
  80.         entityManager.clear();
  81.     }
  82.    
  83.     @Override
  84.     @Transactional
  85.     public void batchUpdateProducts(List<Product> products) {
  86.         final int batchSize = 30;
  87.         
  88.         for (int i = 0; i < products.size(); i++) {
  89.             Product product = products.get(i);
  90.             entityManager.merge(product);
  91.             
  92.             if (i > 0 && i % batchSize == 0) {
  93.                 // 刷新并清除会话,避免内存溢出
  94.                 entityManager.flush();
  95.                 entityManager.clear();
  96.             }
  97.         }
  98.         
  99.         // 刷新剩余的记录
  100.         entityManager.flush();
  101.         entityManager.clear();
  102.     }
  103.    
  104.     @Override
  105.     @Transactional
  106.     public void batchDeleteProducts(List<Long> productIds) {
  107.         final int batchSize = 30;
  108.         
  109.         for (int i = 0; i < productIds.size(); i++) {
  110.             Long productId = productIds.get(i);
  111.             Product product = entityManager.find(Product.class, productId);
  112.             if (product != null) {
  113.                 entityManager.remove(product);
  114.             }
  115.             
  116.             if (i > 0 && i % batchSize == 0) {
  117.                 // 刷新并清除会话,避免内存溢出
  118.                 entityManager.flush();
  119.                 entityManager.clear();
  120.             }
  121.         }
  122.         
  123.         // 刷新剩余的记录
  124.         entityManager.flush();
  125.         entityManager.clear();
  126.     }
  127. }
  128. // 查询优化示例
  129. @Repository
  130. public class ProductRepositoryImpl implements ProductRepositoryCustom {
  131.    
  132.     @PersistenceContext
  133.     private EntityManager entityManager;
  134.    
  135.     @Override
  136.     public List<Product> findProductsByCriteria(ProductSearchCriteria criteria) {
  137.         CriteriaBuilder cb = entityManager.getCriteriaBuilder();
  138.         CriteriaQuery<Product> query = cb.createQuery(Product.class);
  139.         Root<Product> product = query.from(Product.class);
  140.         
  141.         List<Predicate> predicates = new ArrayList<>();
  142.         
  143.         // 添加名称过滤条件
  144.         if (StringUtils.hasText(criteria.getName())) {
  145.             predicates.add(cb.like(product.get("name"), "%" + criteria.getName() + "%"));
  146.         }
  147.         
  148.         // 添加类别过滤条件
  149.         if (StringUtils.hasText(criteria.getCategory())) {
  150.             predicates.add(cb.equal(product.get("category"), criteria.getCategory()));
  151.         }
  152.         
  153.         // 添加价格范围过滤条件
  154.         if (criteria.getMinPrice() != null) {
  155.             predicates.add(cb.ge(product.get("price"), criteria.getMinPrice()));
  156.         }
  157.         if (criteria.getMaxPrice() != null) {
  158.             predicates.add(cb.le(product.get("price"), criteria.getMaxPrice()));
  159.         }
  160.         
  161.         // 添加状态过滤条件
  162.         if (criteria.getStatus() != null) {
  163.             predicates.add(cb.equal(product.get("status"), criteria.getStatus()));
  164.         }
  165.         
  166.         // 组合所有条件
  167.         query.where(predicates.toArray(new Predicate[0]));
  168.         
  169.         // 添加排序
  170.         if (criteria.getSortBy() != null) {
  171.             Path<Object> sortPath = product.get(criteria.getSortBy());
  172.             if (criteria.getSortDirection() == Sort.Direction.DESC) {
  173.                 query.orderBy(cb.desc(sortPath));
  174.             } else {
  175.                 query.orderBy(cb.asc(sortPath));
  176.             }
  177.         }
  178.         
  179.         // 创建查询并设置分页
  180.         TypedQuery<Product> typedQuery = entityManager.createQuery(query);
  181.         if (criteria.getPage() != null && criteria.getSize() != null) {
  182.             typedQuery.setFirstResult(criteria.getPage() * criteria.getSize());
  183.             typedQuery.setMaxResults(criteria.getSize());
  184.         }
  185.         
  186.         return typedQuery.getResultList();
  187.     }
  188. }
复制代码

3. 安全策略
  1. // 安全配置
  2. @Configuration
  3. @EnableWebSecurity
  4. @EnableGlobalMethodSecurity(prePostEnabled = true)
  5. public class SecurityConfig extends WebSecurityConfigurerAdapter {
  6.    
  7.     @Autowired
  8.     private UserDetailsService userDetailsService;
  9.    
  10.     @Autowired
  11.     private JwtAuthenticationEntryPoint unauthorizedHandler;
  12.    
  13.     @Bean
  14.     public PasswordEncoder passwordEncoder() {
  15.         return new BCryptPasswordEncoder();
  16.     }
  17.    
  18.     @Bean
  19.     public JwtAuthenticationFilter jwtAuthenticationFilter() {
  20.         return new JwtAuthenticationFilter();
  21.     }
  22.    
  23.     @Override
  24.     public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
  25.         authenticationManagerBuilder
  26.                 .userDetailsService(userDetailsService)
  27.                 .passwordEncoder(passwordEncoder());
  28.     }
  29.    
  30.     @Bean(BeanIds.AUTHENTICATION_MANAGER)
  31.     @Override
  32.     public AuthenticationManager authenticationManagerBean() throws Exception {
  33.         return super.authenticationManagerBean();
  34.     }
  35.    
  36.     @Override
  37.     protected void configure(HttpSecurity http) throws Exception {
  38.         http
  39.                 .cors()
  40.                 .and()
  41.                 .csrf()
  42.                 .disable()
  43.                 .exceptionHandling()
  44.                 .authenticationEntryPoint(unauthorizedHandler)
  45.                 .and()
  46.                 .sessionManagement()
  47.                 .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
  48.                 .and()
  49.                 .authorizeRequests()
  50.                 .antMatchers("/api/auth/**")
  51.                 .permitAll()
  52.                 .antMatchers("/api/public/**")
  53.                 .permitAll()
  54.                 .antMatchers("/api/admin/**")
  55.                 .hasRole("ADMIN")
  56.                 .antMatchers(HttpMethod.GET, "/api/products/**", "/api/categories/**")
  57.                 .permitAll()
  58.                 .anyRequest()
  59.                 .authenticated();
  60.         
  61.         // 添加JWT过滤器
  62.         http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
  63.     }
  64. }
  65. // JWT认证过滤器
  66. public class JwtAuthenticationFilter extends OncePerRequestFilter {
  67.    
  68.     @Autowired
  69.     private JwtTokenProvider tokenProvider;
  70.    
  71.     @Autowired
  72.     private UserDetailsService userDetailsService;
  73.    
  74.     private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
  75.    
  76.     @Override
  77.     protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
  78.             throws ServletException, IOException {
  79.         try {
  80.             String jwt = getJwtFromRequest(request);
  81.             
  82.             if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
  83.                 Long userId = tokenProvider.getUserIdFromJWT(jwt);
  84.                
  85.                 UserDetails userDetails = userDetailsService.loadUserById(userId);
  86.                 UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
  87.                         userDetails, null, userDetails.getAuthorities());
  88.                 authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
  89.                
  90.                 SecurityContextHolder.getContext().setAuthentication(authentication);
  91.             }
  92.         } catch (Exception ex) {
  93.             logger.error("Could not set user authentication in security context", ex);
  94.         }
  95.         
  96.         filterChain.doFilter(request, response);
  97.     }
  98.    
  99.     private String getJwtFromRequest(HttpServletRequest request) {
  100.         String bearerToken = request.getHeader("Authorization");
  101.         if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
  102.             return bearerToken.substring(7);
  103.         }
  104.         return null;
  105.     }
  106. }
  107. // 方法级安全示例
  108. @Service
  109. public class OrderServiceImpl implements OrderService {
  110.    
  111.     @Override
  112.     @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
  113.     public Order getOrderById(Long id) {
  114.         // 获取订单逻辑
  115.     }
  116.    
  117.     @Override
  118.     @PreAuthorize("hasRole('ADMIN')")
  119.     public List<Order> getAllOrders() {
  120.         // 获取所有订单逻辑
  121.     }
  122.    
  123.     @Override
  124.     @PreAuthorize("#order.userId == authentication.principal.id or hasRole('ADMIN')")
  125.     public void updateOrder(Order order) {
  126.         // 更新订单逻辑
  127.     }
  128.    
  129.     @Override
  130.     @PreAuthorize("#order.userId == authentication.principal.id or hasRole('ADMIN')")
  131.     public void deleteOrder(Order order) {
  132.         // 删除订单逻辑
  133.     }
  134. }
复制代码
  1. // 加密服务
  2. @Service
  3. public class EncryptionServiceImpl implements EncryptionService {
  4.    
  5.     private final String encryptionKey;
  6.     private final String salt;
  7.    
  8.     @Autowired
  9.     public EncryptionServiceImpl(
  10.             @Value("${app.encryption.key}") String encryptionKey,
  11.             @Value("${app.encryption.salt}") String salt) {
  12.         this.encryptionKey = encryptionKey;
  13.         this.salt = salt;
  14.     }
  15.    
  16.     @Override
  17.     public String encrypt(String data) {
  18.         try {
  19.             SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  20.             KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt.getBytes(), 65536, 256);
  21.             SecretKey tmp = factory.generateSecret(spec);
  22.             SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
  23.             
  24.             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  25.             cipher.init(Cipher.ENCRYPT_MODE, secretKey);
  26.             
  27.             byte[] iv = new byte[16];
  28.             new SecureRandom().nextBytes(iv);
  29.             IvParameterSpec ivSpec = new IvParameterSpec(iv);
  30.             
  31.             cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
  32.             byte[] encryptedData = cipher.doFinal(data.getBytes());
  33.             
  34.             byte[] combined = new byte[iv.length + encryptedData.length];
  35.             System.arraycopy(iv, 0, combined, 0, iv.length);
  36.             System.arraycopy(encryptedData, 0, combined, iv.length, encryptedData.length);
  37.             
  38.             return Base64.getEncoder().encodeToString(combined);
  39.         } catch (Exception e) {
  40.             throw new EncryptionException("Failed to encrypt data", e);
  41.         }
  42.     }
  43.    
  44.     @Override
  45.     public String decrypt(String encryptedData) {
  46.         try {
  47.             byte[] combined = Base64.getDecoder().decode(encryptedData);
  48.             
  49.             byte[] iv = new byte[16];
  50.             byte[] encrypted = new byte[combined.length - iv.length];
  51.             System.arraycopy(combined, 0, iv, 0, iv.length);
  52.             System.arraycopy(combined, iv.length, encrypted, 0, encrypted.length);
  53.             
  54.             SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
  55.             KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt.getBytes(), 65536, 256);
  56.             SecretKey tmp = factory.generateSecret(spec);
  57.             SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
  58.             
  59.             Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
  60.             IvParameterSpec ivSpec = new IvParameterSpec(iv);
  61.             
  62.             cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
  63.             byte[] decryptedData = cipher.doFinal(encrypted);
  64.             
  65.             return new String(decryptedData);
  66.         } catch (Exception e) {
  67.             throw new EncryptionException("Failed to decrypt data", e);
  68.         }
  69.     }
  70. }
  71. // 敏感数据处理器
  72. @Aspect
  73. @Component
  74. public class SensitiveDataAspect {
  75.    
  76.     private final EncryptionService encryptionService;
  77.    
  78.     @Autowired
  79.     public SensitiveDataAspect(EncryptionService encryptionService) {
  80.         this.encryptionService = encryptionService;
  81.     }
  82.    
  83.     @Around("@annotation(EncryptSensitiveData)")
  84.     public Object encryptSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
  85.         Object result = joinPoint.proceed();
  86.         
  87.         // 处理返回结果中的敏感数据
  88.         if (result instanceof User) {
  89.             User user = (User) result;
  90.             // 加密敏感字段
  91.             if (user.getEmail() != null) {
  92.                 user.setEmail(encryptionService.encrypt(user.getEmail()));
  93.             }
  94.             if (user.getPhone() != null) {
  95.                 user.setPhone(encryptionService.encrypt(user.getPhone()));
  96.             }
  97.             if (user.getIdCard() != null) {
  98.                 user.setIdCard(encryptionService.encrypt(user.getIdCard()));
  99.             }
  100.         }
  101.         
  102.         return result;
  103.     }
  104.    
  105.     @Around("@annotation(DecryptSensitiveData)")
  106.     public Object decryptSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
  107.         Object[] args = joinPoint.getArgs();
  108.         
  109.         // 处理方法参数中的敏感数据
  110.         for (int i = 0; i < args.length; i++) {
  111.             if (args[i] instanceof User) {
  112.                 User user = (User) args[i];
  113.                 // 解密敏感字段
  114.                 if (user.getEmail() != null) {
  115.                     user.setEmail(encryptionService.decrypt(user.getEmail()));
  116.                 }
  117.                 if (user.getPhone() != null) {
  118.                     user.setPhone(encryptionService.decrypt(user.getPhone()));
  119.                 }
  120.                 if (user.getIdCard() != null) {
  121.                     user.setIdCard(encryptionService.decrypt(user.getIdCard()));
  122.                 }
  123.             }
  124.         }
  125.         
  126.         return joinPoint.proceed(args);
  127.     }
  128. }
复制代码

4. 监控与运维
  1. // 自定义健康指标
  2. @Component
  3. public class CustomHealthIndicator implements HealthIndicator {
  4.    
  5.     private final DatabaseHealthIndicator databaseHealthIndicator;
  6.     private final RedisHealthIndicator redisHealthIndicator;
  7.     private final ExternalServiceHealthIndicator externalServiceHealthIndicator;
  8.    
  9.     @Autowired
  10.     public CustomHealthIndicator(DatabaseHealthIndicator databaseHealthIndicator,
  11.                                RedisHealthIndicator redisHealthIndicator,
  12.                                ExternalServiceHealthIndicator externalServiceHealthIndicator) {
  13.         this.databaseHealthIndicator = databaseHealthIndicator;
  14.         this.redisHealthIndicator = redisHealthIndicator;
  15.         this.externalServiceHealthIndicator = externalServiceHealthIndicator;
  16.     }
  17.    
  18.     @Override
  19.     public Health health() {
  20.         // 检查数据库状态
  21.         Health dbHealth = databaseHealthIndicator.health();
  22.         
  23.         // 检查Redis状态
  24.         Health redisHealth = redisHealthIndicator.health();
  25.         
  26.         // 检查外部服务状态
  27.         Health externalServiceHealth = externalServiceHealthIndicator.health();
  28.         
  29.         // 确定整体状态
  30.         Status overallStatus = Status.UP;
  31.         List<String> details = new ArrayList<>();
  32.         
  33.         if (dbHealth.getStatus() != Status.UP) {
  34.             overallStatus = Status.DOWN;
  35.             details.add("Database is not available: " + dbHealth.getDetails());
  36.         }
  37.         
  38.         if (redisHealth.getStatus() != Status.UP) {
  39.             overallStatus = overallStatus == Status.UP ? Status.UP : Status.DOWN;
  40.             details.add("Redis is not available: " + redisHealth.getDetails());
  41.         }
  42.         
  43.         if (externalServiceHealth.getStatus() != Status.UP) {
  44.             overallStatus = overallStatus == Status.UP ? Status.UP : Status.DOWN;
  45.             details.add("External service is not available: " + externalServiceHealth.getDetails());
  46.         }
  47.         
  48.         if (overallStatus == Status.UP) {
  49.             return Health.up()
  50.                     .withDetail("database", dbHealth.getDetails())
  51.                     .withDetail("redis", redisHealth.getDetails())
  52.                     .withDetail("externalService", externalServiceHealth.getDetails())
  53.                     .build();
  54.         } else {
  55.             return Health.down()
  56.                     .withDetail("reason", String.join("; ", details))
  57.                     .withDetail("database", dbHealth.getDetails())
  58.                     .withDetail("redis", redisHealth.getDetails())
  59.                     .withDetail("externalService", externalServiceHealth.getDetails())
  60.                     .build();
  61.         }
  62.     }
  63. }
  64. // 自定义指标
  65. @Service
  66. public class CustomMetrics {
  67.    
  68.     private final MeterRegistry meterRegistry;
  69.     private final Counter orderCounter;
  70.     private final Timer orderProcessingTimer;
  71.    
  72.     @Autowired
  73.     public CustomMetrics(MeterRegistry meterRegistry) {
  74.         this.meterRegistry = meterRegistry;
  75.         this.orderCounter = Counter.builder("orders.created")
  76.                 .description("Number of orders created")
  77.                 .register(meterRegistry);
  78.         
  79.         this.orderProcessingTimer = Timer.builder("orders.processing.time")
  80.                 .description("Time taken to process orders")
  81.                 .register(meterRegistry);
  82.     }
  83.    
  84.     public void incrementOrderCounter() {
  85.         orderCounter.increment();
  86.     }
  87.    
  88.     public Timer.Sample startOrderProcessingTimer() {
  89.         return Timer.start(meterRegistry);
  90.     }
  91.    
  92.     public void stopOrderProcessingTimer(Timer.Sample sample) {
  93.         sample.stop(orderProcessingTimer);
  94.     }
  95. }
  96. // 使用自定义指标
  97. @Service
  98. public class OrderServiceImpl implements OrderService {
  99.    
  100.     private final OrderRepository orderRepository;
  101.     private final CustomMetrics customMetrics;
  102.    
  103.     @Autowired
  104.     public OrderServiceImpl(OrderRepository orderRepository, CustomMetrics customMetrics) {
  105.         this.orderRepository = orderRepository;
  106.         this.customMetrics = customMetrics;
  107.     }
  108.    
  109.     @Override
  110.     @Transactional
  111.     public Order createOrder(Order order) {
  112.         Timer.Sample sample = customMetrics.startOrderProcessingTimer();
  113.         
  114.         try {
  115.             // 创建订单逻辑
  116.             Order savedOrder = orderRepository.save(order);
  117.             
  118.             // 增加订单计数器
  119.             customMetrics.incrementOrderCounter();
  120.             
  121.             return savedOrder;
  122.         } finally {
  123.             // 停止计时器
  124.             customMetrics.stopOrderProcessingTimer(sample);
  125.         }
  126.     }
  127. }
复制代码
  1. // 日志配置
  2. @Configuration
  3. public class LoggingConfig {
  4.    
  5.     @Bean
  6.     public InMemoryLogAppender inMemoryLogAppender() {
  7.         InMemoryLogAppender appender = new InMemoryLogAppender();
  8.         appender.setName("InMemoryLogAppender");
  9.         appender.setThreshold(Level.INFO);
  10.         appender.setMaxSize(1000);
  11.         
  12.         PatternLayoutEncoder encoder = new PatternLayoutEncoder();
  13.         encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
  14.         encoder.start();
  15.         
  16.         appender.setEncoder(encoder);
  17.         appender.start();
  18.         
  19.         Logger rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
  20.         if (rootLogger instanceof ch.qos.logback.classic.Logger) {
  21.             ((ch.qos.logback.classic.Logger) rootLogger).addAppender(appender);
  22.         }
  23.         
  24.         return appender;
  25.     }
  26. }
  27. // 审计日志服务
  28. @Service
  29. public class AuditLogServiceImpl implements AuditLogService {
  30.    
  31.     private final AuditLogRepository auditLogRepository;
  32.    
  33.     @Autowired
  34.     public AuditLogServiceImpl(AuditLogRepository auditLogRepository) {
  35.         this.auditLogRepository = auditLogRepository;
  36.     }
  37.    
  38.     @Override
  39.     @Async
  40.     public void logAction(String userId, String action, String details) {
  41.         AuditLog auditLog = new AuditLog();
  42.         auditLog.setUserId(userId);
  43.         auditLog.setAction(action);
  44.         auditLog.setDetails(details);
  45.         auditLog.setTimestamp(LocalDateTime.now());
  46.         auditLog.setIpAddress(getCurrentIpAddress());
  47.         auditLog.setUserAgent(getCurrentUserAgent());
  48.         
  49.         auditLogRepository.save(auditLog);
  50.     }
  51.    
  52.     @Override
  53.     public Page<AuditLog> getAuditLogs(String userId, LocalDateTime startTime, LocalDateTime endTime,
  54.                                       Pageable pageable) {
  55.         Specification<AuditLog> spec = Specification.where(null);
  56.         
  57.         if (StringUtils.hasText(userId)) {
  58.             spec = spec.and((root, query, cb) -> cb.equal(root.get("userId"), userId));
  59.         }
  60.         
  61.         if (startTime != null) {
  62.             spec = spec.and((root, query, cb) -> cb.greaterThanOrEqualTo(root.get("timestamp"), startTime));
  63.         }
  64.         
  65.         if (endTime != null) {
  66.             spec = spec.and((root, query, cb) -> cb.lessThanOrEqualTo(root.get("timestamp"), endTime));
  67.         }
  68.         
  69.         return auditLogRepository.findAll(spec, pageable);
  70.     }
  71.    
  72.     private String getCurrentIpAddress() {
  73.         // 获取当前请求的IP地址
  74.         RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  75.         if (requestAttributes instanceof ServletRequestAttributes) {
  76.             HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
  77.             String ipAddress = request.getHeader("X-Forwarded-For");
  78.             if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
  79.                 ipAddress = request.getHeader("Proxy-Client-IP");
  80.             }
  81.             if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
  82.                 ipAddress = request.getHeader("WL-Proxy-Client-IP");
  83.             }
  84.             if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
  85.                 ipAddress = request.getRemoteAddr();
  86.             }
  87.             return ipAddress;
  88.         }
  89.         return "unknown";
  90.     }
  91.    
  92.     private String getCurrentUserAgent() {
  93.         // 获取当前请求的User-Agent
  94.         RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
  95.         if (requestAttributes instanceof ServletRequestAttributes) {
  96.             HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
  97.             return request.getHeader("User-Agent");
  98.         }
  99.         return "unknown";
  100.     }
  101. }
  102. // 审计日志切面
  103. @Aspect
  104. @Component
  105. public class AuditLogAspect {
  106.    
  107.     private final AuditLogService auditLogService;
  108.    
  109.     @Autowired
  110.     public AuditLogAspect(AuditLogService auditLogService) {
  111.         this.auditLogService = auditLogService;
  112.     }
  113.    
  114.     @AfterReturning(pointcut = "@annotation(auditLog)", returning = "result")
  115.     public void logAfterReturning(JoinPoint joinPoint, AuditLog auditLog, Object result) {
  116.         String userId = getCurrentUserId();
  117.         String action = auditLog.action();
  118.         String details = createLogDetails(joinPoint, result);
  119.         
  120.         auditLogService.logAction(userId, action, details);
  121.     }
  122.    
  123.     @AfterThrowing(pointcut = "@annotation(auditLog)", throwing = "exception")
  124.     public void logAfterThrowing(JoinPoint joinPoint, AuditLog auditLog, Exception exception) {
  125.         String userId = getCurrentUserId();
  126.         String action = auditLog.action();
  127.         String details = "Failed: " + exception.getMessage();
  128.         
  129.         auditLogService.logAction(userId, action, details);
  130.     }
  131.    
  132.     private String getCurrentUserId() {
  133.         // 获取当前用户ID
  134.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  135.         if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
  136.             return authentication.getName();
  137.         }
  138.         return "anonymous";
  139.     }
  140.    
  141.     private String createLogDetails(JoinPoint joinPoint, Object result) {
  142.         StringBuilder details = new StringBuilder();
  143.         details.append("Method: ").append(joinPoint.getSignature().toShortString());
  144.         
  145.         // 添加参数信息
  146.         Object[] args = joinPoint.getArgs();
  147.         if (args.length > 0) {
  148.             details.append(", Parameters: [");
  149.             for (int i = 0; i < args.length; i++) {
  150.                 if (i > 0) {
  151.                     details.append(", ");
  152.                 }
  153.                 details.append(args[i] != null ? args[i].toString() : "null");
  154.             }
  155.             details.append("]");
  156.         }
  157.         
  158.         // 添加返回值信息
  159.         if (result != null) {
  160.             details.append(", Result: ").append(result.toString());
  161.         }
  162.         
  163.         return details.toString();
  164.     }
  165. }
复制代码

总结与展望

AntiX系统开发框架作为一个全面的企业级开发解决方案,提供了丰富的特性和工具,帮助开发团队构建稳定、高效、可维护的应用系统。通过本文的介绍,我们深入了解了AntiX框架的高级特性和最佳实践,并通过真实项目案例展示了如何充分发挥框架优势。

关键要点总结

1. 模块化架构:AntiX框架采用模块化设计,使开发者能够根据项目需求选择合适的组件,避免不必要的复杂性。
2. 依赖注入与控制反转:通过DI和IoC容器,AntiX框架降低了组件之间的耦合度,提高了代码的可测试性和可维护性。
3. 面向切面编程:AOP支持使开发者能够将横切关注点与业务逻辑分离,提高代码的模块化程度。
4. 高级数据访问:AntiX框架提供了强大的数据访问层支持,包括ORM集成、查询优化和批量操作等功能。
5. 事件驱动架构:通过事件驱动机制,AntiX框架支持松耦合的组件通信,提高系统的可扩展性和灵活性。
6. 缓存机制:多级缓存支持帮助提高应用性能,减少数据库负载。
7. 安全框架集成:全面的安全支持,包括认证、授权、数据加密等功能,保护企业应用免受安全威胁。
8. 微服务支持:AntiX框架支持构建微服务架构,使应用能够模块化、可扩展且易于维护。
9. 性能优化:通过异步处理、缓存策略和数据库优化等技术,AntiX框架帮助构建高性能应用。
10. 监控与运维:全面的监控、日志和健康检查支持,使应用的运维更加高效。

模块化架构:AntiX框架采用模块化设计,使开发者能够根据项目需求选择合适的组件,避免不必要的复杂性。

依赖注入与控制反转:通过DI和IoC容器,AntiX框架降低了组件之间的耦合度,提高了代码的可测试性和可维护性。

面向切面编程:AOP支持使开发者能够将横切关注点与业务逻辑分离,提高代码的模块化程度。

高级数据访问:AntiX框架提供了强大的数据访问层支持,包括ORM集成、查询优化和批量操作等功能。

事件驱动架构:通过事件驱动机制,AntiX框架支持松耦合的组件通信,提高系统的可扩展性和灵活性。

缓存机制:多级缓存支持帮助提高应用性能,减少数据库负载。

安全框架集成:全面的安全支持,包括认证、授权、数据加密等功能,保护企业应用免受安全威胁。

微服务支持:AntiX框架支持构建微服务架构,使应用能够模块化、可扩展且易于维护。

性能优化:通过异步处理、缓存策略和数据库优化等技术,AntiX框架帮助构建高性能应用。

监控与运维:全面的监控、日志和健康检查支持,使应用的运维更加高效。

未来发展方向

1. 云原生支持:未来AntiX框架将进一步增强对云原生应用的支持,包括容器化部署、服务网格和云平台集成等。
2. AI/ML集成:随着人工智能和机器学习技术的发展,AntiX框架将提供更多AI/ML集成支持,使开发者能够轻松构建智能化应用。
3. 低代码/无代码开发:AntiX框架将引入更多低代码/无代码开发工具,降低开发门槛,提高开发效率。
4. 实时数据处理:增强对实时数据流处理的支持,满足实时分析和决策需求。
5. 边缘计算支持:随着边缘计算的兴起,AntiX框架将提供更多边缘计算场景下的开发支持。

云原生支持:未来AntiX框架将进一步增强对云原生应用的支持,包括容器化部署、服务网格和云平台集成等。

AI/ML集成:随着人工智能和机器学习技术的发展,AntiX框架将提供更多AI/ML集成支持,使开发者能够轻松构建智能化应用。

低代码/无代码开发:AntiX框架将引入更多低代码/无代码开发工具,降低开发门槛,提高开发效率。

实时数据处理:增强对实时数据流处理的支持,满足实时分析和决策需求。

边缘计算支持:随着边缘计算的兴起,AntiX框架将提供更多边缘计算场景下的开发支持。

通过持续创新和改进,AntiX框架将继续为企业级应用开发提供强大支持,帮助开发团队应对不断变化的业务需求和技术挑战。
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则