### Create Moment Response Example Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Example JSON response for a successful request to create a moment, returning the created moment's details. ```JSON { "code": "200", "data": { "id": 42, "userId": "user123", "userModel": null, "content": "New moment content", "gmtCreated": "2024-06-24 14:30:00", "gmtModified": "2024-06-24 14:30:00" }, "msg": null, "traceId": "trace-id-value" } ``` -------------------------------- ### GET /account/detail Response (200 OK) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Example JSON response for a successful retrieval of account details. ```json { "code": "200", "data": { "userId": "user123", "userName": "John Doe" }, "msg": null, "traceId": "trace-id-value" } ``` -------------------------------- ### List Moments API Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Example of how to retrieve a list of moments using a GET request to the moment service via the gateway. Supports pagination with page and pageSize parameters. ```bash curl http://localhost:7001/moment/list?page=1&pageSize=10 ``` -------------------------------- ### List Moments Response Example Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Example JSON response for a successful request to list moments, including pagination details and moment data. ```JSON { "code": "200", "data": [ { "id": 1, "userId": "user123", "userModel": { "userId": "user123", "userName": "John Doe" }, "content": "Moment content here", "gmtCreated": "2023-12-15 10:30:00", "gmtModified": "2023-12-15 10:30:00" } ], "msg": null, "traceId": "trace-id-value", "totalCount": 42, "totalPages": 5, "pageSize": 10, "pageNo": 1, "cursor": null } ``` -------------------------------- ### GET /index Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Renders the login page for user access. ```APIDOC ## GET /index ### Description Renders the login page. ### Method GET ### Endpoint /index ### Response HTML login page template (`login.vm`) ``` -------------------------------- ### POST /account/login Response (200 OK) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Example JSON response for a successful user login, returning a token or session ID. ```json { "code": "200", "data": "login-token-or-session-id", "msg": null, "traceId": "trace-id-value" } ``` -------------------------------- ### Add Moment Success Response Structure Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Example JSON structure for a successful moment creation response. ```json { "code": "200", "data": { "id": 42, "userId": "user123", "userModel": null, "content": "This is my moment", "gmtCreated": "2024-06-24 14:30:00", "gmtModified": "2024-06-24 14:30:00" }, "msg": null, "traceId": "abc-123" } ``` -------------------------------- ### GET /index Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Renders the login page. This endpoint serves the HTML login page template. ```http GET /index ``` -------------------------------- ### Dynamic Datasource Switching Example Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/configuration.md Demonstrates how to switch between datasources using DynamicDataSourceContextHolder before performing database operations. Ensure the DataSourceType enum is correctly configured. ```java DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MOMENT); momentMapper.selectById(123); // Uses test database DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.COMMENT); commentMapper.insert(comment); // Uses test2 database ``` -------------------------------- ### Create Moment API Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Example of how to create a new moment post using a POST request to the moment service via the gateway. Requires content. ```bash curl -X POST http://localhost:7001/moment \ -d "content=My first moment!" ``` -------------------------------- ### Build and Run Spring Cloud Services Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Instructions for setting up the project, including database creation, building modules, and starting services in the correct order. Assumes prerequisites like Java, Maven, MySQL, and Redis are met. ```bash mysql -u root < schema.sql cd spring-cloud-parent && mvn clean install -DskipTests cd ../spring-cloud-client && mvn clean install -DskipTests cd ../spring-cloud-starter && mvn clean install -DskipTests cd ../spring-cloud-eureka && mvn clean spring-boot:run # Port 7003 cd ../spring-cloud-account && mvn clean spring-boot:run # Port 7002 cd ../spring-cloud-biz && mvn clean spring-boot:run # Port 7004 cd ../spring-cloud-gateway && mvn clean spring-boot:run # Port 7001 open http://localhost:7001/index ``` -------------------------------- ### Login Flow Example Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Demonstrates the typical login process: validating credentials, loading user details, establishing a session, and logging the event. Ensure the AccountService is available for validation and detail retrieval. ```java ResultModel authResult = accountService.validateUserIdAndPassword(userId, password); if ("200".equals(authResult.getCode())) { ResultModel userResult = accountService.detail(userId); AccountModel user = userResult.getData(); AccountHelper.setUserId(userId); LOGGER.info("User {} logged in", userId); } ``` -------------------------------- ### Maven Build and Run Commands Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/README.md Commands to clean, install, and run the Spring Cloud microservices in order. Ensure Redis and MySQL are running before execution. ```bash cd spring-cloud-parent mvn clean install -DskipTests cd ../spring-cloud-client mvn clean install -DskipTests cd ../spring-cloud-starter mvn clean install -DskipTests cd spring-cloud-eureka mvn clean spring-boot:run cd spring-cloud-account mvn clean spring-boot:run cd spring-cloud-biz mvn clean spring-boot:run cd spring-cloud-gateway mvn clean spring-boot:run ``` -------------------------------- ### User Login API Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Example of how to perform a user login using a POST request to the account service via the gateway. Requires userId and password. ```bash curl -X POST http://localhost:7001/account/login \ -d "userId=testuser&password=password123" ``` -------------------------------- ### List Comments Data Flow Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/comment-service.md Illustrates the sequence of operations for listing comments, starting from an HTTP GET request and detailing the service calls, database queries, and data transformations involved. ```text GET /comment/{momentId}/list ↓ Gateway CommentController.listCommentsByMomentId() ↓ CommentFeignService.listCommentsByMomentId(momentId) ↓ Biz Service CommentController ↓ CommentServiceImpl.listCommentsByMomentId(momentId) ↓ Check if momentId is null ↓ CommentDoMapper.listCommentsByMomentId() [queries test2 db] ↓ Convert CommentDo → CommentModel (each item) ↓ Return ListResultModel ↓ Render commentList.vm template with data ``` -------------------------------- ### Get Account Details (Account Service) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Feign client interface for retrieving account details by userId. Returns an AccountModel. ```java ResultModel detailByUserId( @RequestParam String userId ); ``` -------------------------------- ### Load Moment with Comments Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/comment-service.md Example of how to retrieve a moment and its associated comments using the comment service. This involves fetching the moment first, then listing comments by the moment ID, and finally attaching the comments to the moment object for display. ```java // 1. Get moment MomentModel moment = getMoment(momentId); // 2. Load comments ListResultModel commentResult = commentService.listCommentsByMomentId(momentId); // 3. Attach to moment List comments = commentResult.getData(); // Display moment and all comments displayMoment(moment); for (CommentModel comment : comments) { displayComment(comment); } ``` -------------------------------- ### Handling Successful API Response (Java) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Example of how to check for a '200' success code and process the data from a ResultModel in Java. ```java ResultModel result = accountService.detail(userId); if ("200".equals(result.getCode())) { AccountModel account = result.getData(); // Process successful response } ``` -------------------------------- ### GET /account/detail Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Retrieves detailed account information for a given user ID. ```APIDOC ## GET /account/detail ### Description Retrieves account details by user ID. ### Method GET ### Endpoint /account/detail ### Parameters #### Query Parameters - **userId** (string) - Required - The ID of the user whose account details are to be retrieved. ### Response #### Success Response (200) ResultModel - Contains the account details. ``` -------------------------------- ### Get User ID from Session Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Demonstrates how to retrieve the current user's ID from the session context using AccountHelper. ```java String userId = AccountHelper.getUserId(); // From session context ResultModel result = momentFeignService.addMoment(userId, content); ``` -------------------------------- ### Client-Side Error Handling Pattern Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md JavaScript example demonstrating how to parse API responses, handle specific error codes, and log trace IDs for support. ```javascript // JavaScript/TypeScript fetch('/api/comment/5/add', { method: 'POST', body: new URLSearchParams({content: 'Great post!'}) }) .then(r => r.json()) .then(result => { if (result.code === '200') { // Success - display comment showComment(result.data); } else if (result.code === 'noThisMoment') { // Specific error handling showAlert('Moment no longer exists'); } else { // Generic error showAlert('Error: ' + result.msg); } // Always log trace ID for support console.log('Trace ID: ' + result.traceId); }) ``` -------------------------------- ### Logging Invalid Parameter Errors (Java) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Example of logging an 'invalidParam' error in Java, including trace ID and relevant parameters. ```java LOGGER.error("traceId:{} addMoment, invalidParam, userId:{}, content:{}", TraceIdHelper.getTraceId(), userId, content); ``` -------------------------------- ### Service Layer Dynamic Datasource Usage Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/dynamic-datasource.md Example of a service method that switches datasources to interact with different databases. It first sets the datasource to MOMENT for verification, then to COMMENT for insertion. ```java import org.springframework.stereotype.Service; import spring.cloud.biz.config.datasourceConfig.DataSourceType; import spring.cloud.biz.config.datasourceConfig.DynamicDataSourceContextHolder; @Service public class CommentServiceImpl implements CommentService { @Override public ResultModel addComment(Long momentId, String content) { // First, verify moment exists in MOMENT database DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MOMENT); MomentDo moment = momentDoMapper.selectByPrimaryKey(momentId); // Then, insert comment in COMMENT database DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.COMMENT); CommentDo comment = new CommentDo(); comment.setMomentId(momentId); comment.setContent(content); commentDoMapper.insert(comment); return ResultModel.createSuccess(comment); } } ``` -------------------------------- ### Add Comment API Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Example of how to add a comment to a specific moment using a POST request to the comment service via the gateway. Requires the moment ID and comment content. ```bash curl -X POST http://localhost:7001/comment/5/add \ -d "content=Great moment!" ``` -------------------------------- ### List Comments for a Moment (GET) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Retrieves a list of comments associated with a specific moment ID. The response includes comment details and pagination information. ```HTTP GET /comment/{momentId}/list ``` ```JSON { "code": "200", "data": [ { "id": 1, "momentId": 5, "content": "Great moment!", "gmtCreated": "2024-06-24 15:00:00", "gmtModified": "2024-06-24 15:00:00" } ], "msg": null, "traceId": "trace-id-value", "totalCount": 3, "totalPages": 1, "pageSize": null, "pageNo": null, "cursor": null } ``` -------------------------------- ### GET /account/detail Request Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Retrieves user account details. An optional userId parameter can be provided; otherwise, it returns the current logged-in user's information. ```http GET /account/detail?userId= ``` -------------------------------- ### Database Creation and Table Schema Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/README.md SQL statements for creating the 'test' and 'test2' databases and their respective tables: 'account', 'moment', and 'comment'. ```sql create database test; CREATE TABLE `account` ( `user_id` varchar(127) NOT NULL DEFAULT '', `user_name` varchar(127) NOT NULL DEFAULT '', `password` varchar(127) NOT NULL DEFAULT '', `gmt_created` datetime NOT NULL, `gmt_modified` datetime DEFAULT NULL, `is_deleted` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`), KEY `index_user_id` (`user_id`) KEY_BLOCK_SIZE=10 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; CREATE TABLE `moment` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` varchar(127) COLLATE utf8mb4_unicode_ci NOT NULL, `content` text COLLATE utf8mb4_unicode_ci, `gmt_created` datetime NOT NULL, `gmt_modified` datetime DEFAULT NULL, `is_deleted` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `index_user_id` (`user_id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; create database test2; CREATE TABLE `comment` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `moment_id` bigint(20) unsigned NOT NULL, `content` text COLLATE utf8mb4_unicode_ci, `gmt_created` datetime NOT NULL, `gmt_modified` datetime DEFAULT NULL, `is_deleted` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `index_moment_id` (`moment_id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ``` -------------------------------- ### GET /health Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Gateway health check endpoint. Used to verify the operational status of the gateway. ```APIDOC ## GET /health ### Description Gateway health check endpoint. ### Method GET ### Endpoint /health ### Response #### Success Response (200) Service health status (varies by implementation) ``` -------------------------------- ### GET /health Endpoint Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md This is the gateway health check endpoint. It is used to monitor the health status of the service. ```http GET /health ``` -------------------------------- ### Multi-Instance Deployment Architecture Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/configuration.md Illustrates a typical multi-instance deployment architecture for a Spring Cloud application, showing the interaction between a load balancer, gateway instances, service instances, and an Eureka cluster. ```text Load Balancer ├── Gateway Instance 1:7001 ├── Gateway Instance 2:7001 ├── Account Instance 1:7002 ├── Account Instance 2:7002 ├── Biz Instance 1:7004 ├── Biz Instance 2:7004 └── Eureka Cluster ├── Eureka Instance 1:7003 ├── Eureka Instance 2:7003 └── Eureka Instance 3:7003 ``` -------------------------------- ### Get Account Detail Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Retrieves detailed information for a specific user account using their user ID. ```APIDOC ## detail ### Description Retrieve account information for a specific user. ### Method Not applicable (Java method signature) ### Endpoint Not applicable (Java method signature) ### Parameters #### Path Parameters - **userId** (String) - Required - User identifier (cannot be empty) ### Request Example ```java ResultModel result = accountService.detail("user123"); if ("200".equals(result.getCode())) { AccountModel account = result.getData(); System.out.println("User: " + account.getUserName()); } else { System.err.println("Error: " + result.getMsg()); } ``` ### Response #### Success Response (200) - **code** (String) - "200" - **data** (AccountModel) - Contains user details like userId and userName. - **msg** (null) - Null on success. - **traceId** (String) - Unique identifier for the request trace. #### Response Example ```json { "code": "200", "data": { "userId": "user123", "userName": "John Doe" }, "msg": null, "traceId": "abc-123" } ``` #### Error Response (Invalid Parameter) ```json { "code": "invalidParam", "data": null, "msg": "User ID is required", "traceId": "abc-123" } ``` #### Error Response (User Not Found) ```json { "code": "noThisUser", "data": null, "msg": "User does not exist", "traceId": "abc-123" } ``` ``` -------------------------------- ### Get Chinese Zodiac Sign Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/utility-functions.md Retrieves the Chinese zodiac sign for a given date. Accepts a `java.util.Date` object. ```java public static String getZodica(Date date) ``` ```java String zodiac = DateUtils.getZodica(new Date(1990, 0, 15)); // Returns: "马" (Horse) ``` -------------------------------- ### Get Object from Cache Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/cache-service.md Retrieves a deserialized object from Redis using its key. Returns null if the object is not found. ```java Object cachedAccount = cacheService.getObject("account:user123"); if (cachedAccount != null) { AccountModel account = (AccountModel) cachedAccount; } ``` -------------------------------- ### PageHelper Pagination Usage Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Shows how to use the PageHelper library to implement database pagination, including setting parameters and processing results. ```java PageHelper.startPage(page, pageSize, "id desc"); List momentDoList = momentDoMapper.listMoment(); PageInfo pageInfo = new PageInfo<>(momentDoList); result.setPageNo(pageInfo.getPageNum()); result.setTotalPages(pageInfo.getPages()); result.setTotalCount(pageInfo.getTotal()); ``` -------------------------------- ### Create Moment (Biz Service) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Feign client interface for creating a new moment. Requires userId and content as parameters. ```java ResultModel addMoment( @RequestParam String userId, @RequestParam String content ); ``` -------------------------------- ### GET /account/detail Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Retrieves the details of a user account. If no userId is provided, it returns the currently logged-in user's information. ```APIDOC ## GET /account/detail ### Description Retrieve user account details. If not provided, returns current logged-in user's information. ### Method GET ### Endpoint /account/detail ### Parameters #### Query Parameters - **userId** (String) - Optional - User ID. If not provided, returns current logged-in user's information ### Response #### Success Response (200 OK) - **code** (String) - Response code - **data** (AccountModel) - User account information - **msg** (null) - Message - **traceId** (String) - Trace ID ### Response Example ```json { "code": "200", "data": { "userId": "user123", "userName": "John Doe" }, "msg": null, "traceId": "trace-id-value" } ``` ``` -------------------------------- ### Java Cross-Database Operations with Data Source Switching Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Shows how to safely perform operations across different databases by dynamically switching the data source context. It verifies data existence in the source database before proceeding. ```java // Pattern: Verify data in source DB before writing to target DB DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.MOMENT); MomentDo moment = mapper.selectByPrimaryKey(momentId); if (null == moment) { LOGGER.error("traceId:{}, moment not found: {}", TraceIdHelper.getTraceId(), momentId); return ResultModel.createFail("noThisMoment"); } DynamicDataSourceContextHolder.setDataSourceType(DataSourceType.COMMENT); // Safe to proceed with insert ``` -------------------------------- ### Get Datasource Type Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/dynamic-datasource.md Retrieves the datasource type currently set for the thread. Defaults to MOMENT if no type has been explicitly set. ```java DataSourceType current = DynamicDataSourceContextHolder.getDataSourceType(); System.out.println("Using datasource: " + current); ``` -------------------------------- ### Index Page Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/modules.md Endpoint to render the login page. ```APIDOC ## GET /index ### Description Renders the main login page for the application. ### Method GET ### Endpoint /index ### Response #### Success Response (200) - HTML content for the login page ``` -------------------------------- ### Get String from Cache Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/cache-service.md Retrieves a cached string value from Redis using its key. Returns null if the key does not exist. ```java String cachedValue = cacheService.getString("config:app.name"); if (cachedValue != null) { System.out.println("App name: " + cachedValue); } ``` -------------------------------- ### Authenticate User with Hashed Password Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Demonstrates how to authenticate a user by comparing a provided password against a stored hash and salt. ```java boolean valid = EncryptUtil.authenticate( providedPassword, storedHash, storedSalt ); ``` -------------------------------- ### Create Moment Data Flow Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Details the process for creating a new moment, including gateway interaction, session retrieval, and database insertion. ```text Controller Request (POST /moment) ↓ Gateway MomentController.addMoment() ↓ Get userId from AccountHelper (session) ↓ MomentFeignService.addMoment(userId, content) ↓ BizApplication MomentController ↓ MomentServiceImpl.addMoment(userId, content) ↓ Validate parameters (not empty) ↓ Create MomentDo object, set fields ↓ MomentDoMapper.insert(MomentDo) ↓ Convert MomentDo → MomentModel ↓ Return ResultModel ``` -------------------------------- ### Handling Invalid Parameter API Response (Java) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Example of checking for an 'invalidParam' error code and displaying the error message in Java. ```java ResultModel result = commentService.addComment(null, ""); if ("invalidParam".equals(result.getCode())) { System.err.println("Error: " + result.getMsg()); // Re-prompt user for valid input } ``` -------------------------------- ### Error Handling for Moment Creation Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Demonstrates how to handle potential exceptions during moment creation. It attempts to add a moment with a null user ID and checks the result code for errors, logging any exceptions. ```java try { ResultModel result = momentService.addMoment(null, "content"); if (!"200".equals(result.getCode())) { System.err.println("Error: " + result.getMsg()); } } catch (Exception e) { LOGGER.error("Service error", e); } ``` -------------------------------- ### Account Service Authentication Failure Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Shows an example of an authentication failure due to an incorrect password, returning the 'wrongUserOrPwd' error code. ```java // When password doesn't match (or user not found) accountService.validateUserIdAndPassword("user123", "wrongpwd"); // Returns code: "wrongUserOrPwd" ``` -------------------------------- ### List Moments (Biz Service) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Feign client interface for listing moments with pagination. Requires page and pageSize parameters. ```java ListResultModel listFirstPageMoment( @RequestParam Integer page, @RequestParam Integer pageSize ); ``` -------------------------------- ### Get Remote IP Address Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/trace-id-helper.md Retrieves the remote client IP address stored for the current thread. Returns null if not set. ```java public static String getRemoteIp() ``` ```java String ip = TraceIdHelper.getRemoteIp(); logger.info("Request from: {}", ip); ``` -------------------------------- ### Eureka Service Registration and Heartbeat Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/configuration.md Details on how services register with Eureka, including default heartbeat configuration and an example of faster failure detection. ```APIDOC ## Eureka Service Discovery ### Service Registration Services auto-register with Eureka on startup. | Service Name | Instance Port | Eureka Config | |--------------|---------------|---------------| | spring.cloud.eureka | 7003 | Self (eureka server) | | spring.cloud.account | 7002 | Default settings | | spring.cloud.biz | 7004 | Default settings | | spring.cloud.gateway | 7001 | Default settings | ### Heartbeat Configuration **Default heartbeat:** 30 seconds (Spring Cloud default) **Demo configuration:** 5 seconds (faster failure detection) ```properties euroka.instance.lease-renewal-interval-in-seconds=5 euroka.instance.lease-expiration-duration-in-seconds=15 ``` ``` -------------------------------- ### Create and Retrieve Moment Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Adds a new moment with a user ID and content, then retrieves the created moment's ID. It then lists the first page of moments to verify the creation. ```java ResultModel createResult = momentService.addMoment( "user123", "Spring Cloud is awesome!" ); if ("200".equals(createResult.getCode())) { MomentModel created = createResult.getData(); long momentId = created.getId(); // List moments to verify creation ListResultModel listResult = momentService.listFirstPageMoment(1, 10); } ``` -------------------------------- ### Example Error Response with Trace ID Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md This JSON structure represents a typical error response, including a unique trace ID for debugging. ```json { "code": "invalidParam", "msg": "Invalid parameters", "traceId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890" } ``` -------------------------------- ### Java Resource Not Found Error Handling Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Illustrates how to handle cases where a requested resource (e.g., a user account) is not found. It logs the error and returns a specific error code. ```java // Pattern: Check existence before operation Optional account = dataAccess.selectByPrimaryKey(userId); if (!account.isPresent()) { LOGGER.error("traceId:{}, user not found: {}", TraceIdHelper.getTraceId(), userId); return ResultModel.createFail("noThisUser"); } ``` -------------------------------- ### GET /comment/{momentId}/list Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Retrieves a list of comments for a specified moment. This endpoint returns an HTML template containing the comment list. ```APIDOC ## GET /comment/{momentId}/list ### Description List comments for a specific moment. ### Method GET ### Endpoint /comment/{momentId}/list ### Parameters #### Path Parameters - **momentId** (Long) - Yes - ID of the moment to fetch comments for (path parameter) ### Response #### Success Response (200 OK) - **code** (string) - - **data** (List) - - **msg** (null) - - **traceId** (string) - - **totalCount** (integer) - - **totalPages** (integer) - - **pageSize** (null) - - **pageNo** (null) - - **cursor** (null) - #### Response Example ```json { "code": "200", "data": [ { "id": 1, "momentId": 5, "content": "Great moment!", "gmtCreated": "2024-06-24 15:00:00", "gmtModified": "2024-06-24 15:00:00" } ], "msg": null, "traceId": "trace-id-value", "totalCount": 3, "totalPages": 1, "pageSize": null, "pageNo": null, "cursor": null } ``` ``` -------------------------------- ### Java Parameter Validation Patterns Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md Demonstrates common patterns for validating input parameters in Java. Includes checks for null or empty strings, multiple parameters using a utility, and object property validation. ```java // Pattern 1: Single parameter check if (Strings.isNullOrEmpty(userId)) { return ResultModel.createFail("invalidParam"); } // Pattern 2: Multiple parameters Optional error = ParamCheckUtils.checkParams( Arrays.asList("userId", "password"), userId, password ); if (error.isPresent()) { return ResultModel.createFail("invalidParam", error.get()); } // Pattern 3: Object validation if (null == momentId || null == content || content.isEmpty()) { return ResultModel.createFail("invalidParam"); } ``` -------------------------------- ### Get Trace ID in Java Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/trace-id-helper.md Retrieves the trace ID for the current thread. This is commonly included in log messages and response objects for correlation. ```java String traceId = TraceIdHelper.getTraceId(); if (traceId != null) { logger.info("Request trace: {}", traceId); } ``` -------------------------------- ### Create Moment Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/modules.md Creates a new moment post. ```APIDOC ## POST /moment ### Description Creates a new moment post. ### Method POST ### Endpoint /moment ### Parameters #### Request Body - **userId** (String) - Required - The ID of the user creating the moment. - **content** (String) - Required - The content of the moment. ``` -------------------------------- ### Get Not Null Property Names - Java Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/utility-functions.md Retrieves an array of property names that are not null in the given object. Useful for identifying populated fields. ```java public static String[] getNotNullPropertyNames(Object source) ``` -------------------------------- ### CacheService Methods Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/cache-service.md The CacheService interface offers methods for putting, getting, and deleting cached objects and strings, with options for setting expiration times. ```APIDOC ## CacheService Interface ### Description Provides Redis-backed caching operations for storing and retrieving both serialized objects and strings with optional TTL support. ### Methods #### `putObject(String key, Object value)` Stores an object in the cache with the given key. #### `putObject(String key, Object value, int expire)` Stores an object in the cache with the given key and an expiration time in seconds. #### `deleteObjectByKey(String key)` Deletes an object from the cache by its key. #### `expire(String key, int expire)` Sets or updates the expiration time for a cached item in seconds. #### `getObject(String key)` Retrieves an object from the cache by its key. #### `putString(String key, String value)` Stores a string in the cache with the given key. #### `putString(String key, String value, int expire)` Stores a string in the cache with the given key and an expiration time in seconds. #### `getString(String key)` Retrieves a string from the cache by its key. ### Exceptions All methods can throw `Exception`. ``` -------------------------------- ### Create Moment Table SQL Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md SQL statement to create the 'moment' table in the database. Includes primary key and user ID index. ```sql CREATE TABLE `moment` ( `id` bigint(20) unsigned NOT NULL AUTO_INCREMENT, `user_id` varchar(127) NOT NULL, `content` text, `gmt_created` datetime NOT NULL, `gmt_modified` datetime DEFAULT NULL, `is_deleted` tinyint(1) DEFAULT '0', PRIMARY KEY (`id`), KEY `index_user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` -------------------------------- ### Moment Service Interface Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Handles business logic related to moments. Use `listFirstPageMoment` for pagination and `addMoment` to create new moments. ```java MomentService.listFirstPageMoment(Integer page, Integer pageSize) ``` ```java MomentService.addMoment(String userId, String content) ``` -------------------------------- ### Cache Configuration Data Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/cache-service.md Use `putString` to cache configuration values like database URLs with a long TTL. This is suitable for data that changes infrequently. ```java String dbUrl = "jdbc:mysql://localhost:3306/test"; cacheService.putString("db.url", dbUrl, 86400); // 24 hours ``` -------------------------------- ### Middleware Authentication Interceptor Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md An example of an interceptor that uses the AccountService to validate a user's existence before allowing a request to proceed. This is useful for securing endpoints. ```java @Component public class AuthenticationInterceptor extends HandlerInterceptorAdapter { @Autowired private AccountService accountService; @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String userId = getUserIdFromSession(request); ResultModel result = accountService.detail(userId); return "200".equals(result.getCode()); } } ``` -------------------------------- ### Add Moment Error Response Structure (Invalid Parameters) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Example JSON structure for an error response when invalid parameters are provided during moment creation. ```json { "code": "invalidParam", "data": null, "msg": "Missing required parameter", "traceId": "abc-123" } ``` -------------------------------- ### POST /moment Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Creates a new moment with the provided user ID and content. ```APIDOC ## POST /moment ### Description Creates a new moment. ### Method POST ### Endpoint /moment ### Parameters #### Query Parameters - **userId** (string) - Required - The ID of the user creating the moment. - **content** (string) - Required - The content of the moment. ### Response #### Success Response (200) ResultModel - Contains the newly created MomentModel. ``` -------------------------------- ### aes_encrypt (CBC mode) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/encrypt-util.md Encrypts a string using AES in CBC mode with an initialization vector. Requires BouncyCastle provider. ```APIDOC ## aes_encrypt (CBC mode) ### Description Encrypt string using AES CBC mode with initialization vector. ### Method Signature ```java public static String aes_encrypt(String sKey, String ivParameter, String sSrc) throws Exception ``` ### Parameters #### Path Parameters - **sKey** (String) - Required - Encryption key - **ivParameter** (String) - Required - Initialization vector (16 bytes) - **sSrc** (String) - Required - Plaintext to encrypt ### Response #### Success Response - **Returns:** String - Hexadecimal-encoded ciphertext #### Throws - **Exception** - Encryption failure, initialization failure ### Algorithm AES/CBC/PKCS7Padding (requires BouncyCastle provider) ### Example ```java String key = "mySecureKey12345"; String iv = "initVector12345"; // 16 bytes String encrypted = EncryptUtil.aes_encrypt(key, iv, "secret data"); ``` ``` -------------------------------- ### Get Null Property Names - Java Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/utility-functions.md Retrieves an array of property names that have null values in the given object. Useful for debugging or conditional logic. ```java public static String[] getNullPropertyNames(Object source) ``` ```java MomentModel model = new MomentModel(); model.setId(123L); // model.content is null String[] nullProps = CopyProperityUtils.getNullPropertyNames(model); // Returns: ["content", "userModel", "gmtCreated", ...] ``` -------------------------------- ### List Moments with Pagination (Java) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Retrieves a paginated list of moments, sorted by creation date descending. Uses PageHelper for pagination and automatically filters out soft-deleted moments. ```java ListResultModel result = momentService.listFirstPageMoment(1, 10); // Result: // { // "code": "200", // "data": [ ... 10 moments ... ], // "totalCount": 42, // "totalPages": 5, // "pageNo": 1, // "pageSize": 10, // "traceId": "abc-123" // } ``` -------------------------------- ### Using Default Datasource Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/dynamic-datasource.md When the datasource is not explicitly set, the system defaults to a predefined datasource (e.g., MOMENT). Clear the datasource type to revert to the default. ```java DynamicDataSourceContextHolder.clearDataSourceType(); // Next operation uses DataSourceType.MOMENT (default) ``` -------------------------------- ### CacheService Interface Definition Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/cache-service.md Defines the contract for Redis-backed caching operations, including methods for putting, getting, and deleting objects and strings, with support for TTL. ```java public interface CacheService { void putObject(String key, Object value) throws Exception; void putObject(String key, Object value, int expire) throws Exception; void deleteObjectByKey(String key) throws Exception; void expire(String key, int expire) throws Exception; Object getObject(String key) throws Exception; void putString(String key, String value) throws Exception; void putString(String key, String value, int expire) throws Exception; String getString(String key) throws Exception; } ``` -------------------------------- ### Account Service with @RefreshScope Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Enables dynamic configuration refresh for the Account Service without requiring a restart. Use when configuration properties need to be updated on the fly. ```java import org.springframework.cloud.context.config.annotation.RefreshScope; import org.springframework.stereotype.Service; @Service("accountService") @RefreshScope public class AccountServiceImpl implements AccountService { // Configuration can be refreshed without restart } ``` -------------------------------- ### List Moments Data Flow Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Illustrates the sequence of calls for listing moments, from controller request to database query and result transformation. ```text Controller Request ↓ Gateway ListMomentController ↓ MomentFeignService (Feign call to biz service) ↓ BizApplication MomentController ↓ MomentServiceImpl.listFirstPageMoment() ↓ PageHelper.startPage(page, pageSize, "id desc") ↓ MomentDoMapper.listMoment() [queries database] ↓ PageInfo wraps results with pagination metadata ↓ Convert MomentDo → MomentModel (property copy) ↓ Return ListResultModel ``` -------------------------------- ### Production Authorization Check Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/comment-service.md This snippet demonstrates how to implement authorization checks in a production environment to verify if a user owns a moment or is an administrator before allowing comment actions. ```java String currentUserId = AccountHelper.getUserId(); // Verify user owns the moment or is admin if (!isOwner(momentId, currentUserId) && !isAdmin(currentUserId)) { return ResultModel.createFail("notAuthorized"); } ``` -------------------------------- ### List Moments with Pagination Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Retrieves the first page of moments with specified page number and size. Checks the response code and iterates through the moments to print their content and pagination details. ```java ListResultModel result = momentService.listFirstPageMoment(1, 20); if ("200".equals(result.getCode())) { for (MomentModel moment : result.getData()) { System.out.println(moment.getContent()); } System.out.println("Page " + result.getPageNo() + " of " + result.getTotalPages()); } ``` -------------------------------- ### Create New Moment Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Creates a new moment with provided text content. The content parameter is mandatory and cannot be empty. Uses AccountHelper to determine the current user ID. ```HTTP POST /moment Content-Type: application/x-www-form-urlencoded content= ``` -------------------------------- ### Get Zodiac Constellation Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/utility-functions.md Determines the zodiac constellation based on month and day. Month should be between 1-12 and day between 1-31. Returns an empty string for invalid dates. ```java public static String getConstellation(int month, int day) ``` ```java String constellation = DateUtils.getConstellation(3, 21); // Returns: "白羊座" (Aries) ``` -------------------------------- ### List Comments by Moment ID (Biz Service) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/endpoints.md Feign client interface for listing comments for a specific moment. Requires momentId as a path variable. ```java ListResultModel listCommentsByMomentId( @PathVariable Long momentId ); ``` -------------------------------- ### Database Query for User Existence Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/errors.md SQL query to select a user from the account table, ensuring they are not soft-deleted. ```sql SELECT * FROM account WHERE user_id = 'userId' AND is_deleted = 0 ``` -------------------------------- ### Account Detail Caching Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Example of caching account details using Spring's @Cacheable annotation. This improves performance by storing frequently accessed user data in a cache named 'accountCache', keyed by userId. ```java import org.springframework.cache.annotation.Cacheable; @Cacheable(value = "accountCache", key = "#userId") public ResultModel detail(String userId) { // ... } ``` -------------------------------- ### Account Service Interface Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Manages user accounts and authentication. Use `detail` to retrieve user information and `validateUserIdAndPassword` for login validation. ```java AccountService.detail(String userId) ``` ```java AccountService.validateUserIdAndPassword(String userId, String password) ``` -------------------------------- ### Moment Service Spring Configuration Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Java code demonstrating the Spring Service configuration for MomentServiceImpl. This service can be injected by its bean name 'momentService'. ```java @Service("momentService") public class MomentServiceImpl implements MomentService { @Autowired private MomentDoMapper momentDoMapper; // ... } ``` -------------------------------- ### Account Database Schema Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/account-service.md Defines the structure of the 'account' table in the 'test' database. Includes fields for user identification, credentials, audit timestamps, and a soft delete flag. ```sql CREATE TABLE `account` ( `user_id` varchar(127) NOT NULL DEFAULT '', `user_name` varchar(127) NOT NULL DEFAULT '', `password` varchar(127) NOT NULL DEFAULT '', `gmt_created` datetime NOT NULL, `gmt_modified` datetime DEFAULT NULL, `is_deleted` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`user_id`), KEY `index_user_id` (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; ``` -------------------------------- ### Dynamic Data Source API Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Enables dynamic routing to multiple data sources and manages the data source context. ```APIDOC ## Dynamic Data Source API ### Description Enables dynamic routing to multiple data sources and manages the data source context. ### Enumerations - `DataSourceType`: MOMENT, COMMENT ### Methods - `DynamicDataSourceContextHolder.setDataSourceType(type)`: Sets the data source type for the current context. - `DynamicDataSourceContextHolder.getDataSourceType()`: Retrieves the current data source type. - `DynamicDataSourceContextHolder.clearDataSourceType()`: Clears the data source type from the current context. - `manageCrossDatabaseTransactions()`: Example of handling transactions across different data sources. ``` -------------------------------- ### Encrypt Util API Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/README.md Offers a suite of cryptographic utilities for hashing, encryption, and password management. ```APIDOC ## Encrypt Util API ### Description Offers a suite of cryptographic utilities for hashing, encryption, and password management. ### Methods - `hashMD5(data)`: Computes the MD5 hash of the input data. - `hashSHA1(data)`: Computes the SHA-1 hash of the input data. - `encryptAES(data, key, mode)`: Encrypts data using AES in ECB or CBC mode. - `decryptAES(data, key, mode)`: Decrypts data using AES in ECB or CBC mode. - `encryptRSA(data, publicKey)`: Encrypts data using RSA public key encryption. - `hashPasswordPBKDF2(password)`: Hashes a password using PBKDF2. - `generateSalt()`: Generates a random salt for password hashing. ``` -------------------------------- ### Add New Moment (Java) Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Creates a new moment with the provided user ID and content. Includes validation for required parameters and details automatic field population. ```java ResultModel result = momentService.addMoment( "user123", "Just completed my spring-cloud demo!" ); if ("200".equals(result.getCode())) { MomentModel created = result.getData(); System.out.println("Moment created with ID: " + created.getId()); } ``` -------------------------------- ### Copy All Properties - Java Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/utility-functions.md Copies all properties from a source object to a target object using Spring BeanUtils. Ensure both objects have compatible property types. ```java public static void copyAllProperies(Object source, Object target) ``` ```java MomentDo momentDo = momentMapper.selectById(123); MomentModel momentModel = new MomentModel(); CopyProperityUtils.copyAllProperies(momentDo, momentModel); // Now momentModel has all properties from momentDo ``` -------------------------------- ### Create Moment Source: https://github.com/chxfantasy/spring-cloud-demo/blob/master/_autodocs/api-reference/moment-service.md Creates a new moment. The user ID is obtained from the session context. ```APIDOC ## POST /moment ### Description Creates a new moment with the provided content. The user ID is automatically determined from the session. ### Method POST ### Endpoint /moment ### Parameters #### Query Parameters - **userId** (String) - Required - The ID of the user creating the moment. - **content** (String) - Required - The content of the moment. ### Request Example { "userId": "user123", "content": "My first moment!" } ### Response #### Success Response (200) - **data** (MomentModel) - The created moment object. #### Response Example { "data": { "id": "87654321-e89b-12d3-a456-426614174000", "userId": "user123", "content": "My first moment!", "createdAt": "2023-10-27T10:05:00Z" } } ```