# fastboot-commons **Repository Path**: fastboot_655354/fastboot-commons ## Basic Information - **Project Name**: fastboot-commons - **Description**: No description available - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2025-12-03 - **Last Updated**: 2026-02-26 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # FastBoot Commons 项目文档 ## 项目简介 FastBoot Commons 是一个基于 Spring Boot 的企业级基础组件库,专为微服务架构应用开发设计。该库提供统一的公共模块支持,涵盖缓存、数据访问、安全控制、Web 工具、远程调用等多个核心领域,通过模块化设计实现功能解耦,开发者可根据实际需求按需引入相应模块。 本项目采用 Gradle 构建系统,模块间依赖关系清晰,每个模块均经过精心设计和测试,确保在企业级应用场景中的稳定性和可靠性。项目的核心目标是简化 Spring Boot 应用的开发流程,提供经过生产验证的通用解决方案,让开发者能够专注于业务逻辑的实现。 FastBoot Commons 的设计理念强调**约定优于配置**、**开箱即用**和**高度可扩展**。所有模块均支持自定义配置,同时提供合理的默认行为,降低上手难度的同时保留足够的灵活性。项目遵循严格的代码规范和测试标准,确保模块的质量和可维护性。 ## 模块功能概览 ### fastboot-commons-cache 缓存模块提供统一的缓存抽象层,支持多级缓存架构(本地缓存 + 分布式缓存),并提供注解驱动的缓存管理方案。该模块的主要特性包括:基于 Caffeine 的高性能本地缓存实现,支持配置化的缓存规格;基于 Redis 的分布式缓存,支持灵活的过期时间设置;多级缓存组合策略,同时利用本地缓存的低延迟和分布式缓存的共享性;缓存失效消息广播机制,确保多节点环境下缓存的一致性。核心类包括 `CacheOps` 提供统一的缓存操作接口,`DoubleCacheOps` 实现双缓存逻辑,`DCacheableAspect` 支持注解驱动的缓存管理。 ### fastboot-commons-core 核心工具模块包含丰富的通用组件和工具类,是整个组件库的基础。异常处理体系包括 `BaseException` 及其子类 `BusinessException`、`SystemException`,支持统一的异常捕获和处理;类型转换工具 `ConvertUtils` 提供日期时间、数字、布尔值等类型的安全转换;加密工具包括 `AesUtils` 支持 ECB 和 CBC 模式的 AES 加密解密,`RsaUtils` 提供完整的 RSA 密钥对生成、签名验证和分块加解密功能;Lambda 表达式解析工具 `LambdaUtils` 和 `LambdaMeta` 支持序列化和字段名提取;SQL 构建器 `SqlQueryBuilder` 提供链式 API 构建复杂查询语句,支持条件构造、连表查询、排序分组等功能;实体比较工具 `EntityComparer` 支持对象差异比较;函数式接口封装包括 `Func0`、`Func1`、`Func2` 等便于函数式编程。 ### fastboot-commons-data-elasticsearch Elasticsearch 数据访问模块基于 Spring Data Elasticsearch,提供统一的 Elasticsearch 操作接口 `ElasticsearchOps`。该模块支持索引管理(创建、删除、存在性检查)、文档操作(保存、批量操作、更新)、多种查询方式(条件查询、多字段匹配、JSON 查询)以及分页支持。`ElasticsearchOps` 继承自 `ElasticsearchTemplate`,扩展了常用操作方法,简化了 Elasticsearch 的使用复杂度。 ### fastboot-commons-data-mongodb MongoDB 数据访问模块基于 Spring Data MongoDB,提供统一的 MongoDB 操作接口。核心接口 `IMongoRepository` 定义了标准的 CRUD 操作,`AbstractMongoRepository` 提供了通用实现,`MongoOps` 扩展了 `MongoTemplate` 增加分页查询和游标操作支持。该模块支持save、update、remove 等基本操作,分页查询,条件更新,批量处理等功能。 ### fastboot-commons-data-mybatis MyBatis 增强模块基于 MyBatis-Plus,提供自定义 SQL 注入器和通用 Mapper。`FastSqlInjector` 扩展默认注入器,新增 `SelectBySql` 方法支持自定义 SQL 查询;`FastMapper` 接口继承 `BaseMapper` 提供基础 CRUD;`CommFastMapper` 作为通用 Mapper 实现可直接使用。该模块简化 MyBatis 配置,自动注入常用查询方法。 ### fastboot-commons-data-redis Redis 数据访问模块提供统一的 Redis 操作接口 `RedisOps`,支持多种数据结构的操作。字符串操作包括基本的 get/set、过期时间设置、原子计数器;哈希操作支持 hget/hset/hmget/hmset 等;集合操作支持添加、获取、删除、交集;列表操作支持左右 push/pop、索引访问、批量设置;支持 Lua 脚本执行和原子操作。分布式锁模块 `RLockOps` 基于 Redisson 提供可重入锁、尝试获取锁等分布式锁功能。`LuaScriptLoader` 支持从文件加载 Lua 脚本。 ### fastboot-commons-rpc-feign 远程调用模块基于 Feign 封装,提供异常处理和拦截功能。`ExceptionErrorDecoder` 自定义错误解码器,将远程服务异常转换为本地可处理的异常;`WebExceptionInterceptor` 处理 Web 层的异常渲染;`FastSentinelFeign` 集成 Sentinel 实现限流熔断保护;`JavaSerialization` 支持 Java 序列化用于 Feign 调用的数据传输。该模块增强了 Feign 的可用性和健壮性。 ### fastboot-commons-security Spring Security 安全模块基于 Spring Security 6 和 OAuth2,提供完整的认证授权解决方案。资源服务器配置 `FastResourceServerConfiguration` 支持 JWT 和不透明令牌;`FastCustomOpaqueTokenIntrospector` 自定义令牌 introspection;权限校验服务 `PermissionService` 配合 `@HasPermission` 注解实现方法级权限控制;用户详情服务 `FastUserDetailsService` 支持多种登录方式;OAuth2 授权服务 `RedisOAuth2AuthorizationService` 和 `RedisOAuth2AuthorizationConsentService` 使用 Redis 存储授权信息;客户端详情服务 `FastRegisteredClientRepository` 支持客户端认证。 ### fastboot-commons-security-satoken Sa-Token 安全模块集成轻量级权限框架 Sa-Token,提供用户登录状态管理功能。`StpUserUtil` 封装 Sa-Token 的核心 API,提供登录登出、会话管理、权限校验、角色检查、分布式会话等功能。该模块配置灵活,支持单点登录、踢人下线、会话禁用、安全验证等高级功能。 ### fastboot-commons-web Web 层通用工具模块提供 Jackson JSON 处理、Web 工具、消息处理等组件。`JsonUtils` 提供 JSON 序列化反序列化工具方法;`FastJavaTimeModule` 处理 Java 8 时间类型的序列化;`WebUtils` 扩展 Spring WebUtils 提供 Cookie 操作、客户端 IP 获取、请求体读取等功能;`SpringUtils` 提供 Spring 上下文访问和 Bean 获取;`MessageUtils` 支持国际化消息获取;`ValidationUtils` 提供 Bean 验证功能;`MapStructUtil` 对象转换工具;`RequestBodyCachingFilter` 请求体缓存过滤器支持多次读取请求体。 ## 使用指南 ### 环境要求 - JDK 17 或更高版本 - Spring Boot 3.x - Gradle 8.x ### 依赖引入 在项目的 `build.gradle` 文件中配置依赖。根据需要引入对应的模块: ```groovy dependencies { // 缓存模块 implementation 'com.wfcdev.fastboot:fastboot-commons-cache' // 核心工具模块 implementation 'com.wfcdev.fastboot:fastboot-commons-core' // Elasticsearch 数据访问模块 implementation 'com.wfcdev.fastboot:fastboot-commons-data-elasticsearch' // MongoDB 数据访问模块 implementation 'com.wfcdev.fastboot:fastboot-commons-data-mongodb' // MyBatis 增强模块 implementation 'com.wfcdev.fastboot:fastboot-commons-data-mybatis' // Redis 数据访问模块 implementation 'com.wfcdev.fastboot:fastboot-commons-data-redis' // Feign 远程调用模块 implementation 'com.wfcdev.fastboot:fastboot-commons-rpc-feign' // Spring Security 安全模块 implementation 'com.wfcdev.fastboot:fastboot-commons-security' // Sa-Token 安全模块 implementation 'com.wfcdev.fastboot:fastboot-commons-security-satoken' // Web 工具模块 implementation 'com.wfcdev.fastboot:fastboot-commons-web' } ``` ### 配置说明 #### 缓存配置(fastboot-commons-cache) ```yaml spring: cache: type: redis caffeine: enabled: true specs: default: maximumSize=100,expireAfterWrite=10m users: maximumSize=1000,expireAfterWrite=30m fastboot: cache: time-to-live: example-cache: 60s users-cache: 300s app: doubleCache: lockWaitTime: 5 lockReleaseTime: 10 nullValueExpireTime: 300 ``` #### Redis 配置(fastboot-commons-data-redis) ```yaml spring: redis: host: localhost port: 6379 password: "" database: 0 timeout: 10000ms lettuce: pool: max-active: 20 max-idle: 10 min-idle: 5 max-wait: -1ms ``` Redisson 分布式锁配置: ```yaml spring: data: redis: repositories: enabled: false ``` #### Sa-Token 配置(fastboot-commons-security-satoken) ```yaml fastboot: sa-token: custom: user: timeout: 86400 is-concurrent: true token-name: satoken is-share: true ``` #### 安全配置(fastboot-commons-security) ```yaml security: oauth2: ignore: urls: - /login - /logout - /public/** app: clientDetails: url: '/fast-upms/sysOauthClientDetails/findByClientId' sysUserDetails: url: '/fast-upms/sysUser/findByUsername' userDetails: url: '/fast-upms/user/findByPhone' ``` #### Web 配置(fastboot-commons-web) ```yaml spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 serialization: write-dates-as-timestamps: false deserialization: fail-on-unknown-properties: false ``` ## 示例代码 ### 缓存使用示例(fastboot-commons-cache) ```java @Service public class UserService { private final CacheOps cacheOps; public UserService(CacheOps cacheOps) { this.cacheOps = cacheOps; } public User getCachedUser(Long userId) { return cacheOps.runCaching("userCache", () -> getUserFromDatabase(userId), userId.toString()); } public User getUserFromDatabase(Long userId) { // 从数据库查询用户 return userRepository.findById(userId); } public void refreshUserCache(Long userId) { cacheOps.localCacheEvictAll("userCache", userId.toString()); } } ``` 使用注解方式(DCacheable): ```java @Service public class OrderService { @DCacheable(cacheName = "orderCache", key = "#orderId") public Order getOrder(Long orderId) { return orderRepository.findById(orderId); } } ``` ### Redis 使用示例(fastboot-commons-data-redis) ```java @Service public class RedisService { private final RedisOps redisOps; public RedisService(RedisOps redisOps) { this.redisOps = redisOps; } public void setUserToken(String token, User user, long timeout, TimeUnit unit) { redisOps.set(token, user, timeout, unit); } public User getUserByToken(String token) { return (User) redisOps.get(token); } public void incrementVisitCount(String date) { redisOps.incr("visit:" + date, 1); } public Map getHashData(String key) { return redisOps.hmget(key); } public boolean setIfAbsent(String lockKey, Object lockValue, long timeout, TimeUnit unit) { return redisOps.setIfAbsent(lockKey, lockValue, timeout, unit); } } ``` 分布式锁使用示例: ```java @Service public class DistributedLockService { private final RLockOps rLockOps; public DistributedLockService(RLockOps rLockOps) { this.rLockOps = rLockOps; } public void executeWithLock(String lockName, Runnable task) { rLockOps.tryLock(() -> { task.run(); return null; }, lockName, 10, 30); } public T executeWithLock(String lockName, Func0 func) { return rLockOps.tryLock(func, lockName, 10, 30); } } ``` ### 安全权限控制(fastboot-commons-security) ```java @RestController @RequestMapping("/api") public class UserController { @Autowired private PermissionService permissionService; @GetMapping("/users") @HasPermission("user:read") public List listUsers() { return userService.listUsers(); } @PostMapping("/users") @HasPermission("user:write") public User createUser(@RequestBody User user) { return userService.createUser(user); } @DeleteMapping("/users/{id}") @HasPermission({"user:write", "user:delete"}) public void deleteUser(@PathVariable Long id) { userService.deleteUser(id); } } ``` 获取当前登录用户: ```java @RestController @RequestMapping("/api") public class ProfileController { @GetMapping("/profile") public AuthUser getProfile() { Authentication auth = SecurityUtils.getAuthentication(); return SecurityUtils.getUser(auth); } } ``` ### Sa-Token 登录控制(fastboot-commons-security-satoken) ```java @RestController @RequestMapping("/auth") public class AuthController { @PostMapping("/login") public String login(@RequestParam String username, @RequestParam String password) { if ("admin".equals(username) && "password".equals(password)) { StpUserUtil.login(username); return "Login successful, token: " + StpUserUtil.getTokenValue(); } throw new BusinessException("Invalid credentials"); } @GetMapping("/check-login") public boolean checkLogin() { return StpUserUtil.isLogin(); } @PostMapping("/logout") public String logout() { StpUserUtil.logout(); return "Logged out successfully"; } @GetMapping("/permissions") public List getPermissions() { return StpUserUtil.getPermissionList(); } @GetMapping("/has-permission/{permission}") public boolean hasPermission(@PathVariable String permission) { return StpUserUtil.hasPermission(permission); } } ``` ### SQL 构建器使用(fastboot-commons-core) ```java @Service public class SqlExampleService { public void buildQueryExamples() { // 基本查询 SqlQueryBuilder query1 = SqlQueryBuilder.select("id, name, age") .from("users") .where("age", 18, ">") .orderBy("created_at", false); System.out.println(query1); // SELECT id, name, age FROM users WHERE age > ? ORDER BY created_at DESC // 联表查询 Table users = new Table("users", "u"); Table orders = new Table("orders", "o"); SqlQueryBuilder query2 = SqlQueryBuilder.select(users.column("name"), orders.column("order_no")) .from(users) .join(orders, users.column("id"), orders.column("user_id")) .where(users.column("status"), "ACTIVE"); // 复杂条件 SqlQueryBuilder query3 = SqlQueryBuilder.select("*") .from("products") .where(w -> w.eq("category", "electronics") .like("name", "phone") .between("price", 100, 1000)); // 分组聚合 SqlQueryBuilder query4 = SqlQueryBuilder.select("category", "COUNT(*) as count", "AVG(price) as avg_price") .from("products") .groupBy("category") .having("COUNT(*)", 10, ">"); } } ``` ### MongoDB 使用示例(fastboot-commons-data-mongodb) ```java @Repository public class UserRepository extends AbstractMongoRepository { public UserRepository(MongoOps mongoOps) { super(mongoOps, User.class, "users"); } public PageResult findActiveUsers(Pageable pageable) { Query query = new Query(Criteria.where("active").is(true)); return page(pageable, query); } public List findByNameContaining(String name) { Query query = new Query(Criteria.where("name").regex(name)); return mongoOps.find(query, User.class); } } ``` ### Elasticsearch 使用示例(fastboot-commons-data-elasticsearch) ```java @Service public class DocumentService { private final ElasticsearchOps elasticsearchOps; public DocumentService(elasticsearchOps elasticsearchOps) { this.elasticsearchOps = elasticsearchOps; } public void initIndex() { if (!elasticsearchOps.indexExists("documents")) { elasticsearchOps.createIndex(Document.class); } } public void saveDocument(Document doc) { elasticsearchOps.save(doc); } public void bulkSave(List docs) { elasticsearchOps.saveAll(docs); } public SearchHits search(String keyword, int page, int size) { return elasticsearchOps.multiMatchSearch(keyword, new String[]{"title", "content"}, Document.class, page, size); } public void updateDocument(String id, Map fields) { elasticsearchOps.updateDocument(id, fields, Document.class, "documents"); } } ``` ### Web 工具使用示例(fastboot-commons-web) ```java @Service public class WebExampleService { public void webUtilsExamples() { // 获取请求响应 HttpServletRequest request = WebUtils.getRequest(); HttpServletResponse response = WebUtils.getResponse(); // 获取客户端IP String clientIP = WebUtils.getClientIP(request); // 获取请求体 String body = WebUtils.getBodyStr(request); // JSON 转换 String json = JsonUtils.toJsonStr(user); User user = JsonUtils.toBean(json, User.class); // 对象转换 UserDTO dto = MapStructUtil.convert(user, UserDTO.class); List dtoList = MapStructUtil.convertList(userList, UserDTO.class); // 获取 Spring Bean UserService userService = SpringUtils.getBean(UserService.class); String property = SpringUtils.getProperty("app.name"); // 验证 Set> violations = ValidationUtils.validate(user); ValidationUtils.validateAndThrow(user); // 国际化消息 String message = MessageUtils.message("user.not.found", userId); // 事务提交后执行 TransactionUtils.afterCommit(() -> { // 发送通知等 }); } } ``` ## 开发建议 **模块化设计原则**:根据项目实际需求选择引入相应模块,避免引入不必要的依赖导致项目臃肿。建议采用按需引入的方式,只引入实际使用到的模块,这有助于减少最终应用的依赖体积和启动时间。 **配置驱动开发**:充分利用 `application.yml` 或 `application.properties` 进行模块配置,通过配置文件实现环境适配。不同环境(开发、测试、生产)可以使用不同的配置文件,通过 Spring Boot 的 Profile 机制进行切换。 **异常处理统一化**:使用 `BaseException` 及其子类(`BusinessException`、`SystemException`)进行统一异常处理,结合全局异常处理器实现一致的错误响应格式,提升系统的健壮性和可维护性。 **日志记录与调试**:使用 `@Slf4j` 注解结合 SLF4J 日志框架,在关键业务节点记录日志,便于问题追踪和性能分析。建议采用分级日志(DEBUG、INFO、WARN、ERROR),生产环境至少开启 INFO 级别。 **安全性保障**:根据项目需求选择合适的安全模块(Spring Security OAuth2 或 Sa-Token),启用安全控制后确保所有敏感接口都受到保护。定期更新依赖版本以修复安全漏洞。 **缓存策略设计**:合理设计缓存键命名规范和过期策略,避免缓存穿透、缓存击穿和缓存雪崩问题。对于热点数据采用较长的过期时间,不常变化的数据可以设置较长的缓存时间。 **数据访问规范**:使用各数据访问模块时遵循其最佳实践,如 MyBatis-Plus 的逻辑删除、乐观锁等特性,MongoDB 的索引优化,Elasticsearch 的分片和副本配置等。 ## 贡献指南 欢迎社区开发者贡献代码和提出建议。在提交代码前,请确保: 1. 代码风格与项目现有代码保持一致,遵循项目定义的代码规范 2. 为新功能编写必要的单元测试和集成测试,确保测试覆盖 3. 更新相关文档,说明新功能的用途和使用方法 4. 提交 Pull Request 时详细描述修改内容和动机 您可以通过以下方式参与贡献: - 在 Gitee 上提交 Issue 报告 bug 或提出新功能建议 - Fork 项目后提交 Pull Request 贡献代码 - 完善项目文档和使用示例 - 分享使用经验,帮助其他开发者解决问题 ## 许可证 本项目采用 Apache License 2.0 协议开源。详情请参见 [LICENSE](LICENSE) 文件。 ``` Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION ``` --- **项目地址**:https://gitee.com/fastboot_655354/fastboot-commons **问题反馈**:https://gitee.com/fastboot_655354/fastboot-commons/issues