### Basic fd-framework Configuration Example Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/index This snippet demonstrates a minimal set of conventional configurations for an application using fd-framework. It includes setting the application name and enabling Swagger, along with configuring the log level. These settings can be adjusted based on project requirements. ```yaml spring: application: name: your-app-name fd: swagger: enable: true log: level: INFO ``` -------------------------------- ### Include Specific fd-framework Starter Modules Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/index After importing the fd-framework BOM, you can include specific starter modules as needed without explicitly defining their versions. This example shows how to include the bootstrap starter, which provides basic Web capabilities, Swagger, global exception handling, and serialization enhancements. ```xml com.fd.framework bootstrap-spring-boot-starter ``` -------------------------------- ### GET /example/user Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/example This endpoint demonstrates basic web functionalities, including how Long and Date types are serialized and the structure of the BaseResult. ```APIDOC ## GET /example/user ### Description Demonstrates basic web functionalities, including Long to String serialization (to prevent frontend precision loss) and Date formatting to `yyyy-MM-dd HH:mm:ss`. Also shows the `BaseResult` structure (code/message/data). ### Method GET ### Endpoint /example/user ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **code** (integer) - Response status code. - **message** (string) - Response message. - **data** (object) - The actual response data, which may include serialized Longs and formatted Dates. #### Response Example ```json { "code": 200, "message": "Success", "data": { "userId": "1234567890123456789", "timestamp": "2023-10-27 10:30:00" } } ``` ``` -------------------------------- ### GET /example/exception Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/example This endpoint tests the global exception handling mechanism, ensuring that all exceptions are uniformly presented as 'System busy'. ```APIDOC ## GET /example/exception ### Description Tests the global exception handling. This endpoint is designed to trigger an exception that should be caught and uniformly returned as 'System busy' to the client. ### Method GET ### Endpoint /example/exception ### Parameters #### Path Parameters None #### Query Parameters None ### Request Example ```json {} ``` ### Response #### Success Response (200) - **code** (integer) - Response status code, expected to be a server error code. - **message** (string) - Response message, expected to be 'System busy'. - **data** (null) - Data field should be null or absent. #### Response Example ```json { "code": 500, "message": "System busy", "data": null } ``` ``` -------------------------------- ### Execute an HTTP Request with OkHttp Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/easy-http-spring-boot-starter This Java code illustrates how to execute an HTTP GET request using an OkHttpClient instance. It shows how to build a request, execute it, and retrieve the response body. Error handling for the response body is included. ```java Request request = new Request.Builder().url("https://example.com").get().build(); try (Response resp = okHttpClient.newCall(request).execute()) { String body = resp.body() == null ? null : resp.body().string(); } ``` -------------------------------- ### Introduce Resource Spring Boot Starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/resource-spring-boot-starter This snippet shows how to add the resource-spring-boot-starter dependency to your Maven project. This is the first step to start using the module's functionalities. ```xml com.fd.framework resource-spring-boot-starter ``` -------------------------------- ### OpenAI Chat Configuration with Proxy Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/ai-spring-boot-starter Example of configuring the OpenAI service and OkHttp proxy settings in your application. This includes API key, host, and proxy details like URL, port, and type. It also shows OkHttp timeout and logging configurations. ```yaml ai: openai: api-key: your-api-key api-host: https://api.openai.com/ okhttp: proxy-url: 127.0.0.1 proxy-port: 7890 proxy-type: HTTP log: HEADERS connect-timeout: 300 read-timeout: 300 write-timeout: 300 time-unit: SECONDS ``` -------------------------------- ### Configure Tripartite Auth with JustAuth Properties Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/tripartite-auth-spring-boot-starter This example demonstrates the minimal configuration required to enable and set up tripartite authentication using JustAuth. It specifies the authentication type (e.g., Gitee) with its client ID, client secret, and redirect URI. It also shows how to configure the state cache type, with Redis being an option. ```yaml justauth: enabled: true type: GITEE: client-id: your-client-id client-secret: your-client-secret redirect-uri: http://localhost:8080/oauth/gitee/callback cache: type: redis ``` -------------------------------- ### Manage fd-framework Versions with Maven BOM Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/index Import fd-framework as a Bill of Materials (BOM) in your business project to uniformly manage the versions of various starters. This simplifies dependency management by allowing you to import the BOM and then include specific modules without specifying their versions. ```xml com.fd.framework fd-framework 1.0.0-SNAPSHOT pom import ``` -------------------------------- ### Dual-Level Cache Usage (List Example) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/cache-spring-boot-starter Illustrates how to use the dual-level caching strategy for lists. This method includes an additional parameter for the secondary cache expiration time. It fetches a list of users based on a department ID, utilizing both primary and secondary caches. ```java return fdCacheManager.getListHasSecond( "dept:users:" + deptId, 5, 1800, 7200, User.class, () -> userMapper.selectByDeptId(deptId) ); ``` -------------------------------- ### Typical Controller Usage for Tripartite OAuth Login Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/tripartite-auth-spring-boot-starter This Java code snippet illustrates a typical controller setup for handling tripartite OAuth login flows. It utilizes `AuthRequestFactory` to obtain authentication requests for different platforms and manages the authorization and callback processes. ```java @RestController @RequestMapping("/oauth") public class AuthController { @Resource private AuthRequestFactory factory; @GetMapping public List list() { return factory.oauthList(); } @GetMapping("/login/{type}") public void login(@PathVariable String type, HttpServletResponse response) throws IOException { AuthRequest authRequest = factory.get(type); response.sendRedirect(authRequest.authorize(AuthStateUtils.createState())); } @GetMapping("/{type}/callback") public AuthResponse callback(@PathVariable String type, AuthCallback callback) { AuthRequest authRequest = factory.get(type); return authRequest.login(callback); } } ``` -------------------------------- ### Get User Endpoint Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/guides/example Retrieves a user record by ID. This endpoint verifies MyBatis-Plus CRUD operations. ```APIDOC ## GET /user/get ### Description Retrieves a specific user record by their ID using MyBatis-Plus. ### Method GET ### Endpoint /user/get ### Parameters #### Path Parameters None #### Query Parameters - **id** (integer) - Required - The ID of the user to retrieve. ### Request Example ``` GET /user/get?id=1 ``` ### Response #### Success Response (200) - **id** (integer) - The user's ID. - **username** (string) - The user's username. - **email** (string) - The user's email. #### Response Example ```json { "id": 1, "username": "existinguser", "email": "existinguser@example.com" } ``` ``` -------------------------------- ### GET /user/get?id=1 Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/example Retrieves a user by their ID. This endpoint verifies the basic CRUD operations of the MyBatis-Plus ORM. ```APIDOC ## GET /user/get?id=1 ### Description Retrieves a user by their unique identifier. This endpoint validates the fundamental Create, Read, Update, and Delete (CRUD) operations provided by MyBatis-Plus. ### Method GET ### Endpoint /user/get ### Parameters #### Path Parameters None #### Query Parameters - **id** (long) - Required - The unique identifier of the user to retrieve. ### Request Example ```json { "id": 1 } ``` ### Response #### Success Response (200) - **id** (long) - The unique identifier for the user. - **username** (string) - The username of the user. - **email** (string) - The email address of the user. - **createTime** (datetime) - The timestamp when the user was created. - **updateTime** (datetime) - The timestamp when the user was last updated. - **version** (integer) - The version number of the user record. #### Response Example ```json { "id": 1, "username": "janedoe", "email": "jane.doe@example.com", "createTime": "2023-10-26 09:00:00", "updateTime": "2023-10-27 11:00:00", "version": 2 } ``` ``` -------------------------------- ### Word to PDF Conversion Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/common-spring-boot-starter Shows how to use the `DocumentTools.wordToPdf` method to convert Word documents to PDF. Note: This functionality depends on Aspose.Words and requires proper licensing and error handling for production use. ```java DocumentTools.wordToPdf("D:/tmp/a.docx", "D:/tmp/a.pdf"); ``` -------------------------------- ### Include OkHttp Dependency in Maven Project Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/easy-http-spring-boot-starter This snippet shows how to add the easy-http-spring-boot-starter dependency to your Maven project's pom.xml. This allows for unified referencing and version management of OkHttp dependencies. ```xml com.fd.framework easy-http-spring-boot-starter ``` -------------------------------- ### Hash Operations Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Methods for interacting with Redis Hash data structures, including setting, getting, checking existence, deleting fields, and incrementing/decrementing values. ```APIDOC ## Hash Operations ### Description Methods for interacting with Redis Hash data structures, including setting, getting, checking existence, deleting fields, and incrementing/decrementing values. ### Methods #### `RedisUtil.hSet(String key, Map data)` - **Description**: Sets multiple fields in a Hash. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **data** (Map) - Required - A map of field-value pairs to set. #### `RedisUtil.hSet(String key, String hashKey, Object value)` - **Description**: Sets a single field in a Hash. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKey** (String) - Required - The field name. - **value** (Object) - Required - The value to set for the field. #### `RedisUtil.hSet(String key, Map data, Long expireSeconds)` - **Description**: Sets multiple fields in a Hash with an expiration time. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **data** (Map) - Required - A map of field-value pairs to set. - **expireSeconds** (Long) - Required - The expiration time in seconds. #### `RedisUtil.hSet(String key, String hashKey, Object value, Long expireSeconds)` - **Description**: Sets a single field in a Hash with an expiration time. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKey** (String) - Required - The field name. - **value** (Object) - Required - The value to set for the field. - **expireSeconds** (Long) - Required - The expiration time in seconds. #### `RedisUtil.hGet(String key)` - **Description**: Retrieves all fields and values from a Hash. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **Response**: Map - A map containing all field-value pairs. #### `RedisUtil.hGet(String key, String hashKey)` - **Description**: Retrieves the value of a single field from a Hash. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKey** (String) - Required - The field name. - **Response**: Object - The value of the specified field. #### `RedisUtil#hashKey(String key, String hashKey)` - **Description**: Checks if a field exists within a Hash. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKey** (String) - Required - The field name to check. - **Response**: Boolean - True if the field exists, false otherwise. #### `RedisUtil#hahsDel(String key, String... hashKeys)` - **Description**: Deletes one or more fields from a Hash. - **Method**: DELETE (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKeys** (String...) - Required - The field names to delete. #### `RedisUtil#increment(String key, String hashKey, long number)` - **Description**: Increments or decrements the value of a field in a Hash by a specified number. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the Hash. - **hashKey** (String) - Required - The field name. - **number** (long) - Required - The number to increment/decrement by (use negative for decrement). - **Response**: Long - The value of the field after the increment/decrement operation. ``` -------------------------------- ### Maven Dependency for ai-spring-boot-starter Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/ai-spring-boot-starter This snippet shows how to include the ai-spring-boot-starter library as a Maven dependency in your project. It automatically bundles necessary libraries like OkHttp and Logging. ```xml com.fd.framework ai-spring-boot-starter ``` -------------------------------- ### Parse Date Parameters in GET/Query Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/bootstrap-spring-boot-starter Automatically parse date strings from GET or Query parameters into java.util.Date objects. The module supports various date string formats for parsing. ```java @GetMapping("/report") public BaseResult report(@RequestParam Date startTime, @RequestParam Date endTime) { // startTime/endTime will be automatically parsed using multiple formats return BaseResult.success(); } ``` -------------------------------- ### List Operations Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Methods for managing Redis List data structures, including pushing elements to the left or right, retrieving elements by index or range, and getting the list length. ```APIDOC ## List Operations ### Description Methods for managing Redis List data structures, including pushing elements to the left or right, retrieving elements by index or range, and getting the list length. ### Methods #### `RedisUtil#leftPush(String key, Object value)` - **Description**: Pushes an element to the left (head) of a List. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **value** (Object) - Required - The element to push. #### `RedisUtil#leftPush(String key, Object value, Long expireSeconds)` - **Description**: Pushes an element to the left (head) of a List with an expiration time. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **value** (Object) - Required - The element to push. - **expireSeconds** (Long) - Required - The expiration time in seconds. #### `RedisUtil#index(String key, long index)` - **Description**: Retrieves the element at a specific index in a List. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **index** (long) - Required - The index of the element to retrieve (0-based). - **Response**: Object - The element at the specified index. #### `RedisUtil#range(String key, long start, long end)` - **Description**: Retrieves a range of elements from a List. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **start** (long) - Required - The starting index of the range (inclusive). - **end** (long) - Required - The ending index of the range (inclusive). - **Response**: List - A list containing the elements within the specified range. #### `RedisUtil#leftPushAll(String key, String... values)` - **Description**: Pushes multiple elements to the left (head) of a List. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **values** (String...) - Required - The elements to push. #### `RedisUtil#leftPushAll(String key, Long expireSeconds, String... values)` - **Description**: Pushes multiple elements to the left (head) of a List with an expiration time. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **expireSeconds** (Long) - Required - The expiration time in seconds. - **values** (String...) - Required - The elements to push. #### `RedisUtil#rightPush(String key, String value)` - **Description**: Pushes an element to the right (tail) of a List. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **value** (String) - Required - The element to push. #### `RedisUtil#rightPushAll(String key, String... values)` - **Description**: Pushes multiple elements to the right (tail) of a List. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **values** (String...) - Required - The elements to push. #### `RedisUtil#leftPushIfPresent(String key, Object value)` - **Description**: Pushes an element to the left (head) of a List only if the List exists. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **value** (Object) - Required - The element to push. #### `RedisUtil#rightPushIfPresent(String key, Object value)` - **Description**: Pushes an element to the right (tail) of a List only if the List exists. - **Method**: POST (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **value** (Object) - Required - The element to push. #### `RedisUtil#listLength(String key)` - **Description**: Gets the number of elements in a List. - **Method**: GET (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **Response**: Long - The length of the List. #### `RedisUtil#leftPop(String key)` - **Description**: Removes and returns the element from the left (head) of a List. - **Method**: DELETE (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **Response**: Object - The removed element from the left of the List. #### `RedisUtil#rightPop(String key)` - **Description**: Removes and returns the element from the right (tail) of a List. - **Method**: DELETE (or similar, conceptually) - **Endpoint**: N/A (Utility Method) - **Parameters**: - **key** (String) - Required - The key of the List. - **Response**: Object - The removed element from the right of the List. ``` -------------------------------- ### Business Exception with Custom Error Codes Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/common-spring-boot-starter Illustrates creating and using custom error codes with `BusinessException` for more specific error reporting. This leverages the `ResultCode` interface. ```java public enum UserErrorCode implements ResultCode { USER_NOT_FOUND(40001, "用户不存在"); private final Integer code; private final String message; UserErrorCode(Integer code, String message) { this.code = code; this.message = message; } @Override public Integer getCode() { return code; } @Override public String getMessage() { return message; } } // 使用 throw new BusinessException(UserErrorCode.USER_NOT_FOUND); ``` -------------------------------- ### RedissonClient Rate Limiter (RRateLimiter) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Demonstrates how to use RedissonClient for rate limiting. This example sets a rate limit of 10 requests per second for SMS sending and checks if a request can be acquired. ```java RRateLimiter limiter = redissonClient.getRateLimiter("api:sendSms"); limiter.trySetRate(RateType.OVERALL, 10, 1, RateIntervalUnit.SECONDS); // Max 10 times per second if (!limiter.tryAcquire()) { throw new RuntimeException("Request frequency is too high"); } ``` -------------------------------- ### Business Exception Handling (Service Layer) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/common-spring-boot-starter Shows how to throw `BusinessException` in the service layer to indicate business logic failures. This exception is handled globally by the starter. ```java if (user == null) { throw new BusinessException("用户不存在"); } ``` -------------------------------- ### RedissonClient Distributed Lock (RLock) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Example of using RedissonClient to implement a distributed lock. It shows how to acquire a lock, handle potential acquisition failures, execute critical business logic, and release the lock in a finally block. ```java @Resource private RedissonClient redissonClient; public void createOrder(String orderId) throws InterruptedException { RLock lock = redissonClient.getLock("order:lock:" + orderId); boolean locked = lock.tryLock(0, 30, TimeUnit.SECONDS); if (!locked) { throw new RuntimeException("System is busy, please try again later"); } try { // Business logic } finally { if (lock.isHeldByCurrentThread()) { lock.unlock(); } } } ``` -------------------------------- ### Pagination Parameter Usage Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/common-spring-boot-starter Demonstrates using the `PageParam` object for handling pagination in API requests. It encapsulates page number and size. ```java @PostMapping("/page") public BaseResult> page(@RequestBody PageParam page) { // page.getPageNum() / page.getPageSize() return BaseResult.success(userService.page(page)); } ``` -------------------------------- ### Redis Hash Operations (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Provides methods for interacting with Redis Hash data structures. Supports setting, getting, checking existence, deleting fields, and incrementing/decrementing values within a hash. Some methods support setting expiration times. ```java RedisUtil.hSet(String key, Map data) RedisUtil.hSet(String key, String hashKey, Object value) RedisUtil.hSet(String key, Map data, Long expireSeconds) RedisUtil.hSet(String key, String hashKey, Object value, Long expireSeconds) RedisUtil.hGet(String key) RedisUtil.hGet(String key, String hashKey) RedisUtil.hashKey(String key, String hashKey) RedisUtil.hahsDel(String key, String... hashKeys) RedisUtil.increment(String key, String hashKey, long number) ``` -------------------------------- ### RedisUtil Hash Operations Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Illustrates Hash operations using RedisUtil. This includes setting individual fields, setting multiple fields from a map, retrieving a single field, and retrieving all fields from a hash. ```java RedisUtil.hSet("user:profile:" + userId, "nickname", "张三"); RedisUtil.hSet("user:profile:" + userId, Map.of("age", 18, "gender", "M")); Object nickname = RedisUtil.hGet("user:profile:" + userId, "nickname"); Map all = RedisUtil.hGet("user:profile:" + userId); ``` -------------------------------- ### Generate Captcha Image Endpoint Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/image-code-spring-boot-starter This Java code snippet demonstrates how to create a Spring Boot controller endpoint to generate a captcha image. It utilizes the `imageCodeHandler` to get the captcha, returning it as a `BaseResult` containing `ImageCodeRes`. Ensure `imageCodeHandler` is properly injected. ```java @GetMapping("/captcha") public BaseResult captcha() { return BaseResult.success(imageCodeHandler.getImageCode()); } ``` -------------------------------- ### Configure OkHttpClient as a Spring Bean Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/easy-http-spring-boot-starter This Java code demonstrates how to configure OkHttpClient as a Spring Bean. It sets connection, read, and write timeouts for efficient and robust HTTP requests. This approach promotes reuse of connection pools and consistent interceptor application. ```java @Configuration public class OkHttpClientConfig { @Bean public OkHttpClient okHttpClient() { return new OkHttpClient.Builder() .connectTimeout(Duration.ofSeconds(5)) .readTimeout(Duration.ofSeconds(15)) .writeTimeout(Duration.ofSeconds(15)) .build(); } } ``` -------------------------------- ### Configure OSS Properties Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/resource-spring-boot-starter This snippet outlines the necessary OSS configuration properties. These properties, such as endpoint, access key ID, secret, and bucket names, are required for the module to connect to and interact with Alibaba Cloud OSS. ```yaml oss: endpoint: oss-cn-beijing.aliyuncs.com accessKeyId: your-access-key-id accessKeySecret: your-access-key-secret bucketName: your-bucket-name adminBucketName: your-admin-bucket-name # 可选:管理后台专用桶 ``` -------------------------------- ### RedisUtil Key and Expiration Operations Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Demonstrates key management operations with RedisUtil. This includes setting an expiration time for a key, retrieving the time-to-live (TTL) of a key, and deleting one or multiple keys. ```java RedisUtil.expire("user:" + userId, 3600L); Long ttl = RedisUtil.getExpire("user:" + userId); RedisUtil.delKey("user:" + userId); RedisUtil.delKey("k1", "k2", "k3"); ``` -------------------------------- ### SpEL Usage for LogRecord Annotation (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/log-spring-boot-starter This example demonstrates using SpEL expressions within the @LogRecord annotation to dynamically populate fields like 'action' and 'coreParam'. It highlights the use of curly braces `{}` as delimiters and referencing method parameters. Note that direct result referencing is not supported. ```java @LogRecord( action = "创建用户: {#user.username}", coreParam = "入参: {#user}" ) ``` -------------------------------- ### Include Maven Dependency for Image Code Starter Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/image-code-spring-boot-starter To use the image code functionality, include this dependency in your project's pom.xml. This starter module relies on a configured Redis instance for captcha storage and validation. ```xml com.fd.framework image-code-spring-boot-starter ``` -------------------------------- ### Server-Side File Upload to OSS using ImageUploadTool (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/resource-spring-boot-starter This Java code snippet shows how to use `ImageUploadTool` for server-side file uploads to OSS. This is useful when the server needs to perform pre-upload operations like validation or compression before sending the file to OSS. It requires an `ImageUploadTool` instance and a `SendOssReq` object containing file details. ```java @Resource private ImageUploadTool imageUploadTool; @PostMapping("/oss/upload") public BaseResult upload(@RequestParam MultipartFile file) throws IOException { SendOssReq req = new SendOssReq(); req.setAccessKeyId("your-access-key-id"); req.setAccessKeySecret("your-access-key-secret"); req.setOriginalFilename(file.getOriginalFilename()); req.setInputStream(file.getInputStream()); String url = imageUploadTool.uploadFile(req); return BaseResult.success(url); } ``` -------------------------------- ### Generate OSS Signature for Frontend Upload (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/resource-spring-boot-starter This Java code demonstrates how to generate an OSS signature using `OssService`. This is typically used when you want to allow frontend applications to directly upload files to OSS, enhancing performance and reducing server load. It requires an `OssService` instance and `OssProperties` for configuration. ```java @Resource private OssService ossService; @Resource private OssProperties ossProperties; @GetMapping("/oss/sign") public BaseResult sign() { ResourceInfo info = new ResourceInfo() .setResourceType(ResourceTypeEnum.OSS) .setChannelId(ossProperties.getAccessKeyId()) .setAppSecret(ossProperties.getAccessKeySecret()); OssSign sign = ossService.getOssSign(info, ossProperties.getBucketName(), "upload/"); return BaseResult.success(sign); } ``` -------------------------------- ### Redis List Operations (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Operations for manipulating Redis List data structures. Supports pushing elements to the left or right, inserting elements if present, retrieving elements by index, ranging elements, pushing multiple elements, getting list length, and popping elements from either end. ```java RedisUtil.leftPush(String key, Object value) RedisUtil.leftPush(String key, Object value, Long expireSeconds) RedisUtil.index(String key, long index) RedisUtil.range(String key, long start, long end) RedisUtil.leftPushAll(String key, String... values) RedisUtil.leftPushAll(String key, Long expireSeconds, String... values) RedisUtil.rightPush(String key, String value) RedisUtil.rightPushAll(String key, String... values) RedisUtil.leftPushIfPresent(String key, Object value) RedisUtil.rightPushIfPresent(String key, Object value) RedisUtil.listLength(String key) RedisUtil.leftPop(String key) RedisUtil.rightPop(String key) ``` -------------------------------- ### Add orm-spring-boot-starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/orm-spring-boot-starter To use the orm-spring-boot-starter module, you need to add the dependency to your project's pom.xml file. This makes all the ORM capabilities provided by the starter available to your application. ```xml com.fd.framework orm-spring-boot-starter ``` -------------------------------- ### Redis Set Operations (Java) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Methods for managing Redis Set data structures. Includes operations for retrieving all elements, adding elements, adding with expiration, checking for element existence, getting set size, removing elements, randomly selecting elements, popping elements, and performing set difference operations. ```java RedisUtil.sGet(String key) RedisUtil.sGet(String key, Class type) RedisUtil.sAdd(String key, Object... values) RedisUtil.sSetAndTime(String key, Long expireSeconds, Object... values) RedisUtil.sHasKey(String key, Object value) RedisUtil.sGetSetSize(String key) RedisUtil.sRemove(String key, Object... values) RedisUtil.randomSget(String key, long count) RedisUtil.randomSget(String key) RedisUtil.pop(String key) RedisUtil.difference(String key, String destKey) ``` -------------------------------- ### Configure Datasource for ORM Starter Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/orm-spring-boot-starter The orm-spring-boot-starter requires a datasource to be configured in your application's properties or YAML file. This connection information is essential for the starter to interact with your database. ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/your_db?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: root driver-class-name: com.mysql.cj.jdbc.Driver ``` -------------------------------- ### Include log-spring-boot-starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/log-spring-boot-starter This snippet shows how to add the log-spring-boot-starter dependency to your Maven project. Ensure you have a compatible Spring Boot version. ```xml com.fd.framework log-spring-boot-starter ``` -------------------------------- ### Add Common Spring Boot Starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/common-spring-boot-starter This snippet shows how to include the common-spring-boot-starter as a dependency in your Maven project. ```xml com.fd.framework common-spring-boot-starter ``` -------------------------------- ### RedisUtil String Set/Get Operations Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Demonstrates basic String operations using the RedisUtil class. This includes setting a value with and without an expiration time, and retrieving a value. ```java RedisUtil.set("user:" + userId, user); User cached = RedisUtil.get("user:" + userId); RedisUtil.set("sms:code:" + mobile, code, 60L); ``` -------------------------------- ### Generate Mock Data with MockUtil Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/test-spring-boot-starter Illustrates the usage of `util.MockUtil` to generate mock objects and lists. It utilizes `jmockdata` and supports generating lists of mock objects with a specified count. It also highlights the ability to mock complex generic types using `TypeReference`. ```java User mock = MockUtil.mock(User.class); List list = MockUtil.multiMock(User.class, 10); ``` ```java List list = MockUtil.mock(new TypeReference>() {}); ``` -------------------------------- ### Add Excel Spring Boot Starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/excel-spring-boot-starter Include the excel-spring-boot-starter dependency in your project's pom.xml to enable Excel import and export functionalities. ```xml com.fd.framework excel-spring-boot-starter ``` -------------------------------- ### Spring Boot Redis Configuration Notes (Properties) Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Essential configuration notes for Spring Boot Redis, including the requirement for `spring.application.name`, cluster node configuration when `enable-cluster=true`, and considerations for using static vs. instance methods of `RedisUtil`. Also mentions default transaction support for RedisTemplate. ```properties # Must configure spring.application.name for key prefix and client-name. # If enable-cluster=true, spring.redis.cluster.nodes must be configured. # Usage of RedisUtil: # - Static methods are globally accessible. # - Instance methods (e.g., leftPush) require injecting RedisUtil or creating an instance. # - Consider creating a wrapper for consistent usage. # RedisTemplate transaction support is enabled by default. # Disable if Redis transactions are not used to reduce overhead. ``` -------------------------------- ### Maven Dependency for Redis Spring Boot Starter Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Include this dependency in your project's pom.xml to integrate the redis-spring-boot-starter. This starter provides pre-configured Redis functionalities. ```xml com.fd.framework redis-spring-boot-starter ``` -------------------------------- ### Synchronous Chat Completion with OpenAI Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/ai-spring-boot-starter Demonstrates how to perform a synchronous chat completion using the AiService. It retrieves the chat service for OpenAI, builds a chat completion request with a user message, and returns the content of the response. ```java @Resource private AiService aiService; public String chatOnce() throws Exception { IChatService chatService = aiService.getChatService(PlatformType.OPENAI); ChatCompletion req = ChatCompletion.builder() .model("gpt-4o-mini") .message(ChatMessage.withUser("你好,介绍一下 fd-framework")) .build(); ChatCompletionResponse resp = chatService.chatCompletion(req); return resp.getChoices().get(0).getMessage().getContent(); } ``` -------------------------------- ### Add test-spring-boot-starter Dependency Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/test-spring-boot-starter This snippet shows how to include the test-spring-boot-starter dependency in your project's pom.xml file. This dependency is scoped for testing purposes. ```xml com.fd.framework test-spring-boot-starter test ``` -------------------------------- ### Service Isolation and Serialization Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/redis-spring-boot-starter Explanation of how service isolation (key prefixing) and default value serialization (Fastjson2) work, along with security recommendations and customization options. ```APIDOC ## Service Isolation and Serialization ### Description Explanation of how service isolation (key prefixing) and default value serialization (Fastjson2) work, along with security recommendations and customization options. ### Service Isolation (Key Prefixing) - **Configuration**: `spring.redis.service-isolation=true` - **Behavior**: When enabled, Redis keys are automatically prefixed with the `spring.application.name` to isolate data between different services. - Example: A key `user:1` becomes `{spring.application.name}:user:1`. - **Cross-Service Sharing**: To share keys across services, disable this feature (`false`) or use explicit key prefixing. ### Default Value Serialization (Fastjson2) - **Strategy**: Fastjson2 is used for value serialization and deserialization by default. - **Features Enabled**: - **WriteClassName**: Includes type information in serialized JSON for easier deserialization. - **SupportAutoType**: Enables deserialization of JSON with type information. - **Benefits**: Allows seamless `set` and `get` operations with arbitrary objects in most scenarios. ### Security Recommendations - **Untrusted Input**: Avoid deserializing JSON from untrusted sources using autoType, as it has historical security risks. - **Best Practice**: Server-side generation and reading of cache, session, and business keys are recommended to prevent direct exposure of controllable input to Redis deserialization. ### Customizing Serialization - **Requirement**: If you need to use a different serialization strategy (e.g., Jackson, or only String/byte[]), you can customize the `RedisTemplate` bean. - **Configuration**: Ensure `spring.main.allow-bean-definition-overriding=true` is set if you are overriding default beans. ### Important Considerations - **`spring.application.name`**: Must be configured for service isolation and default client name. - **Cluster Mode**: If `enable-cluster=true`, `spring.redis.cluster.nodes` must be configured. - **Static vs. Instance Methods**: `RedisUtil` contains both static and instance methods. For consistency, consider injecting `RedisUtil` and using instance methods or creating your own wrapper. - **Transaction Support**: `RedisTemplate` has transaction support enabled by default (`setEnableTransactionSupport(true)`). Disable if not needed to reduce overhead. ``` -------------------------------- ### Maven Dependency for data-permission-spring-boot-starter Source: https://www.dlightaiflow.com/fd-doc/1.0.0-SNAPSHOT/modules/data-permission-spring-boot-starter This snippet shows how to include the data-permission-spring-boot-starter as a dependency in your Maven project. ```xml com.fd.framework data-permission-spring-boot-starter ```