|
|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
x
引言
在当今快速发展的软件开发领域,选择合适的开发框架对于构建高效、稳定且可维护的企业级应用系统至关重要。AntiX系统开发框架作为一个现代化的企业级开发解决方案,提供了一套全面的工具和功能,帮助开发团队快速构建高性能、可扩展的应用程序。本文将深入探讨AntiX框架的高级特性、最佳实践,并通过真实项目案例展示如何充分利用该框架的优势,构建稳定高效的企业级应用系统。
AntiX框架概述
AntiX是一个全栈企业级开发框架,旨在简化复杂业务应用的开发过程。它采用模块化设计,提供了从前端到后端的完整解决方案,使开发团队能够专注于业务逻辑而非底层技术细节。
核心架构
AntiX框架基于分层架构设计,主要包括以下几个核心组件:
1. 表示层:提供用户界面和交互功能
2. 业务逻辑层:处理核心业务规则和流程
3. 数据访问层:管理与数据库的交互
4. 基础设施层:提供横切关注点支持,如安全性、事务管理等
主要特点
• 高性能:采用优化的执行引擎和缓存机制,确保应用响应迅速
• 可扩展性:支持水平扩展和微服务架构,适应业务增长需求
• 开发效率:提供丰富的代码生成工具和模板,加速开发过程
• 易于维护:清晰的架构设计和完善的文档支持,降低维护成本
AntiX框架的高级特性
1. 依赖注入与控制反转
AntiX框架提供了强大的依赖注入(DI)和控制反转(IoC)容器,使组件之间的耦合度降到最低,提高代码的可测试性和可维护性。
- // 定义服务接口
- public interface UserService {
- User getUserById(Long id);
- void saveUser(User user);
- }
- // 实现服务
- @Service
- public class UserServiceImpl implements UserService {
- private final UserRepository userRepository;
-
- // 通过构造函数注入依赖
- @Autowired
- public UserServiceImpl(UserRepository userRepository) {
- this.userRepository = userRepository;
- }
-
- @Override
- public User getUserById(Long id) {
- return userRepository.findById(id).orElse(null);
- }
-
- @Override
- @Transactional
- public void saveUser(User user) {
- userRepository.save(user);
- }
- }
- // 在控制器中使用服务
- @RestController
- @RequestMapping("/api/users")
- public class UserController {
- private final UserService userService;
-
- @Autowired
- public UserController(UserService userService) {
- this.userService = userService;
- }
-
- @GetMapping("/{id}")
- public ResponseEntity<User> getUser(@PathVariable Long id) {
- User user = userService.getUserById(id);
- return ResponseEntity.ok(user);
- }
- }
复制代码
2. 面向切面编程(AOP)
AntiX框架支持面向切面编程,允许开发者将横切关注点(如日志、安全、事务等)与业务逻辑分离,提高代码的模块化程度。
- // 定义切面
- @Aspect
- @Component
- public class LoggingAspect {
-
- private static final Logger logger = LoggerFactory.getLogger(LoggingAspect.class);
-
- // 定义切入点
- @Pointcut("execution(* com.example.antix.service.*.*(..))")
- public void serviceMethods() {}
-
- // 前置通知
- @Before("serviceMethods()")
- public void logMethodCall(JoinPoint joinPoint) {
- String methodName = joinPoint.getSignature().getName();
- logger.info("Entering method: {}", methodName);
- }
-
- // 后置通知
- @AfterReturning(pointcut = "serviceMethods()", returning = "result")
- public void logMethodReturn(JoinPoint joinPoint, Object result) {
- String methodName = joinPoint.getSignature().getName();
- logger.info("Exiting method: {} with result: {}", methodName, result);
- }
-
- // 异常通知
- @AfterThrowing(pointcut = "serviceMethods()", throwing = "exception")
- public void logMethodException(JoinPoint joinPoint, Throwable exception) {
- String methodName = joinPoint.getSignature().getName();
- logger.error("Exception in method: {}: {}", methodName, exception.getMessage());
- }
- }
复制代码
3. 高级数据访问与ORM集成
AntiX框架提供了强大的数据访问层,支持多种数据库和ORM框架,如Hibernate、MyBatis等,并提供了简化的API和高级查询功能。
- // 定义实体
- @Entity
- @Table(name = "users")
- public class User {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- @Column(nullable = false)
- private String username;
-
- @Column(nullable = false)
- private String email;
-
- @Column(nullable = false)
- private String password;
-
- // getters and setters
- }
- // 定义Repository接口
- public interface UserRepository extends JpaRepository<User, Long>, JpaSpecificationExecutor<User> {
-
- // 自定义查询方法
- User findByUsername(String username);
-
- @Query("SELECT u FROM User u WHERE u.email = :email")
- User findByEmail(@Param("email") String email);
-
- // 使用规范进行动态查询
- default List<User> findUsersByCriteria(String username, String email) {
- return findAll((Root<User> root, CriteriaQuery<?> query, CriteriaBuilder cb) -> {
- List<Predicate> predicates = new ArrayList<>();
-
- if (StringUtils.hasText(username)) {
- predicates.add(cb.like(root.get("username"), "%" + username + "%"));
- }
-
- if (StringUtils.hasText(email)) {
- predicates.add(cb.like(root.get("email"), "%" + email + "%"));
- }
-
- return cb.and(predicates.toArray(new Predicate[0]));
- });
- }
- }
复制代码
4. 事件驱动架构支持
AntiX框架内置了事件驱动架构支持,允许组件之间通过事件进行松耦合通信,提高系统的可扩展性和灵活性。
- // 定义事件
- public class UserCreatedEvent {
- private final User user;
- private final LocalDateTime createdAt;
-
- public UserCreatedEvent(User user) {
- this.user = user;
- this.createdAt = LocalDateTime.now();
- }
-
- // getters
- }
- // 定义事件发布者
- @Service
- public class UserServiceImpl implements UserService {
- private final UserRepository userRepository;
- private final ApplicationEventPublisher eventPublisher;
-
- @Autowired
- public UserServiceImpl(UserRepository userRepository, ApplicationEventPublisher eventPublisher) {
- this.userRepository = userRepository;
- this.eventPublisher = eventPublisher;
- }
-
- @Override
- @Transactional
- public void saveUser(User user) {
- userRepository.save(user);
- // 发布事件
- eventPublisher.publishEvent(new UserCreatedEvent(user));
- }
- }
- // 定义事件监听器
- @Component
- public class UserEventListener {
-
- private static final Logger logger = LoggerFactory.getLogger(UserEventListener.class);
-
- @EventListener
- public void handleUserCreatedEvent(UserCreatedEvent event) {
- User user = event.getUser();
- logger.info("User created: {} at {}", user.getUsername(), event.getCreatedAt());
-
- // 执行其他业务逻辑,如发送欢迎邮件等
- sendWelcomeEmail(user);
- }
-
- private void sendWelcomeEmail(User user) {
- // 邮件发送逻辑
- }
- }
复制代码
5. 高级缓存机制
AntiX框架提供了强大的缓存支持,包括本地缓存和分布式缓存,帮助提高应用性能。
- // 启用缓存
- @Configuration
- @EnableCaching
- public class CacheConfig {
-
- @Bean
- public CacheManager cacheManager() {
- // 使用Redis作为分布式缓存
- RedisCacheManager.Builder builder = RedisCacheManager.builder(redisConnectionFactory())
- .cacheDefaults(cacheConfiguration())
- .withInitialCacheConfigurations(getCacheConfigurations());
-
- return builder.build();
- }
-
- @Bean
- public RedisConnectionFactory redisConnectionFactory() {
- return new LettuceConnectionFactory();
- }
-
- private RedisCacheConfiguration cacheConfiguration() {
- return RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofMinutes(30))
- .disableCachingNullValues()
- .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
- }
-
- private Map<String, RedisCacheConfiguration> getCacheConfigurations() {
- Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
-
- // 用户缓存,TTL为1小时
- cacheConfigurations.put("users", RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofHours(1))
- .disableCachingNullValues());
-
- // 产品缓存,TTL为2小时
- cacheConfigurations.put("products", RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofHours(2))
- .disableCachingNullValues());
-
- return cacheConfigurations;
- }
- }
- // 在服务中使用缓存
- @Service
- public class UserServiceImpl implements UserService {
- private final UserRepository userRepository;
-
- @Autowired
- public UserServiceImpl(UserRepository userRepository) {
- this.userRepository = userRepository;
- }
-
- @Override
- @Cacheable(value = "users", key = "#id")
- public User getUserById(Long id) {
- return userRepository.findById(id).orElse(null);
- }
-
- @Override
- @CacheEvict(value = "users", key = "#user.id")
- public void saveUser(User user) {
- userRepository.save(user);
- }
-
- @Override
- @CacheEvict(value = "users", allEntries = true)
- public void clearUserCache() {
- // 清除所有用户缓存
- }
- }
复制代码
6. 安全框架集成
AntiX框架提供了全面的安全支持,包括认证、授权、加密等功能,保护企业应用免受安全威胁。
- // 安全配置
- @Configuration
- @EnableWebSecurity
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Bean
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
-
- @Override
- protected void configure(AuthenticationManagerBuilder auth) throws Exception {
- auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .csrf().disable()
- .authorizeRequests()
- .antMatchers("/api/public/**").permitAll()
- .antMatchers("/api/admin/**").hasRole("ADMIN")
- .antMatchers("/api/user/**").hasAnyRole("USER", "ADMIN")
- .anyRequest().authenticated()
- .and()
- .sessionManagement()
- .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
- .and()
- .addFilter(new JwtAuthenticationFilter(authenticationManager()))
- .addFilter(new JwtAuthorizationFilter(authenticationManager()));
- }
- }
- // JWT认证过滤器
- public class JwtAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
-
- private final AuthenticationManager authenticationManager;
-
- public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
- this.authenticationManager = authenticationManager;
- setFilterProcessesUrl("/api/login");
- }
-
- @Override
- public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
- throws AuthenticationException {
- try {
- UserCredentials credentials = new ObjectMapper()
- .readValue(request.getInputStream(), UserCredentials.class);
-
- return authenticationManager.authenticate(
- new UsernamePasswordAuthenticationToken(
- credentials.getUsername(),
- credentials.getPassword(),
- new ArrayList<>())
- );
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- }
-
- @Override
- protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response,
- FilterChain chain, Authentication auth) throws IOException, ServletException {
- String token = Jwts.builder()
- .setSubject(((User) auth.getPrincipal()).getUsername())
- .setExpiration(new Date(System.currentTimeMillis() + 864_000_000)) // 10天
- .signWith(SignatureAlgorithm.HS512, "SecretKey".getBytes())
- .compact();
-
- response.addHeader("Authorization", "Bearer " + token);
- }
- }
- // 方法级安全
- @Service
- public class OrderServiceImpl implements OrderService {
-
- @PreAuthorize("hasRole('ADMIN') or #order.userId == authentication.principal.id")
- public Order getOrder(Order order) {
- // 获取订单逻辑
- }
-
- @PostAuthorize("returnObject.userId == authentication.principal.id")
- public Order findOrderById(Long orderId) {
- // 查找订单逻辑
- }
- }
复制代码
AntiX框架的最佳实践
1. 项目结构组织
良好的项目结构是构建可维护应用的基础。以下是AntiX框架推荐的项目结构:
- project-root/
- ├── src/
- │ ├── main/
- │ │ ├── java/
- │ │ │ └── com/
- │ │ │ └── example/
- │ │ │ └── application/
- │ │ │ ├── Application.java
- │ │ │ ├── config/
- │ │ │ │ ├── SecurityConfig.java
- │ │ │ │ ├── CacheConfig.java
- │ │ │ │ └── DatabaseConfig.java
- │ │ │ ├── controller/
- │ │ │ │ ├── UserController.java
- │ │ │ │ └── OrderController.java
- │ │ │ ├── service/
- │ │ │ │ ├── UserService.java
- │ │ │ │ ├── UserServiceImpl.java
- │ │ │ │ ├── OrderService.java
- │ │ │ │ └── OrderServiceImpl.java
- │ │ │ ├── repository/
- │ │ │ │ ├── UserRepository.java
- │ │ │ │ └── OrderRepository.java
- │ │ │ ├── model/
- │ │ │ │ ├── User.java
- │ │ │ │ └── Order.java
- │ │ │ ├── dto/
- │ │ │ │ ├── UserDto.java
- │ │ │ │ └── OrderDto.java
- │ │ │ ├── exception/
- │ │ │ │ ├── ResourceNotFoundException.java
- │ │ │ │ └── GlobalExceptionHandler.java
- │ │ │ └── util/
- │ │ │ └── DateUtils.java
- │ │ └── resources/
- │ │ ├── application.properties
- │ │ ├── application-dev.properties
- │ │ ├── application-prod.properties
- │ │ └── static/
- │ │ └── templates/
- │ └── test/
- │ └── java/
- │ └── com/
- │ └── example/
- │ └── application/
- │ ├── service/
- │ │ ├── UserServiceTest.java
- │ │ └── OrderServiceTest.java
- │ └── controller/
- │ ├── UserControllerTest.java
- │ └── OrderControllerTest.java
- ├── .gitignore
- ├── pom.xml
- └── README.md
复制代码
2. 配置管理
AntiX框架支持多种配置方式,推荐使用外部化配置,便于不同环境的部署和管理。
- # application.properties - 基础配置
- # 应用配置
- app.name=AntiX Application
- app.version=1.0.0
- # 服务器配置
- server.port=8080
- server.servlet.context-path=/api
- # 数据库配置
- spring.datasource.url=jdbc:mysql://localhost:3306/antix_db
- spring.datasource.username=root
- spring.datasource.password=password
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- # JPA配置
- spring.jpa.hibernate.ddl-auto=update
- spring.jpa.show-sql=true
- spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
- spring.jpa.properties.hibernate.format_sql=true
- # 日志配置
- logging.level.root=INFO
- logging.level.com.example.application=DEBUG
- logging.file.name=logs/antix-application.log
- # 环境特定配置
- spring.profiles.active=dev
复制代码- # application-dev.properties - 开发环境配置
- # 数据库配置
- spring.datasource.url=jdbc:mysql://localhost:3306/antix_db_dev
- spring.datasource.username=dev_user
- spring.datasource.password=dev_password
- # 日志配置
- logging.level.root=DEBUG
- logging.level.com.example.application=TRACE
- # 开发工具配置
- spring.devtools.restart.enabled=true
- spring.devtools.livereload.enabled=true
复制代码- # application-prod.properties - 生产环境配置
- # 数据库配置
- spring.datasource.url=jdbc:mysql://prod-db-host:3306/antix_db_prod
- spring.datasource.username=prod_user
- spring.datasource.password=${DB_PASSWORD:}
- # 日志配置
- logging.level.root=WARN
- logging.level.com.example.application=INFO
- logging.file.name=/var/log/antix/antix-application.log
- # 性能配置
- server.tomcat.max-threads=200
- server.tomcat.min-spare-threads=20
复制代码
3. 异常处理
统一的异常处理可以提高应用的健壮性和用户体验。
- // 自定义异常类
- public class ResourceNotFoundException extends RuntimeException {
- public ResourceNotFoundException(String message) {
- super(message);
- }
-
- public ResourceNotFoundException(String resourceName, String fieldName, Object fieldValue) {
- super(String.format("%s not found with %s: '%s'", resourceName, fieldName, fieldValue));
- }
- }
- // 全局异常处理器
- @ControllerAdvice
- public class GlobalExceptionHandler {
-
- private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
-
- // 处理资源未找到异常
- @ExceptionHandler(ResourceNotFoundException.class)
- public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException ex) {
- ErrorResponse errorResponse = new ErrorResponse(
- HttpStatus.NOT_FOUND.value(),
- ex.getMessage(),
- System.currentTimeMillis()
- );
-
- logger.error("Resource not found: {}", ex.getMessage());
- return new ResponseEntity<>(errorResponse, HttpStatus.NOT_FOUND);
- }
-
- // 处理验证异常
- @ExceptionHandler(MethodArgumentNotValidException.class)
- public ResponseEntity<ErrorResponse> handleValidationExceptions(MethodArgumentNotValidException ex) {
- List<String> errors = ex.getBindingResult()
- .getFieldErrors()
- .stream()
- .map(error -> error.getField() + ": " + error.getDefaultMessage())
- .collect(Collectors.toList());
-
- ErrorResponse errorResponse = new ErrorResponse(
- HttpStatus.BAD_REQUEST.value(),
- "Validation failed",
- errors,
- System.currentTimeMillis()
- );
-
- logger.error("Validation error: {}", errors);
- return new ResponseEntity<>(errorResponse, HttpStatus.BAD_REQUEST);
- }
-
- // 处理所有其他异常
- @ExceptionHandler(Exception.class)
- public ResponseEntity<ErrorResponse> handleAllExceptions(Exception ex) {
- ErrorResponse errorResponse = new ErrorResponse(
- HttpStatus.INTERNAL_SERVER_ERROR.value(),
- "An unexpected error occurred",
- System.currentTimeMillis()
- );
-
- logger.error("Unexpected error: {}", ex.getMessage(), ex);
- return new ResponseEntity<>(errorResponse, HttpStatus.INTERNAL_SERVER_ERROR);
- }
- }
- // 错误响应DTO
- public class ErrorResponse {
- private int status;
- private String message;
- private List<String> errors;
- private long timestamp;
-
- // 构造函数、getters和setters
- }
复制代码
4. 测试策略
全面的测试是确保应用质量的关键。AntiX框架支持多种测试类型,包括单元测试、集成测试和端到端测试。
5. 性能优化
性能优化是构建高效企业级应用的关键。以下是AntiX框架中的一些性能优化策略:
- // 使用缓存优化查询性能
- @Service
- public class ProductServiceImpl implements ProductService {
-
- private final ProductRepository productRepository;
-
- @Autowired
- public ProductServiceImpl(ProductRepository productRepository) {
- this.productRepository = productRepository;
- }
-
- @Override
- @Cacheable(value = "products", key = "#id")
- public Product getProductById(Long id) {
- return productRepository.findById(id).orElse(null);
- }
-
- @Override
- @Cacheable(value = "products", key = "'category:' + #category")
- public List<Product> getProductsByCategory(String category) {
- return productRepository.findByCategory(category);
- }
-
- @Override
- @Caching(
- put = @CachePut(value = "products", key = "#product.id"),
- evict = @CacheEvict(value = "products", key = "'category:' + #product.category")
- )
- public Product updateProduct(Product product) {
- return productRepository.save(product);
- }
- }
- // 使用异步处理提高吞吐量
- @Service
- public class NotificationServiceImpl implements NotificationService {
-
- private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
-
- @Override
- @Async
- public void sendEmail(String to, String subject, String body) {
- // 模拟发送邮件的耗时操作
- try {
- Thread.sleep(1000);
- logger.info("Email sent to {} with subject: {}", to, subject);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- @Async("taskExecutor")
- public Future<String> sendSms(String phoneNumber, String message) {
- // 模拟发送短信的耗时操作
- try {
- Thread.sleep(500);
- String result = "SMS sent to " + phoneNumber;
- logger.info(result);
- return new AsyncResult<>(result);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return new AsyncResult<>("Failed to send SMS due to interruption");
- }
- }
- }
- // 配置异步任务执行器
- @Configuration
- @EnableAsync
- public class AsyncConfig implements AsyncConfigurer {
-
- @Override
- public Executor getAsyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(5);
- executor.setMaxPoolSize(10);
- executor.setQueueCapacity(25);
- executor.setThreadNamePrefix("AntiX-Async-");
- executor.initialize();
- return executor;
- }
-
- @Bean(name = "taskExecutor")
- public Executor taskExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(10);
- executor.setMaxPoolSize(20);
- executor.setQueueCapacity(50);
- executor.setThreadNamePrefix("AntiX-Task-");
- executor.initialize();
- return executor;
- }
- }
复制代码
真实项目案例分析
案例1:电子商务平台
某大型零售企业需要构建一个高性能、高可用的电子商务平台,支持每日百万级别的用户访问和交易处理。平台需要包括商品管理、订单处理、用户管理、支付集成等核心功能。
1. 高并发处理:特别是在促销活动期间,系统需要处理大量并发请求
2. 数据一致性:确保订单、库存和支付数据的一致性
3. 系统扩展性:随着业务增长,系统需要能够水平扩展
4. 用户体验:确保页面加载速度和交易流程的流畅性
- // 商品服务
- @SpringBootApplication
- @EnableDiscoveryClient
- @EnableCaching
- public class ProductServiceApplication {
- public static void main(String[] args) {
- SpringApplication.run(ProductServiceApplication.class, args);
- }
- }
- // 订单服务
- @SpringBootApplication
- @EnableDiscoveryClient
- @EnableCaching
- public class OrderServiceApplication {
- public static void main(String[] args) {
- SpringApplication.run(OrderServiceApplication.class, args);
- }
- }
- // 用户服务
- @SpringBootApplication
- @EnableDiscoveryClient
- @EnableCaching
- public class UserServiceApplication {
- public static void main(String[] args) {
- SpringApplication.run(UserServiceApplication.class, args);
- }
- }
复制代码- // 使用分布式锁处理高并发场景
- @Service
- public class InventoryServiceImpl implements InventoryService {
-
- private final InventoryRepository inventoryRepository;
- private final RedisTemplate<String, String> redisTemplate;
-
- @Autowired
- public InventoryServiceImpl(InventoryRepository inventoryRepository, RedisTemplate<String, String> redisTemplate) {
- this.inventoryRepository = inventoryRepository;
- this.redisTemplate = redisTemplate;
- }
-
- @Override
- @Transactional
- public boolean reduceInventory(Long productId, int quantity) {
- String lockKey = "inventory_lock:" + productId;
- String requestId = UUID.randomUUID().toString();
-
- try {
- // 获取分布式锁
- boolean locked = acquireLock(lockKey, requestId, 10);
- if (!locked) {
- throw new BusinessException("Failed to acquire lock for product: " + productId);
- }
-
- // 检查库存
- Inventory inventory = inventoryRepository.findByProductId(productId);
- if (inventory == null || inventory.getQuantity() < quantity) {
- return false;
- }
-
- // 减少库存
- inventory.setQuantity(inventory.getQuantity() - quantity);
- inventoryRepository.save(inventory);
-
- return true;
- } finally {
- // 释放锁
- releaseLock(lockKey, requestId);
- }
- }
-
- private boolean acquireLock(String lockKey, String requestId, int expireTime) {
- return Boolean.TRUE.equals(redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS));
- }
-
- private boolean releaseLock(String lockKey, String requestId) {
- String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
- DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
- Long result = redisTemplate.execute(redisScript, Collections.singletonList(lockKey), requestId);
- return result != null && result == 1;
- }
- }
复制代码- // 订单创建事件
- public class OrderCreatedEvent {
- private final Order order;
- private final LocalDateTime createdAt;
-
- public OrderCreatedEvent(Order order) {
- this.order = order;
- this.createdAt = LocalDateTime.now();
- }
-
- // getters
- }
- // 订单服务发布事件
- @Service
- public class OrderServiceImpl implements OrderService {
-
- private final OrderRepository orderRepository;
- private final ApplicationEventPublisher eventPublisher;
-
- @Autowired
- public OrderServiceImpl(OrderRepository orderRepository, ApplicationEventPublisher eventPublisher) {
- this.orderRepository = orderRepository;
- this.eventPublisher = eventPublisher;
- }
-
- @Override
- @Transactional
- public Order createOrder(Order order) {
- // 保存订单
- order = orderRepository.save(order);
-
- // 发布订单创建事件
- eventPublisher.publishEvent(new OrderCreatedEvent(order));
-
- return order;
- }
- }
- // 库存服务监听事件
- @Service
- public class InventoryEventListener {
-
- private final InventoryService inventoryService;
-
- @Autowired
- public InventoryEventListener(InventoryService inventoryService) {
- this.inventoryService = inventoryService;
- }
-
- @EventListener
- @Async
- public void handleOrderCreatedEvent(OrderCreatedEvent event) {
- Order order = event.getOrder();
-
- // 减少库存
- for (OrderItem item : order.getItems()) {
- boolean success = inventoryService.reduceInventory(item.getProductId(), item.getQuantity());
- if (!success) {
- // 库存不足,处理回滚逻辑
- throw new InsufficientInventoryException("Insufficient inventory for product: " + item.getProductId());
- }
- }
- }
- }
- // 支付服务监听事件
- @Service
- public class PaymentEventListener {
-
- private final PaymentService paymentService;
-
- @Autowired
- public PaymentEventListener(PaymentService paymentService) {
- this.paymentService = paymentService;
- }
-
- @EventListener
- @Async
- public void handleOrderCreatedEvent(OrderCreatedEvent event) {
- Order order = event.getOrder();
-
- // 处理支付
- PaymentResult result = paymentService.processPayment(order);
- if (!result.isSuccess()) {
- // 支付失败,处理回滚逻辑
- throw new PaymentFailedException("Payment failed for order: " + order.getId());
- }
- }
- }
复制代码- // 商品缓存配置
- @Configuration
- @EnableCaching
- public class CacheConfig {
-
- @Bean
- public RedisCacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
- RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofMinutes(30))
- .disableCachingNullValues()
- .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
-
- // 商品缓存配置
- RedisCacheConfiguration productCacheConfig = RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofHours(1))
- .disableCachingNullValues()
- .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()));
-
- Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
- cacheConfigurations.put("products", productCacheConfig);
-
- return RedisCacheManager.builder(redisConnectionFactory)
- .cacheDefaults(defaultConfig)
- .withInitialCacheConfigurations(cacheConfigurations)
- .build();
- }
- }
- // 商品服务实现
- @Service
- public class ProductServiceImpl implements ProductService {
-
- private final ProductRepository productRepository;
-
- @Autowired
- public ProductServiceImpl(ProductRepository productRepository) {
- this.productRepository = productRepository;
- }
-
- @Override
- @Cacheable(value = "products", key = "#id")
- public Product getProductById(Long id) {
- return productRepository.findById(id).orElse(null);
- }
-
- @Override
- @Cacheable(value = "products", key = "'category:' + #category + ':page:' + #page + ':size:' + #size")
- public Page<Product> getProductsByCategory(String category, int page, int size) {
- Pageable pageable = PageRequest.of(page, size, Sort.by("name").ascending());
- return productRepository.findByCategory(category, pageable);
- }
-
- @Override
- @Caching(
- put = @CachePut(value = "products", key = "#product.id"),
- evict = {
- @CacheEvict(value = "products", key = "'category:' + #product.category + ':page:*'"),
- @CacheEvict(value = "products", key = "'featured'")
- }
- )
- public Product updateProduct(Product product) {
- return productRepository.save(product);
- }
-
- @Override
- @CacheEvict(value = "products", allEntries = true)
- public void refreshProductCache() {
- // 清除所有产品缓存
- }
- }
复制代码
通过使用AntiX框架,该电子商务平台成功实现了以下目标:
1. 高并发处理能力:系统能够平稳处理每秒5000+的请求峰值,促销活动期间无宕机情况
2. 数据一致性:通过分布式事务和事件驱动架构,确保了订单、库存和支付数据的一致性
3. 系统扩展性:采用微服务架构,各服务可独立扩展,系统整体吞吐量提升了3倍
4. 用户体验提升:页面加载时间从平均3秒减少到800毫秒,用户转化率提高了25%
案例2:金融风控系统
一家大型金融机构需要构建一个实时风控系统,用于检测和预防金融交易中的欺诈行为。系统需要能够实时分析大量交易数据,识别可疑模式,并采取相应措施。
1. 实时数据处理:需要在毫秒级别处理大量交易数据
2. 复杂规则引擎:需要实现灵活且高效的风控规则
3. 高可用性:系统需要7x24小时不间断运行
4. 数据安全:确保敏感金融数据的安全性和合规性
- // 交易事件处理器
- @Service
- public class TransactionEventHandler {
-
- private final RiskRuleEngine ruleEngine;
- private final AlertService alertService;
- private final TransactionRepository transactionRepository;
-
- @Autowired
- public TransactionEventHandler(RiskRuleEngine ruleEngine, AlertService alertService,
- TransactionRepository transactionRepository) {
- this.ruleEngine = ruleEngine;
- this.alertService = alertService;
- this.transactionRepository = transactionRepository;
- }
-
- @EventListener
- @Async("transactionProcessor")
- public void handleTransactionEvent(TransactionEvent event) {
- Transaction transaction = event.getTransaction();
-
- // 保存交易记录
- transactionRepository.save(transaction);
-
- // 执行风控规则
- RiskAssessmentResult result = ruleEngine.assessRisk(transaction);
-
- // 根据风险等级采取相应措施
- if (result.getRiskLevel() == RiskLevel.HIGH) {
- // 高风险交易,阻止并生成警报
- blockTransaction(transaction);
- alertService.createHighRiskAlert(transaction, result);
- } else if (result.getRiskLevel() == RiskLevel.MEDIUM) {
- // 中等风险交易,需要人工审核
- alertService.createMediumRiskAlert(transaction, result);
- }
-
- // 更新交易状态
- updateTransactionStatus(transaction, result);
- }
-
- private void blockTransaction(Transaction transaction) {
- // 阻止交易的逻辑
- transaction.setStatus(TransactionStatus.BLOCKED);
- transactionRepository.save(transaction);
- }
-
- private void updateTransactionStatus(Transaction transaction, RiskAssessmentResult result) {
- // 更新交易状态的逻辑
- if (transaction.getStatus() != TransactionStatus.BLOCKED) {
- transaction.setStatus(TransactionStatus.COMPLETED);
- transaction.setRiskScore(result.getScore());
- transactionRepository.save(transaction);
- }
- }
- }
- // 配置异步任务处理器
- @Configuration
- @EnableAsync
- public class AsyncConfig {
-
- @Bean(name = "transactionProcessor")
- public Executor transactionProcessor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(10);
- executor.setMaxPoolSize(50);
- executor.setQueueCapacity(1000);
- executor.setThreadNamePrefix("TransactionProcessor-");
- executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
- executor.initialize();
- return executor;
- }
- }
复制代码- // 风控规则接口
- public interface RiskRule {
- String getName();
- RiskAssessmentResult evaluate(Transaction transaction);
- }
- // 规则引擎实现
- @Service
- public class RiskRuleEngineImpl implements RiskRuleEngine {
-
- private final List<RiskRule> rules;
-
- @Autowired
- public RiskRuleEngineImpl(List<RiskRule> rules) {
- this.rules = rules;
- }
-
- @Override
- public RiskAssessmentResult assessRisk(Transaction transaction) {
- int totalScore = 0;
- List<String> triggeredRules = new ArrayList<>();
-
- // 执行所有规则
- for (RiskRule rule : rules) {
- RiskAssessmentResult result = rule.evaluate(transaction);
- if (result.getScore() > 0) {
- totalScore += result.getScore();
- triggeredRules.add(rule.getName());
- }
- }
-
- // 确定风险等级
- RiskLevel riskLevel = determineRiskLevel(totalScore);
-
- return new RiskAssessmentResult(totalScore, riskLevel, triggeredRules);
- }
-
- private RiskLevel determineRiskLevel(int score) {
- if (score >= 80) {
- return RiskLevel.HIGH;
- } else if (score >= 50) {
- return RiskLevel.MEDIUM;
- } else {
- return RiskLevel.LOW;
- }
- }
- }
- // 示例规则:大额交易检测
- @Component
- public class LargeAmountRule implements RiskRule {
-
- private static final int THRESHOLD = 10000; // 10,000元
- private static final int SCORE = 30;
-
- @Override
- public String getName() {
- return "LargeAmountRule";
- }
-
- @Override
- public RiskAssessmentResult evaluate(Transaction transaction) {
- if (transaction.getAmount().compareTo(BigDecimal.valueOf(THRESHOLD)) > 0) {
- return new RiskAssessmentResult(SCORE, RiskLevel.MEDIUM, Collections.singletonList(getName()));
- }
- return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
- }
- }
- // 示例规则:异常地点检测
- @Component
- public class UnusualLocationRule implements RiskRule {
-
- private final UserLocationHistoryRepository locationHistoryRepository;
-
- @Autowired
- public UnusualLocationRule(UserLocationHistoryRepository locationHistoryRepository) {
- this.locationHistoryRepository = locationHistoryRepository;
- }
-
- @Override
- public String getName() {
- return "UnusualLocationRule";
- }
-
- @Override
- public RiskAssessmentResult evaluate(Transaction transaction) {
- // 获取用户历史交易地点
- List<String> usualLocations = locationHistoryRepository.findFrequentLocations(transaction.getUserId());
-
- // 检查当前交易地点是否在常见地点中
- if (!usualLocations.contains(transaction.getLocation())) {
- return new RiskAssessmentResult(40, RiskLevel.MEDIUM, Collections.singletonList(getName()));
- }
- return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
- }
- }
- // 示例规则:高频交易检测
- @Component
- public class HighFrequencyRule implements RiskRule {
-
- private final TransactionRepository transactionRepository;
-
- @Autowired
- public HighFrequencyRule(TransactionRepository transactionRepository) {
- this.transactionRepository = transactionRepository;
- }
-
- @Override
- public String getName() {
- return "HighFrequencyRule";
- }
-
- @Override
- public RiskAssessmentResult evaluate(Transaction transaction) {
- // 检查过去1小时内的交易次数
- LocalDateTime oneHourAgo = LocalDateTime.now().minusHours(1);
- int transactionCount = transactionRepository.countByUserIdAndTimeAfter(
- transaction.getUserId(), oneHourAgo);
-
- // 如果过去1小时内交易超过5次,认为是高频交易
- if (transactionCount > 5) {
- return new RiskAssessmentResult(50, RiskLevel.HIGH, Collections.singletonList(getName()));
- }
- return new RiskAssessmentResult(0, RiskLevel.LOW, Collections.emptyList());
- }
- }
复制代码- // 健康检查端点
- @RestController
- @RequestMapping("/api/health")
- public class HealthCheckController {
-
- private final DatabaseHealthIndicator databaseHealthIndicator;
- private final RedisHealthIndicator redisHealthIndicator;
- private final KafkaHealthIndicator kafkaHealthIndicator;
-
- @Autowired
- public HealthCheckController(DatabaseHealthIndicator databaseHealthIndicator,
- RedisHealthIndicator redisHealthIndicator,
- KafkaHealthIndicator kafkaHealthIndicator) {
- this.databaseHealthIndicator = databaseHealthIndicator;
- this.redisHealthIndicator = redisHealthIndicator;
- this.kafkaHealthIndicator = kafkaHealthIndicator;
- }
-
- @GetMapping
- public ResponseEntity<Map<String, Object>> health() {
- Map<String, Object> healthStatus = new HashMap<>();
-
- // 检查数据库状态
- Health dbHealth = databaseHealthIndicator.health();
- healthStatus.put("database", dbHealth.getStatus());
-
- // 检查Redis状态
- Health redisHealth = redisHealthIndicator.health();
- healthStatus.put("redis", redisHealth.getStatus());
-
- // 检查Kafka状态
- Health kafkaHealth = kafkaHealthIndicator.health();
- healthStatus.put("kafka", kafkaHealth.getStatus());
-
- // 确定整体状态
- Status overallStatus = Status.UP;
- for (Object status : healthStatus.values()) {
- if (status != Status.UP) {
- overallStatus = Status.DOWN;
- break;
- }
- }
-
- healthStatus.put("status", overallStatus);
- healthStatus.put("timestamp", System.currentTimeMillis());
-
- HttpStatus httpStatus = overallStatus == Status.UP ? HttpStatus.OK : HttpStatus.SERVICE_UNAVAILABLE;
- return ResponseEntity.status(httpStatus).body(healthStatus);
- }
- }
- // 数据库健康指示器
- @Component
- public class DatabaseHealthIndicator implements HealthIndicator {
-
- private final DataSource dataSource;
-
- @Autowired
- public DatabaseHealthIndicator(DataSource dataSource) {
- this.dataSource = dataSource;
- }
-
- @Override
- public Health health() {
- try (Connection connection = dataSource.getConnection()) {
- if (connection.isValid(1)) {
- return Health.up().withDetail("database", "Available").build();
- } else {
- return Health.down().withDetail("database", "Connection is not valid").build();
- }
- } catch (SQLException e) {
- return Health.down().withException(e).build();
- }
- }
- }
- // Redis健康指示器
- @Component
- public class RedisHealthIndicator implements HealthIndicator {
-
- private final RedisConnectionFactory redisConnectionFactory;
-
- @Autowired
- public RedisHealthIndicator(RedisConnectionFactory redisConnectionFactory) {
- this.redisConnectionFactory = redisConnectionFactory;
- }
-
- @Override
- public Health health() {
- try {
- RedisConnection connection = redisConnectionFactory.getConnection();
- String info = connection.info();
- connection.close();
-
- return Health.up().withDetail("redis", "Available").build();
- } catch (Exception e) {
- return Health.down().withException(e).build();
- }
- }
- }
- // 断路器模式实现
- @Service
- public class ExternalRiskServiceProxy {
-
- private final ExternalRiskService externalRiskService;
- private final CircuitBreaker circuitBreaker;
-
- @Autowired
- public ExternalRiskServiceProxy(ExternalRiskService externalRiskService) {
- this.externalRiskService = externalRiskService;
-
- // 配置断路器
- CircuitBreakerConfig config = CircuitBreakerConfig.custom()
- .failureRateThreshold(50)
- .waitDurationInOpenState(Duration.ofSeconds(30))
- .ringBufferSizeInHalfOpenState(10)
- .ringBufferSizeInClosedState(100)
- .build();
-
- this.circuitBreaker = CircuitBreaker.of("externalRiskService", config);
- }
-
- public RiskData getExternalRiskData(String userId) {
- return circuitBreaker.executeSupplier(() -> externalRiskService.getRiskData(userId));
- }
- }
复制代码- // 数据加密服务
- @Service
- public class EncryptionServiceImpl implements EncryptionService {
-
- private final String encryptionKey;
-
- @Autowired
- public EncryptionServiceImpl(@Value("${app.encryption.key}") String encryptionKey) {
- this.encryptionKey = encryptionKey;
- }
-
- @Override
- public String encrypt(String data) {
- try {
- Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
- SecretKeySpec keySpec = new SecretKeySpec(encryptionKey.getBytes(), "AES");
- GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, new byte[12]);
-
- cipher.init(Cipher.ENCRYPT_MODE, keySpec, gcmParameterSpec);
- byte[] encryptedData = cipher.doFinal(data.getBytes());
-
- return Base64.getEncoder().encodeToString(encryptedData);
- } catch (Exception e) {
- throw new EncryptionException("Failed to encrypt data", e);
- }
- }
-
- @Override
- public String decrypt(String encryptedData) {
- try {
- Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
- SecretKeySpec keySpec = new SecretKeySpec(encryptionKey.getBytes(), "AES");
- GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, new byte[12]);
-
- cipher.init(Cipher.DECRYPT_MODE, keySpec, gcmParameterSpec);
- byte[] decodedData = Base64.getDecoder().decode(encryptedData);
- byte[] decryptedData = cipher.doFinal(decodedData);
-
- return new String(decryptedData);
- } catch (Exception e) {
- throw new EncryptionException("Failed to decrypt data", e);
- }
- }
- }
- // 敏感数据处理器
- @Aspect
- @Component
- public class SensitiveDataAspect {
-
- private final EncryptionService encryptionService;
-
- @Autowired
- public SensitiveDataAspect(EncryptionService encryptionService) {
- this.encryptionService = encryptionService;
- }
-
- @Around("@annotation(SensitiveData)")
- public Object handleSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
- Object result = joinPoint.proceed();
-
- // 处理返回结果中的敏感数据
- if (result instanceof Transaction) {
- Transaction transaction = (Transaction) result;
- // 加密敏感字段
- if (transaction.getCardNumber() != null) {
- transaction.setCardNumber(encryptionService.encrypt(transaction.getCardNumber()));
- }
- if (transaction.getAccountNumber() != null) {
- transaction.setAccountNumber(encryptionService.encrypt(transaction.getAccountNumber()));
- }
- }
-
- return result;
- }
- }
- // 审计日志服务
- @Service
- public class AuditLogServiceImpl implements AuditLogService {
-
- private final AuditLogRepository auditLogRepository;
-
- @Autowired
- public AuditLogServiceImpl(AuditLogRepository auditLogRepository) {
- this.auditLogRepository = auditLogRepository;
- }
-
- @Override
- @Async
- public void logAction(String userId, String action, String details) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(userId);
- auditLog.setAction(action);
- auditLog.setDetails(details);
- auditLog.setTimestamp(LocalDateTime.now());
-
- auditLogRepository.save(auditLog);
- }
-
- @Override
- public Page<AuditLog> getAuditLogs(String userId, LocalDateTime startTime, LocalDateTime endTime,
- Pageable pageable) {
- if (startTime != null && endTime != null) {
- return auditLogRepository.findByUserIdAndTimestampBetween(userId, startTime, endTime, pageable);
- } else if (startTime != null) {
- return auditLogRepository.findByUserIdAndTimestampAfter(userId, startTime, pageable);
- } else if (endTime != null) {
- return auditLogRepository.findByUserIdAndTimestampBefore(userId, endTime, pageable);
- } else {
- return auditLogRepository.findByUserId(userId, pageable);
- }
- }
- }
复制代码
通过使用AntiX框架,该金融风控系统成功实现了以下目标:
1. 实时处理能力:系统能够在100毫秒内完成交易风险评估,支持每秒10000+的交易处理量
2. 灵活的规则引擎:实现了可插拔的风控规则,新规则可在不重启系统的情况下动态加载
3. 高可用性:系统实现了99.99%的可用性,全年非计划停机时间不超过52分钟
4. 数据安全合规:所有敏感数据均加密存储,系统通过了金融行业的安全合规审计
构建稳定高效企业级应用的策略
1. 架构设计原则
AntiX框架支持领域驱动设计方法,帮助开发团队构建与业务领域紧密匹配的应用架构。
- // 值对象 - 金额
- public class Money {
- private final BigDecimal amount;
- private final Currency currency;
-
- public Money(BigDecimal amount, Currency currency) {
- if (amount == null || currency == null) {
- throw new IllegalArgumentException("Amount and currency cannot be null");
- }
- if (amount.compareTo(BigDecimal.ZERO) < 0) {
- throw new IllegalArgumentException("Amount cannot be negative");
- }
-
- this.amount = amount;
- this.currency = currency;
- }
-
- // 业务方法
- public Money add(Money other) {
- if (!this.currency.equals(other.currency)) {
- throw new IllegalArgumentException("Cannot add money with different currencies");
- }
- return new Money(this.amount.add(other.amount), this.currency);
- }
-
- public Money subtract(Money other) {
- if (!this.currency.equals(other.currency)) {
- throw new IllegalArgumentException("Cannot subtract money with different currencies");
- }
- BigDecimal newAmount = this.amount.subtract(other.amount);
- if (newAmount.compareTo(BigDecimal.ZERO) < 0) {
- throw new IllegalArgumentException("Insufficient funds");
- }
- return new Money(newAmount, this.currency);
- }
-
- // getters
- }
- // 聚合根 - 订单
- @Entity
- @Table(name = "orders")
- public class Order {
- @Id
- @GeneratedValue(strategy = GenerationType.IDENTITY)
- private Long id;
-
- @Embedded
- private OrderId orderId;
-
- @Embedded
- private CustomerId customerId;
-
- @ElementCollection
- @CollectionTable(name = "order_items", joinColumns = @JoinColumn(name = "order_id"))
- private List<OrderItem> items = new ArrayList<>();
-
- @Embedded
- private Money totalAmount;
-
- @Enumerated(EnumType.STRING)
- private OrderStatus status;
-
- @CreationTimestamp
- private LocalDateTime createdAt;
-
- @UpdateTimestamp
- private LocalDateTime updatedAt;
-
- // 业务方法
- public void addItem(Product product, int quantity) {
- if (status != OrderStatus.NEW) {
- throw new IllegalStateException("Cannot add items to an order that is not in NEW status");
- }
-
- OrderItem item = new OrderItem(product.getId(), product.getName(), product.getPrice(), quantity);
- items.add(item);
- recalculateTotal();
- }
-
- public void removeItem(Long productId) {
- if (status != OrderStatus.NEW) {
- throw new IllegalStateException("Cannot remove items from an order that is not in NEW status");
- }
-
- items.removeIf(item -> item.getProductId().equals(productId));
- recalculateTotal();
- }
-
- public void confirm() {
- if (items.isEmpty()) {
- throw new IllegalStateException("Cannot confirm an empty order");
- }
- this.status = OrderStatus.CONFIRMED;
- }
-
- public void cancel() {
- if (status == OrderStatus.SHIPPED || status == OrderStatus.DELIVERED) {
- throw new IllegalStateException("Cannot cancel an order that has been shipped or delivered");
- }
- this.status = OrderStatus.CANCELLED;
- }
-
- private void recalculateTotal() {
- BigDecimal total = items.stream()
- .map(item -> item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity())))
- .reduce(BigDecimal.ZERO, BigDecimal::add);
-
- this.totalAmount = new Money(total, items.get(0).getUnitPrice().getCurrency());
- }
-
- // getters
- }
- // 仓储接口
- public interface OrderRepository {
- Order save(Order order);
- Optional<Order> findById(OrderId orderId);
- List<Order> findByCustomerId(CustomerId customerId);
- }
- // 仓储实现
- @Repository
- public class OrderRepositoryImpl implements OrderRepository {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Override
- public Order save(Order order) {
- if (order.getId() == null) {
- entityManager.persist(order);
- return order;
- } else {
- return entityManager.merge(order);
- }
- }
-
- @Override
- public Optional<Order> findById(OrderId orderId) {
- try {
- Order order = entityManager.createQuery(
- "SELECT o FROM Order o WHERE o.orderId = :orderId", Order.class)
- .setParameter("orderId", orderId)
- .getSingleResult();
- return Optional.of(order);
- } catch (NoResultException e) {
- return Optional.empty();
- }
- }
-
- @Override
- public List<Order> findByCustomerId(CustomerId customerId) {
- return entityManager.createQuery(
- "SELECT o FROM Order o WHERE o.customerId = :customerId", Order.class)
- .setParameter("customerId", customerId)
- .getResultList();
- }
- }
- // 应用服务
- @Service
- @Transactional
- public class OrderApplicationService {
-
- private final OrderRepository orderRepository;
- private final ProductRepository productRepository;
- private final OrderEventPublisher eventPublisher;
-
- @Autowired
- public OrderApplicationService(OrderRepository orderRepository,
- ProductRepository productRepository,
- OrderEventPublisher eventPublisher) {
- this.orderRepository = orderRepository;
- this.productRepository = productRepository;
- this.eventPublisher = eventPublisher;
- }
-
- public OrderId createOrder(CustomerId customerId) {
- Order order = new Order(OrderId.generate(), customerId);
- orderRepository.save(order);
-
- // 发布订单创建事件
- eventPublisher.publishOrderCreatedEvent(order);
-
- return order.getOrderId();
- }
-
- public void addProductToOrder(OrderId orderId, ProductId productId, int quantity) {
- Order order = orderRepository.findById(orderId)
- .orElseThrow(() -> new OrderNotFoundException(orderId));
-
- Product product = productRepository.findById(productId)
- .orElseThrow(() -> new ProductNotFoundException(productId));
-
- order.addItem(product, quantity);
- orderRepository.save(order);
-
- // 发布订单更新事件
- eventPublisher.publishOrderUpdatedEvent(order);
- }
-
- public void confirmOrder(OrderId orderId) {
- Order order = orderRepository.findById(orderId)
- .orElseThrow(() -> new OrderNotFoundException(orderId));
-
- order.confirm();
- orderRepository.save(order);
-
- // 发布订单确认事件
- eventPublisher.publishOrderConfirmedEvent(order);
- }
- }
复制代码
AntiX框架支持构建微服务架构,使应用能够模块化、可扩展且易于维护。
- // 用户服务API
- @FeignClient(name = "user-service", path = "/api/users")
- public interface UserServiceClient {
-
- @GetMapping("/{id}")
- ResponseEntity<UserDto> getUserById(@PathVariable("id") Long id);
-
- @GetMapping("/search")
- ResponseEntity<List<UserDto>> searchUsers(@RequestParam("query") String query);
-
- @PostMapping
- ResponseEntity<UserDto> createUser(@RequestBody UserCreateDto userCreateDto);
-
- @PutMapping("/{id}")
- ResponseEntity<UserDto> updateUser(@PathVariable("id") Long id, @RequestBody UserUpdateDto userUpdateDto);
-
- @DeleteMapping("/{id}")
- ResponseEntity<Void> deleteUser(@PathVariable("id") Long id);
- }
- // 产品服务API
- @FeignClient(name = "product-service", path = "/api/products")
- public interface ProductServiceClient {
-
- @GetMapping("/{id}")
- ResponseEntity<ProductDto> getProductById(@PathVariable("id") Long id);
-
- @GetMapping("/category/{category}")
- ResponseEntity<List<ProductDto>> getProductsByCategory(@PathVariable("category") String category);
-
- @GetMapping("/search")
- ResponseEntity<Page<ProductDto>> searchProducts(@RequestParam("query") String query,
- @RequestParam("page") int page,
- @RequestParam("size") int size);
-
- @PostMapping
- ResponseEntity<ProductDto> createProduct(@RequestBody ProductCreateDto productCreateDto);
-
- @PutMapping("/{id}")
- ResponseEntity<ProductDto> updateProduct(@PathVariable("id") Long id, @RequestBody ProductUpdateDto productUpdateDto);
-
- @DeleteMapping("/{id}")
- ResponseEntity<Void> deleteProduct(@PathVariable("id") Long id);
- }
- // 订单服务实现
- @Service
- public class OrderServiceImpl implements OrderService {
-
- private final OrderRepository orderRepository;
- private final UserServiceClient userServiceClient;
- private final ProductServiceClient productServiceClient;
- private final OrderEventPublisher eventPublisher;
-
- @Autowired
- public OrderServiceImpl(OrderRepository orderRepository,
- UserServiceClient userServiceClient,
- ProductServiceClient productServiceClient,
- OrderEventPublisher eventPublisher) {
- this.orderRepository = orderRepository;
- this.userServiceClient = userServiceClient;
- this.productServiceClient = productServiceClient;
- this.eventPublisher = eventPublisher;
- }
-
- @Override
- @Transactional
- public OrderDto createOrder(Long userId, List<OrderItemCreateDto> items) {
- // 验证用户存在
- ResponseEntity<UserDto> userResponse = userServiceClient.getUserById(userId);
- if (!userResponse.getStatusCode().is2xxSuccessful() || userResponse.getBody() == null) {
- throw new UserNotFoundException(userId);
- }
-
- // 创建订单
- Order order = new Order();
- order.setUserId(userId);
- order.setStatus(OrderStatus.NEW);
- order.setCreatedAt(LocalDateTime.now());
-
- // 添加订单项
- for (OrderItemCreateDto itemDto : items) {
- // 验证产品存在
- ResponseEntity<ProductDto> productResponse = productServiceClient.getProductById(itemDto.getProductId());
- if (!productResponse.getStatusCode().is2xxSuccessful() || productResponse.getBody() == null) {
- throw new ProductNotFoundException(itemDto.getProductId());
- }
-
- ProductDto product = productResponse.getBody();
- OrderItem item = new OrderItem();
- item.setProductId(product.getId());
- item.setProductName(product.getName());
- item.setUnitPrice(product.getPrice());
- item.setQuantity(itemDto.getQuantity());
- item.setTotalPrice(product.getPrice().multiply(BigDecimal.valueOf(itemDto.getQuantity())));
-
- order.addItem(item);
- }
-
- // 计算总金额
- order.calculateTotal();
-
- // 保存订单
- order = orderRepository.save(order);
-
- // 发布订单创建事件
- eventPublisher.publishOrderCreatedEvent(order);
-
- // 转换为DTO并返回
- return convertToDto(order);
- }
-
- @Override
- public OrderDto getOrderById(Long id) {
- Order order = orderRepository.findById(id)
- .orElseThrow(() -> new OrderNotFoundException(id));
-
- return convertToDto(order);
- }
-
- @Override
- public Page<OrderDto> getOrdersByUserId(Long userId, int page, int size) {
- Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
- Page<Order> orders = orderRepository.findByUserId(userId, pageable);
-
- return orders.map(this::convertToDto);
- }
-
- private OrderDto convertToDto(Order order) {
- OrderDto dto = new OrderDto();
- dto.setId(order.getId());
- dto.setUserId(order.getUserId());
- dto.setStatus(order.getStatus());
- dto.setTotalAmount(order.getTotalAmount());
- dto.setItems(order.getItems().stream()
- .map(this::convertItemToDto)
- .collect(Collectors.toList()));
- dto.setCreatedAt(order.getCreatedAt());
- dto.setUpdatedAt(order.getUpdatedAt());
-
- return dto;
- }
-
- private OrderItemDto convertItemToDto(OrderItem item) {
- OrderItemDto dto = new OrderItemDto();
- dto.setProductId(item.getProductId());
- dto.setProductName(item.getProductName());
- dto.setUnitPrice(item.getUnitPrice());
- dto.setQuantity(item.getQuantity());
- dto.setTotalPrice(item.getTotalPrice());
-
- return dto;
- }
- }
- // 服务网关配置
- @Configuration
- public class GatewayConfig {
-
- @Bean
- public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
- return builder.routes()
- .route("user-service", r -> r.path("/api/users/**")
- .uri("lb://user-service"))
- .route("product-service", r -> r.path("/api/products/**")
- .uri("lb://product-service"))
- .route("order-service", r -> r.path("/api/orders/**")
- .uri("lb://order-service"))
- .build();
- }
- }
复制代码
2. 性能优化策略
- // 多级缓存配置
- @Configuration
- @EnableCaching
- public class CacheConfig {
-
- @Bean
- public CacheManager cacheManager() {
- CompositeCacheManager cacheManager = new CompositeCacheManager(
- caffeineCacheManager(),
- redisCacheManager()
- );
- cacheManager.setFallbackToNoOpCache(false);
- return cacheManager;
- }
-
- @Bean
- public CaffeineCacheManager caffeineCacheManager() {
- CaffeineCacheManager cacheManager = new CaffeineCacheManager();
- cacheManager.setCaffeine(Caffeine.newBuilder()
- .initialCapacity(100)
- .maximumSize(1000)
- .expireAfterWrite(5, TimeUnit.MINUTES));
- return cacheManager;
- }
-
- @Bean
- public RedisCacheManager redisCacheManager() {
- RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
- .entryTtl(Duration.ofHours(1))
- .disableCachingNullValues()
- .serializeValuesWith(RedisSerializationContext.SerializationPair
- .fromSerializer(new GenericJackson2JsonRedisSerializer()));
-
- return RedisCacheManager.builder(redisConnectionFactory())
- .cacheDefaults(config)
- .build();
- }
-
- @Bean
- public RedisConnectionFactory redisConnectionFactory() {
- return new LettuceConnectionFactory();
- }
- }
- // 缓存使用示例
- @Service
- public class ProductServiceImpl implements ProductService {
-
- private final ProductRepository productRepository;
-
- @Autowired
- public ProductServiceImpl(ProductRepository productRepository) {
- this.productRepository = productRepository;
- }
-
- @Override
- @Cacheable(value = "products", key = "#id", unless = "#result == null")
- public Product getProductById(Long id) {
- return productRepository.findById(id).orElse(null);
- }
-
- @Override
- @Cacheable(value = "products", key = "'category:' + #category + ':page:' + #page + ':size:' + #size")
- public Page<Product> getProductsByCategory(String category, int page, int size) {
- Pageable pageable = PageRequest.of(page, size);
- return productRepository.findByCategory(category, pageable);
- }
-
- @Override
- @Caching(
- put = @CachePut(value = "products", key = "#product.id"),
- evict = {
- @CacheEvict(value = "products", key = "'category:' + #product.category + ':page:*'"),
- @CacheEvict(value = "products", key = "'featured'")
- }
- )
- public Product updateProduct(Product product) {
- return productRepository.save(product);
- }
-
- @Override
- @CacheEvict(value = "products", allEntries = true)
- public void refreshProductCache() {
- // 清除所有产品缓存
- }
- }
复制代码- // 异步服务配置
- @Configuration
- @EnableAsync
- public class AsyncConfig implements AsyncConfigurer {
-
- @Override
- public Executor getAsyncExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(5);
- executor.setMaxPoolSize(10);
- executor.setQueueCapacity(25);
- executor.setThreadNamePrefix("AntiX-Async-");
- executor.initialize();
- return executor;
- }
-
- @Override
- public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
- return new CustomAsyncExceptionHandler();
- }
- }
- // 自定义异步异常处理器
- public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
-
- private static final Logger logger = LoggerFactory.getLogger(CustomAsyncExceptionHandler.class);
-
- @Override
- public void handleUncaughtException(Throwable ex, Method method, Object... params) {
- logger.error("Exception in async method: {}", method.getName(), ex);
-
- // 可以在这里添加通知逻辑,如发送邮件、短信等
- }
- }
- // 异步服务实现
- @Service
- public class NotificationServiceImpl implements NotificationService {
-
- private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
-
- @Override
- @Async
- public void sendEmail(String to, String subject, String body) {
- try {
- // 模拟发送邮件的耗时操作
- Thread.sleep(1000);
- logger.info("Email sent to {} with subject: {}", to, subject);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
-
- @Override
- @Async("taskExecutor")
- public Future<String> sendSms(String phoneNumber, String message) {
- try {
- // 模拟发送短信的耗时操作
- Thread.sleep(500);
- String result = "SMS sent to " + phoneNumber;
- logger.info(result);
- return new AsyncResult<>(result);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- return new AsyncResult<>("Failed to send SMS due to interruption");
- }
- }
-
- @Override
- @Async
- public void sendPushNotification(String userId, String title, String message) {
- try {
- // 模拟发送推送通知的耗时操作
- Thread.sleep(300);
- logger.info("Push notification sent to user {} with title: {}", userId, title);
- } catch (InterruptedException e) {
- Thread.currentThread().interrupt();
- }
- }
- }
复制代码- // 数据库配置
- @Configuration
- @EnableJpaRepositories(basePackages = "com.example.antix.repository")
- @EnableTransactionManagement
- public class DatabaseConfig {
-
- @Bean
- @Primary
- @ConfigurationProperties(prefix = "spring.datasource")
- public DataSource dataSource() {
- return DataSourceBuilder.create().type(HikariDataSource.class).build();
- }
-
- @Bean
- public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
- LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
- em.setDataSource(dataSource());
- em.setPackagesToScan("com.example.antix.model");
-
- HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
- em.setJpaVendorAdapter(vendorAdapter);
-
- Properties properties = new Properties();
- properties.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL8Dialect");
- properties.setProperty("hibernate.show_sql", "false");
- properties.setProperty("hibernate.format_sql", "false");
- properties.setProperty("hibernate.hbm2ddl.auto", "none");
- properties.setProperty("hibernate.jdbc.batch_size", "30");
- properties.setProperty("hibernate.order_inserts", "true");
- properties.setProperty("hibernate.order_updates", "true");
- properties.setProperty("hibernate.jdbc.fetch_size", "100");
- properties.setProperty("hibernate.cache.use_second_level_cache", "true");
- properties.setProperty("hibernate.cache.use_query_cache", "true");
- properties.setProperty("hibernate.cache.region.factory_class", "org.hibernate.cache.ehcache.EhCacheRegionFactory");
- properties.setProperty("hibernate.cache.provider_configuration_file_resource_path", "classpath:ehcache.xml");
-
- em.setJpaProperties(properties);
-
- return em;
- }
-
- @Bean
- public PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
- JpaTransactionManager transactionManager = new JpaTransactionManager();
- transactionManager.setEntityManagerFactory(entityManagerFactory);
- return transactionManager;
- }
- }
- // 批量操作示例
- @Service
- public class ProductBatchServiceImpl implements ProductBatchService {
-
- private final ProductRepository productRepository;
- private final EntityManager entityManager;
-
- @Autowired
- public ProductBatchServiceImpl(ProductRepository productRepository, EntityManager entityManager) {
- this.productRepository = productRepository;
- this.entityManager = entityManager;
- }
-
- @Override
- @Transactional
- public void batchInsertProducts(List<Product> products) {
- final int batchSize = 30;
-
- for (int i = 0; i < products.size(); i++) {
- Product product = products.get(i);
- entityManager.persist(product);
-
- if (i > 0 && i % batchSize == 0) {
- // 刷新并清除会话,避免内存溢出
- entityManager.flush();
- entityManager.clear();
- }
- }
-
- // 刷新剩余的记录
- entityManager.flush();
- entityManager.clear();
- }
-
- @Override
- @Transactional
- public void batchUpdateProducts(List<Product> products) {
- final int batchSize = 30;
-
- for (int i = 0; i < products.size(); i++) {
- Product product = products.get(i);
- entityManager.merge(product);
-
- if (i > 0 && i % batchSize == 0) {
- // 刷新并清除会话,避免内存溢出
- entityManager.flush();
- entityManager.clear();
- }
- }
-
- // 刷新剩余的记录
- entityManager.flush();
- entityManager.clear();
- }
-
- @Override
- @Transactional
- public void batchDeleteProducts(List<Long> productIds) {
- final int batchSize = 30;
-
- for (int i = 0; i < productIds.size(); i++) {
- Long productId = productIds.get(i);
- Product product = entityManager.find(Product.class, productId);
- if (product != null) {
- entityManager.remove(product);
- }
-
- if (i > 0 && i % batchSize == 0) {
- // 刷新并清除会话,避免内存溢出
- entityManager.flush();
- entityManager.clear();
- }
- }
-
- // 刷新剩余的记录
- entityManager.flush();
- entityManager.clear();
- }
- }
- // 查询优化示例
- @Repository
- public class ProductRepositoryImpl implements ProductRepositoryCustom {
-
- @PersistenceContext
- private EntityManager entityManager;
-
- @Override
- public List<Product> findProductsByCriteria(ProductSearchCriteria criteria) {
- CriteriaBuilder cb = entityManager.getCriteriaBuilder();
- CriteriaQuery<Product> query = cb.createQuery(Product.class);
- Root<Product> product = query.from(Product.class);
-
- List<Predicate> predicates = new ArrayList<>();
-
- // 添加名称过滤条件
- if (StringUtils.hasText(criteria.getName())) {
- predicates.add(cb.like(product.get("name"), "%" + criteria.getName() + "%"));
- }
-
- // 添加类别过滤条件
- if (StringUtils.hasText(criteria.getCategory())) {
- predicates.add(cb.equal(product.get("category"), criteria.getCategory()));
- }
-
- // 添加价格范围过滤条件
- if (criteria.getMinPrice() != null) {
- predicates.add(cb.ge(product.get("price"), criteria.getMinPrice()));
- }
- if (criteria.getMaxPrice() != null) {
- predicates.add(cb.le(product.get("price"), criteria.getMaxPrice()));
- }
-
- // 添加状态过滤条件
- if (criteria.getStatus() != null) {
- predicates.add(cb.equal(product.get("status"), criteria.getStatus()));
- }
-
- // 组合所有条件
- query.where(predicates.toArray(new Predicate[0]));
-
- // 添加排序
- if (criteria.getSortBy() != null) {
- Path<Object> sortPath = product.get(criteria.getSortBy());
- if (criteria.getSortDirection() == Sort.Direction.DESC) {
- query.orderBy(cb.desc(sortPath));
- } else {
- query.orderBy(cb.asc(sortPath));
- }
- }
-
- // 创建查询并设置分页
- TypedQuery<Product> typedQuery = entityManager.createQuery(query);
- if (criteria.getPage() != null && criteria.getSize() != null) {
- typedQuery.setFirstResult(criteria.getPage() * criteria.getSize());
- typedQuery.setMaxResults(criteria.getSize());
- }
-
- return typedQuery.getResultList();
- }
- }
复制代码
3. 安全策略
- // 安全配置
- @Configuration
- @EnableWebSecurity
- @EnableGlobalMethodSecurity(prePostEnabled = true)
- public class SecurityConfig extends WebSecurityConfigurerAdapter {
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- @Autowired
- private JwtAuthenticationEntryPoint unauthorizedHandler;
-
- @Bean
- public PasswordEncoder passwordEncoder() {
- return new BCryptPasswordEncoder();
- }
-
- @Bean
- public JwtAuthenticationFilter jwtAuthenticationFilter() {
- return new JwtAuthenticationFilter();
- }
-
- @Override
- public void configure(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
- authenticationManagerBuilder
- .userDetailsService(userDetailsService)
- .passwordEncoder(passwordEncoder());
- }
-
- @Bean(BeanIds.AUTHENTICATION_MANAGER)
- @Override
- public AuthenticationManager authenticationManagerBean() throws Exception {
- return super.authenticationManagerBean();
- }
-
- @Override
- protected void configure(HttpSecurity http) throws Exception {
- http
- .cors()
- .and()
- .csrf()
- .disable()
- .exceptionHandling()
- .authenticationEntryPoint(unauthorizedHandler)
- .and()
- .sessionManagement()
- .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
- .and()
- .authorizeRequests()
- .antMatchers("/api/auth/**")
- .permitAll()
- .antMatchers("/api/public/**")
- .permitAll()
- .antMatchers("/api/admin/**")
- .hasRole("ADMIN")
- .antMatchers(HttpMethod.GET, "/api/products/**", "/api/categories/**")
- .permitAll()
- .anyRequest()
- .authenticated();
-
- // 添加JWT过滤器
- http.addFilterBefore(jwtAuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
- }
- }
- // JWT认证过滤器
- public class JwtAuthenticationFilter extends OncePerRequestFilter {
-
- @Autowired
- private JwtTokenProvider tokenProvider;
-
- @Autowired
- private UserDetailsService userDetailsService;
-
- private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
-
- @Override
- protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
- throws ServletException, IOException {
- try {
- String jwt = getJwtFromRequest(request);
-
- if (StringUtils.hasText(jwt) && tokenProvider.validateToken(jwt)) {
- Long userId = tokenProvider.getUserIdFromJWT(jwt);
-
- UserDetails userDetails = userDetailsService.loadUserById(userId);
- UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
- userDetails, null, userDetails.getAuthorities());
- authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
-
- SecurityContextHolder.getContext().setAuthentication(authentication);
- }
- } catch (Exception ex) {
- logger.error("Could not set user authentication in security context", ex);
- }
-
- filterChain.doFilter(request, response);
- }
-
- private String getJwtFromRequest(HttpServletRequest request) {
- String bearerToken = request.getHeader("Authorization");
- if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
- return bearerToken.substring(7);
- }
- return null;
- }
- }
- // 方法级安全示例
- @Service
- public class OrderServiceImpl implements OrderService {
-
- @Override
- @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
- public Order getOrderById(Long id) {
- // 获取订单逻辑
- }
-
- @Override
- @PreAuthorize("hasRole('ADMIN')")
- public List<Order> getAllOrders() {
- // 获取所有订单逻辑
- }
-
- @Override
- @PreAuthorize("#order.userId == authentication.principal.id or hasRole('ADMIN')")
- public void updateOrder(Order order) {
- // 更新订单逻辑
- }
-
- @Override
- @PreAuthorize("#order.userId == authentication.principal.id or hasRole('ADMIN')")
- public void deleteOrder(Order order) {
- // 删除订单逻辑
- }
- }
复制代码- // 加密服务
- @Service
- public class EncryptionServiceImpl implements EncryptionService {
-
- private final String encryptionKey;
- private final String salt;
-
- @Autowired
- public EncryptionServiceImpl(
- @Value("${app.encryption.key}") String encryptionKey,
- @Value("${app.encryption.salt}") String salt) {
- this.encryptionKey = encryptionKey;
- this.salt = salt;
- }
-
- @Override
- public String encrypt(String data) {
- try {
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
- KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt.getBytes(), 65536, 256);
- SecretKey tmp = factory.generateSecret(spec);
- SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
-
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- cipher.init(Cipher.ENCRYPT_MODE, secretKey);
-
- byte[] iv = new byte[16];
- new SecureRandom().nextBytes(iv);
- IvParameterSpec ivSpec = new IvParameterSpec(iv);
-
- cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
- byte[] encryptedData = cipher.doFinal(data.getBytes());
-
- byte[] combined = new byte[iv.length + encryptedData.length];
- System.arraycopy(iv, 0, combined, 0, iv.length);
- System.arraycopy(encryptedData, 0, combined, iv.length, encryptedData.length);
-
- return Base64.getEncoder().encodeToString(combined);
- } catch (Exception e) {
- throw new EncryptionException("Failed to encrypt data", e);
- }
- }
-
- @Override
- public String decrypt(String encryptedData) {
- try {
- byte[] combined = Base64.getDecoder().decode(encryptedData);
-
- byte[] iv = new byte[16];
- byte[] encrypted = new byte[combined.length - iv.length];
- System.arraycopy(combined, 0, iv, 0, iv.length);
- System.arraycopy(combined, iv.length, encrypted, 0, encrypted.length);
-
- SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
- KeySpec spec = new PBEKeySpec(encryptionKey.toCharArray(), salt.getBytes(), 65536, 256);
- SecretKey tmp = factory.generateSecret(spec);
- SecretKey secretKey = new SecretKeySpec(tmp.getEncoded(), "AES");
-
- Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
- IvParameterSpec ivSpec = new IvParameterSpec(iv);
-
- cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
- byte[] decryptedData = cipher.doFinal(encrypted);
-
- return new String(decryptedData);
- } catch (Exception e) {
- throw new EncryptionException("Failed to decrypt data", e);
- }
- }
- }
- // 敏感数据处理器
- @Aspect
- @Component
- public class SensitiveDataAspect {
-
- private final EncryptionService encryptionService;
-
- @Autowired
- public SensitiveDataAspect(EncryptionService encryptionService) {
- this.encryptionService = encryptionService;
- }
-
- @Around("@annotation(EncryptSensitiveData)")
- public Object encryptSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
- Object result = joinPoint.proceed();
-
- // 处理返回结果中的敏感数据
- if (result instanceof User) {
- User user = (User) result;
- // 加密敏感字段
- if (user.getEmail() != null) {
- user.setEmail(encryptionService.encrypt(user.getEmail()));
- }
- if (user.getPhone() != null) {
- user.setPhone(encryptionService.encrypt(user.getPhone()));
- }
- if (user.getIdCard() != null) {
- user.setIdCard(encryptionService.encrypt(user.getIdCard()));
- }
- }
-
- return result;
- }
-
- @Around("@annotation(DecryptSensitiveData)")
- public Object decryptSensitiveData(ProceedingJoinPoint joinPoint) throws Throwable {
- Object[] args = joinPoint.getArgs();
-
- // 处理方法参数中的敏感数据
- for (int i = 0; i < args.length; i++) {
- if (args[i] instanceof User) {
- User user = (User) args[i];
- // 解密敏感字段
- if (user.getEmail() != null) {
- user.setEmail(encryptionService.decrypt(user.getEmail()));
- }
- if (user.getPhone() != null) {
- user.setPhone(encryptionService.decrypt(user.getPhone()));
- }
- if (user.getIdCard() != null) {
- user.setIdCard(encryptionService.decrypt(user.getIdCard()));
- }
- }
- }
-
- return joinPoint.proceed(args);
- }
- }
复制代码
4. 监控与运维
- // 自定义健康指标
- @Component
- public class CustomHealthIndicator implements HealthIndicator {
-
- private final DatabaseHealthIndicator databaseHealthIndicator;
- private final RedisHealthIndicator redisHealthIndicator;
- private final ExternalServiceHealthIndicator externalServiceHealthIndicator;
-
- @Autowired
- public CustomHealthIndicator(DatabaseHealthIndicator databaseHealthIndicator,
- RedisHealthIndicator redisHealthIndicator,
- ExternalServiceHealthIndicator externalServiceHealthIndicator) {
- this.databaseHealthIndicator = databaseHealthIndicator;
- this.redisHealthIndicator = redisHealthIndicator;
- this.externalServiceHealthIndicator = externalServiceHealthIndicator;
- }
-
- @Override
- public Health health() {
- // 检查数据库状态
- Health dbHealth = databaseHealthIndicator.health();
-
- // 检查Redis状态
- Health redisHealth = redisHealthIndicator.health();
-
- // 检查外部服务状态
- Health externalServiceHealth = externalServiceHealthIndicator.health();
-
- // 确定整体状态
- Status overallStatus = Status.UP;
- List<String> details = new ArrayList<>();
-
- if (dbHealth.getStatus() != Status.UP) {
- overallStatus = Status.DOWN;
- details.add("Database is not available: " + dbHealth.getDetails());
- }
-
- if (redisHealth.getStatus() != Status.UP) {
- overallStatus = overallStatus == Status.UP ? Status.UP : Status.DOWN;
- details.add("Redis is not available: " + redisHealth.getDetails());
- }
-
- if (externalServiceHealth.getStatus() != Status.UP) {
- overallStatus = overallStatus == Status.UP ? Status.UP : Status.DOWN;
- details.add("External service is not available: " + externalServiceHealth.getDetails());
- }
-
- if (overallStatus == Status.UP) {
- return Health.up()
- .withDetail("database", dbHealth.getDetails())
- .withDetail("redis", redisHealth.getDetails())
- .withDetail("externalService", externalServiceHealth.getDetails())
- .build();
- } else {
- return Health.down()
- .withDetail("reason", String.join("; ", details))
- .withDetail("database", dbHealth.getDetails())
- .withDetail("redis", redisHealth.getDetails())
- .withDetail("externalService", externalServiceHealth.getDetails())
- .build();
- }
- }
- }
- // 自定义指标
- @Service
- public class CustomMetrics {
-
- private final MeterRegistry meterRegistry;
- private final Counter orderCounter;
- private final Timer orderProcessingTimer;
-
- @Autowired
- public CustomMetrics(MeterRegistry meterRegistry) {
- this.meterRegistry = meterRegistry;
- this.orderCounter = Counter.builder("orders.created")
- .description("Number of orders created")
- .register(meterRegistry);
-
- this.orderProcessingTimer = Timer.builder("orders.processing.time")
- .description("Time taken to process orders")
- .register(meterRegistry);
- }
-
- public void incrementOrderCounter() {
- orderCounter.increment();
- }
-
- public Timer.Sample startOrderProcessingTimer() {
- return Timer.start(meterRegistry);
- }
-
- public void stopOrderProcessingTimer(Timer.Sample sample) {
- sample.stop(orderProcessingTimer);
- }
- }
- // 使用自定义指标
- @Service
- public class OrderServiceImpl implements OrderService {
-
- private final OrderRepository orderRepository;
- private final CustomMetrics customMetrics;
-
- @Autowired
- public OrderServiceImpl(OrderRepository orderRepository, CustomMetrics customMetrics) {
- this.orderRepository = orderRepository;
- this.customMetrics = customMetrics;
- }
-
- @Override
- @Transactional
- public Order createOrder(Order order) {
- Timer.Sample sample = customMetrics.startOrderProcessingTimer();
-
- try {
- // 创建订单逻辑
- Order savedOrder = orderRepository.save(order);
-
- // 增加订单计数器
- customMetrics.incrementOrderCounter();
-
- return savedOrder;
- } finally {
- // 停止计时器
- customMetrics.stopOrderProcessingTimer(sample);
- }
- }
- }
复制代码- // 日志配置
- @Configuration
- public class LoggingConfig {
-
- @Bean
- public InMemoryLogAppender inMemoryLogAppender() {
- InMemoryLogAppender appender = new InMemoryLogAppender();
- appender.setName("InMemoryLogAppender");
- appender.setThreshold(Level.INFO);
- appender.setMaxSize(1000);
-
- PatternLayoutEncoder encoder = new PatternLayoutEncoder();
- encoder.setPattern("%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n");
- encoder.start();
-
- appender.setEncoder(encoder);
- appender.start();
-
- Logger rootLogger = LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
- if (rootLogger instanceof ch.qos.logback.classic.Logger) {
- ((ch.qos.logback.classic.Logger) rootLogger).addAppender(appender);
- }
-
- return appender;
- }
- }
- // 审计日志服务
- @Service
- public class AuditLogServiceImpl implements AuditLogService {
-
- private final AuditLogRepository auditLogRepository;
-
- @Autowired
- public AuditLogServiceImpl(AuditLogRepository auditLogRepository) {
- this.auditLogRepository = auditLogRepository;
- }
-
- @Override
- @Async
- public void logAction(String userId, String action, String details) {
- AuditLog auditLog = new AuditLog();
- auditLog.setUserId(userId);
- auditLog.setAction(action);
- auditLog.setDetails(details);
- auditLog.setTimestamp(LocalDateTime.now());
- auditLog.setIpAddress(getCurrentIpAddress());
- auditLog.setUserAgent(getCurrentUserAgent());
-
- auditLogRepository.save(auditLog);
- }
-
- @Override
- public Page<AuditLog> getAuditLogs(String userId, LocalDateTime startTime, LocalDateTime endTime,
- Pageable pageable) {
- Specification<AuditLog> spec = Specification.where(null);
-
- if (StringUtils.hasText(userId)) {
- spec = spec.and((root, query, cb) -> cb.equal(root.get("userId"), userId));
- }
-
- if (startTime != null) {
- spec = spec.and((root, query, cb) -> cb.greaterThanOrEqualTo(root.get("timestamp"), startTime));
- }
-
- if (endTime != null) {
- spec = spec.and((root, query, cb) -> cb.lessThanOrEqualTo(root.get("timestamp"), endTime));
- }
-
- return auditLogRepository.findAll(spec, pageable);
- }
-
- private String getCurrentIpAddress() {
- // 获取当前请求的IP地址
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- if (requestAttributes instanceof ServletRequestAttributes) {
- HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
- String ipAddress = request.getHeader("X-Forwarded-For");
- if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
- ipAddress = request.getHeader("Proxy-Client-IP");
- }
- if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
- ipAddress = request.getHeader("WL-Proxy-Client-IP");
- }
- if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
- ipAddress = request.getRemoteAddr();
- }
- return ipAddress;
- }
- return "unknown";
- }
-
- private String getCurrentUserAgent() {
- // 获取当前请求的User-Agent
- RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
- if (requestAttributes instanceof ServletRequestAttributes) {
- HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
- return request.getHeader("User-Agent");
- }
- return "unknown";
- }
- }
- // 审计日志切面
- @Aspect
- @Component
- public class AuditLogAspect {
-
- private final AuditLogService auditLogService;
-
- @Autowired
- public AuditLogAspect(AuditLogService auditLogService) {
- this.auditLogService = auditLogService;
- }
-
- @AfterReturning(pointcut = "@annotation(auditLog)", returning = "result")
- public void logAfterReturning(JoinPoint joinPoint, AuditLog auditLog, Object result) {
- String userId = getCurrentUserId();
- String action = auditLog.action();
- String details = createLogDetails(joinPoint, result);
-
- auditLogService.logAction(userId, action, details);
- }
-
- @AfterThrowing(pointcut = "@annotation(auditLog)", throwing = "exception")
- public void logAfterThrowing(JoinPoint joinPoint, AuditLog auditLog, Exception exception) {
- String userId = getCurrentUserId();
- String action = auditLog.action();
- String details = "Failed: " + exception.getMessage();
-
- auditLogService.logAction(userId, action, details);
- }
-
- private String getCurrentUserId() {
- // 获取当前用户ID
- Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
- if (authentication != null && authentication.isAuthenticated() && !authentication.getPrincipal().equals("anonymousUser")) {
- return authentication.getName();
- }
- return "anonymous";
- }
-
- private String createLogDetails(JoinPoint joinPoint, Object result) {
- StringBuilder details = new StringBuilder();
- details.append("Method: ").append(joinPoint.getSignature().toShortString());
-
- // 添加参数信息
- Object[] args = joinPoint.getArgs();
- if (args.length > 0) {
- details.append(", Parameters: [");
- for (int i = 0; i < args.length; i++) {
- if (i > 0) {
- details.append(", ");
- }
- details.append(args[i] != null ? args[i].toString() : "null");
- }
- details.append("]");
- }
-
- // 添加返回值信息
- if (result != null) {
- details.append(", Result: ").append(result.toString());
- }
-
- return details.toString();
- }
- }
复制代码
总结与展望
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框架将继续为企业级应用开发提供强大支持,帮助开发团队应对不断变化的业务需求和技术挑战。 |
|