### Simple Redis Operations Example Source: https://github.com/yl-yue/yue-library/blob/master/yue-library-data-redis/README.md Demonstrates basic Redis operations like setting, getting, deleting values, and acquiring/releasing distributed locks using the injected Redis client. ```java @Repository public class DataRedisExampleDAO { @Autowired Redis redis;// 直接注入即可 /** * 示例 */ public void example() { String key = "key"; String value = "value"; String lockKey = "lockKey"; long lockTimeout = 3600L; // 设置值 redis.set(key, value); // 获得值 redis.get(key); // 删除值 redis.del(key); // 分布式锁-加锁 redis.lock(lockKey, lockTimeout); // 分布式锁-解锁 redis.unlock(lockKey, lockTimeout); } } ``` -------------------------------- ### Example JSON Response Source: https://github.com/yl-yue/yue-library/blob/master/docs/quickstart.md This is an example of a successful JSON response format from the test controller, indicating the integration is working. ```json { "code": 200, "msg": "成功", "flag": true, "data": {} } ``` -------------------------------- ### Using System Proxies in Java Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/网络代理.md Enable Java to use system-wide proxy settings. This must be set before the project starts. ```java public static void main(String[] args) throws Exception { NetProxy.useSystemProxies();// 使用系统代理需要在项目启动之前进行设置 SpringApplication.run(TestApplication.class, args); } ``` -------------------------------- ### Usage Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/二级缓存.md Demonstrates how to use JetCache annotations for caching operations on a UserService interface. ```APIDOC ## Usage Example This example shows how to apply JetCache annotations to a Java interface for caching. ```java public interface UserService { @Cached(name="userCache:", key="#userId", cacheType = CacheType.BOTH, syncLocal = true, expire = 3600) User getUserById(long userId); @CacheUpdate(name="userCache:", key="#user.userId", value="#user") void updateUser(User user); @CacheInvalidate(name="userCache:", key="#userId") void deleteUser(long userId); } ``` ``` -------------------------------- ### Continuous Consumption of Delayed Messages in Java Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/有界阻塞队列与延迟队列.md Provides examples of setting up continuous consumption for delayed messages using a callback. This listener should ideally be started once. ```java delayedQueue.consumerDelayedMsg(msg -> { System.out.println(msg); }); ``` -------------------------------- ### Controller Exception Handling Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/统一异常处理.md Demonstrates how to throw a `ParamException` from a controller endpoint for unified handling. ```java @PostMapping("/exception") public Result exception() { throw new ParamException("异常测试"); } ``` -------------------------------- ### Example API Response Source: https://github.com/yl-yue/yue-library/blob/master/docs/README.md This is an example of a successful API response in JSON format, as handled by Yue Library's Result wrapper. ```json { "code": 200, "msg": "成功", "flag": true, "traceId": "a1bde0ba625de731", "data": {} } ``` -------------------------------- ### Example API Response Source: https://github.com/yl-yue/yue-library/blob/master/README.md This is an example of a typical RESTful API response structure provided by Yue-Library, indicating a successful operation. ```json { "code": 200, "msg": "成功", "flag": true, "traceId": "a1bde0ba625de731", "data": {} } ``` -------------------------------- ### Console Log Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/samples/template-boot.md This log output demonstrates the request details captured by the HttpAspect, including IP address, URI, method, and the handler method invoked. ```log 2021-07-21 14:40:02.940 INFO 40720 --- [nio-8080-exec-1] a.y.l.template.boot.aspect.HttpAspect : requestIp=0:0:0:0:0:0:0:1 2021-07-21 14:40:02.940 INFO 40720 --- [nio-8080-exec-1] a.y.l.template.boot.aspect.HttpAspect : requestUri=/auth/v1.2/user/listAll 2021-07-21 14:40:02.940 INFO 40720 --- [nio-8080-exec-1] a.y.l.template.boot.aspect.HttpAspect : requestMethod=GET 2021-07-21 14:40:02.941 INFO 40720 --- [nio-8080-exec-1] a.y.l.template.boot.aspect.HttpAspect : requestHandlerMethod=ai.yue.library.template.cloud.controller.user.AuthUserController.listAll() 2021-07-21 14:40:02.977 DEBUG 40720 --- [nio-8080-exec-1] druid.sql.Statement : {conn-10001, pstmt-20000} Parameters : [] 2021-07-21 14:40:02.977 DEBUG 40720 --- [nio-8080-exec-1] druid.sql.Statement : {conn-10001, pstmt-20000} Types : [] 2021-07-21 14:40:03.025 DEBUG 40720 --- [nio-8080-exec-1] druid.sql.Statement : {conn-10001, pstmt-20000} executed. SELECT * FROM `user` WHERE 1 = 1 2021-07-21 14:40:03.103 DEBUG 40720 --- [nio-8080-exec-1] druid.sql.Statement : {conn-10001, pstmt-20000} closed ``` -------------------------------- ### Configure Dynamic Data Source Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/快速开始.md Configure the dynamic data source in your application.yml or bootstrap.yml file. This example sets up a primary MySQL data source. ```yaml spring: datasource: dynamic: primary: mysql strict: false datasource: mysql: url: jdbc:mysql://localhost:3306/database??characterEncoding=utf-8&useSSL=false&rewriteBatchedStatements=true username: root password: 02194096e7d840a992a2f627629a94da ``` -------------------------------- ### Console Output for Assertions Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/统一异常处理.md Example console output demonstrating the behavior of different `Assert` methods when handling exceptions. ```log 不抛出异常 ResultException(businessId=0, result=Result(code=600, msg=抛出异常, flag=false, traceId=null, data=null)) 17:56:35.189 [main] WARN ai.yue.library.base.util.Assert - 打印异常消息 17:56:35.191 [main] WARN ai.yue.library.base.util.Assert - 打印异常堆栈 java.lang.ArithmeticException: / by zero at ai.yue.library.test.jdbc.AssertTest.lambda$assertException$4(AssertTest.java:43) at ai.yue.library.base.util.Assert.notThrowIfErrorPrintStackTrace(Assert.java:54) at ai.yue.library.test.jdbc.AssertTest.assertException(AssertTest.java:42) ... 6 more ``` -------------------------------- ### API Response Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/samples/template-boot.md This is an example of a successful API response for fetching a list of users. It adheres to RESTful conventions with a 'code', 'msg', and 'data' structure. ```json { "code": 200, "msg": "成功", "flag": true, "count": null, "data": [ { "id": 10, "sortIdx": null, "deleteTime": 0, "createTime": "2018-08-07 02:30:48", "updateTime": "2021-07-21 11:59:00", "userId": null, "cellphone": "18523246310", "password": "uyJPQmQgEaVE99McVoV2zg==", "nickname": "张三丰", "email": null, "headImg": "ss.png", "birthday": null, "sex": "man", "userStatus": "normal" }, { "id": 18, "sortIdx": null, "deleteTime": 0, "createTime": "2018-07-18 09:10:46", "updateTime": "2021-07-21 11:59:00", "userId": null, "cellphone": "18522146311", "password": "8uXhwp4c3mYwizx/FKfY6wQRltvBd6Oc0qZvYZa+nfQ=", "nickname": "测试", "email": null, "headImg": "http://www.baidu.com", "birthday": null, "sex": "man", "userStatus": "normal" } ] } ``` -------------------------------- ### Custom Log Storage Provider (MQ Example) Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/log/微服务日志.md Implement the LogStorageProvider SPI to customize log persistence logic, such as sending logs to an MQ topic. This custom implementation will take precedence over built-in providers. ```java @Component public class MqLogStorageProvider implements LogStorageProvider { @Resource private RocketMQTemplate rocketMQTemplate; @Override public void storeLoginLog(LoginLogEntity entity) { rocketMQTemplate.convertAndSend("log-login-topic", entity); } @Override public void storeOperLog(OperLogEntity entity) { rocketMQTemplate.convertAndSend("log-oper-topic", entity); } } ``` -------------------------------- ### API Version Controller Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/RESTful.md Demonstrates how to use the @ApiVersion annotation on controller methods to manage different API versions, including deprecated endpoints. ```java @ApiVersion(2) @RestController @RequestMapping("/{version}/apiVersion") public class ApiVersionConroller { // 配合RESTful接口规约 // @RequestMapping("/open/{version}/apiVersion") // public class OpenApiVersionConroller { // @RequestMapping("/auth/{version}/apiVersion") // public class AuthApiVersionConroller { /** * get *

弃用API接口版本演示 * * @param version * @return */ @ApiVersion(deprecated = true) @GetMapping("/get") public Result get(@PathVariable String version) { return R.success("get:" + version); } /** * get2 * * @param version * @return */ @ApiVersion(value = 2, deprecated = true) @GetMapping("/get") public Result get2(@PathVariable String version) { return R.success("get2:" + version); } /** * get3 * * @param version * @return */ @ApiVersion(3.1) @GetMapping("/get") public Result get3(@PathVariable String version) { return R.success("get3:" + version); } /** * get4 * * @param version * @return */ @ApiVersion(4) @GetMapping("/get") public Result get4(@PathVariable String version) { return R.success("get4:" + version); } } ``` -------------------------------- ### Implement a Test Controller with Yue Library Features Source: https://github.com/yl-yue/yue-library/blob/master/docs/quickstart.md Create a REST controller to test API endpoints. This example demonstrates using `JSONObject` for parameter reception and `R.success` for standardized responses, leveraging Yue Library's enhanced features. ```java @RestController @RequestMapping("/quickstart") public class QuickstartController { @GetMapping("/get") public Result get(JSONObject paramJson) { return R.success(paramJson); } } ``` -------------------------------- ### Interface Input Parameter (IPO) Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/Mapper、Service、Controller示例.md Defines an IPO class for interface input parameters, including validation annotations. Used for data transfer into the service layer. ```java import lombok.Data; import lombok.NoArgsConstructor; import lombok.AllArgsConstructor; import javax.validation.constraints.NotNull; import com.yl.base.validation.ValidationGroups; @Data @NoArgsConstructor @AllArgsConstructor public class TableExampleIPO { /** * 有序主键 */ @NotNull(groups = ValidationGroups.Update.class) private Long id; private String fieldOne; private String fieldTwo; private String fieldThree; private String tenantSysId; private String tenantCoId; } ``` -------------------------------- ### PostgreSQL Sequence Creation Syntax Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/SQL方言.md Examples of creating sequences for auto-incrementing primary keys in PostgreSQL. Each table should have a unique sequence to avoid ID gaps. ```sql CREATE SEQUENCE table_name_id_seq START 1; # 创建一个命名为table_name_id_seq的自增序列,从1开始自增 CREATE SEQUENCE table_test_id_seq START 10; # 创建一个命名为table_test_id_seq的自增序列,从10开始自增 CREATE SEQUENCE table_demo_id_seq START 1456465; # 创建一个命名为table_demo_id_seq的自增序列,从1456465开始自增 ``` -------------------------------- ### RESTful Controller Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/Mapper、Service、Controller示例.md A Spring REST controller implementing RESTful API endpoints for the TableExample resource. It uses the TableExampleService for business logic. ```java import io.swagger.annotations.ApiVersion; import lombok.AllArgsConstructor; import com.yl.example.service.TableExampleService; import com.yl.base.result.Result; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.GetMapping; import javax.validation.Valid; import com.yl.example.ipo.TableExampleIPO; @AllArgsConstructor @ApiVersion(1) @RestController @RequestMapping("/auth/{version}/tableExample") public class AuthTableExampleController { TableExampleService tableExampleService; /** * 插入数据 */ @PostMapping("/insert") public Result insert(@Valid TableExampleIPO tableExampleIPO) { return tableExampleService.insert(tableExampleIPO); } /** * 分页 */ @GetMapping("/page") public Result page(String fieldOne, String fieldTwo) { return tableExampleService.page(fieldOne, fieldTwo); } } ``` -------------------------------- ### i18n Resource File Examples Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/i18n.md Define default and language-specific messages in properties files. The system matches the `Accept-Language` header to the corresponding file (e.g., `messages_zh_CN.properties` for `zh-CN`). ```properties # messages_zh_CN.properties ai.yue.library.base.view.ResultEnum.SUCCESS.msg = 成功 ai.yue.library.base.view.ResultEnum.LOGGED_IN.msg = 会话未注销,无需登录 # messages_en.properties ai.yue.library.base.view.ResultEnum.SUCCESS.msg = success ai.yue.library.base.view.ResultEnum.LOGGED_IN.msg = The session is not logged out, so you do not need to log in ``` -------------------------------- ### Setting Linux Network Proxy Environment Variables Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/网络代理.md Configure proxy settings by exporting environment variables. `all_proxy` sets a global proxy, while `no_proxy` specifies hosts that should bypass the proxy. This example demonstrates setting a proxy and then defining local and remote hosts to exclude. ```bash vi /etc/profile export all_proxy=192.168.0.2:3128 # 代理服务器地址及认证信息 no_proxy_local=localhost,127.0.0.1,0.0.0.0,10.0.0.0/8 no_proxy_1=192.168.3.1 no_proxy_2=$(echo 192.168.0.{65..69} | sed 's/ /,/g') no_proxy_3=$(echo 10.15.65.{90..110} | sed 's/ /,/g') export no_proxy=${no_proxy_local},${no_proxy_1},${no_proxy_2},${no_proxy_3} # 不需要代理的IP source /etc/profile && curl www.baidu.com ``` -------------------------------- ### JetCache Batch API Usage Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/二级缓存.md Demonstrates using JetCache batch operations to retrieve, update, and store multiple cache entries. It checks if all requested keys are present in the cache and fetches missing data from the database, then updates the cache. ```java public Result getCacheBatch(Set ids) { // 查询缓存 Map all = cacheTest.getAll(ids); if (all.size() != ids.size()) { System.out.println("未命中Redis缓存,使用JDBC去数据库查询数据。"); // 查询数据库 List list = tableExampleService.listByIds(ids); for (TableExampleStandard tableExampleStandard : list) { all.put(tableExampleStandard.getId(), tableExampleStandard); } // 设置缓存 cacheTest.putAll(all); } return R.success(all); } ``` -------------------------------- ### Basic Parameter Parsing Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/web/请求参数解析与包装.md Demonstrates how the basic parameter parser handles various data types like String, int, and boolean, without distinguishing between query and body parameters. It also enhances deserialization for multiple date formats and serializes dates to a unified 'yyyy-MM-dd HH:mm:ss' format. ```java @PostMapping public Result post(String v1, int v2, boolean v3, v4 v5 ...) ``` -------------------------------- ### Get Symmetric Key API Source: https://github.com/yl-yue/yue-library/blob/master/docs/base-crypto/密钥交换加解密.md This section describes the API endpoint for obtaining a symmetric encryption key. It includes a JavaScript example for making the request and scripts for pre-processing (generating RSA keys) and post-processing (decrypting the AES key). ```APIDOC ## POST /open/v2.6/keyExchange/getSymmetricKey ### Description This endpoint is used by the client to obtain a symmetric encryption key (AES key) from the server. The request involves exchanging RSA public keys to securely transmit the AES key. ### Method POST ### Endpoint /open/v2.6/keyExchange/getSymmetricKey ### Parameters #### Request Body - **sessionKey** (string) - Required - Session key for authentication. - **exchangeKeyType** (string) - Required - Specifies the key exchange type, e.g., "RSA_AES". - **clientPublicKey** (string) - Required - The client's public RSA key in Base64 format. ### Request Example ```js var formdata = new FormData(); formdata.append("sessionKey", "3af180d408e04d3fb6a6df4cad95c78d"); formdata.append("exchangeKeyType", "RSA_AES"); formdata.append("clientPublicKey", "{{publicKeyBase64}}"); var requestOptions = { method: 'POST', body: formdata, redirect: 'follow' }; fetch("localhost:8080/open/v2.6/keyExchange/getSymmetricKey", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); ``` ### Pre-processing Script (Generate RSA Keys) This script generates an RSA key pair and extracts the public key in Base64 format for use in the API request. ```js const rsa = require('jsrsasign'); // Generate RSA key pair var keypair = rsa.KEYUTIL.generateKeypair("RSA", 1024); const publicKeyPEM = rsa.KEYUTIL.getPEM(keypair.pubKeyObj); const privateKeyPEM = rsa.KEYUTIL.getPEM(keypair.prvKeyObj, "PKCS8PRV"); // Remove PEM identifiers and newlines const publicKeyBase64 = publicKeyPEM .replace(/-----BEGIN PUBLIC KEY-----/g, '') // Remove start identifier .replace(/-----END PUBLIC KEY-----/g, '') // Remove end identifier .replace(/\s+/g, ''); // Remove all whitespace characters, including newlines console.log("Public Key:", publicKeyBase64); console.log("Private Key:", privateKeyPEM); pm.variables.set("publicKeyBase64", publicKeyBase64); pm.variables.set("privateKeyPEM", privateKeyPEM); ``` ### Post-processing Script (Decrypt AES Key) This script uses the generated RSA private key to decrypt the symmetric key returned by the server. ```js const rsa = require('jsrsasign'); // Get RSA private key const privateKeyPEM = pm.variables.get("privateKeyPEM"); // Decrypt with private key var encryptedBase64 = pm.response.json().data.clientPublicKeyEncryptSymmetricKey; const decryptedHex = rsa.b64tohex(encryptedBase64); // Decode Base64 to Hex console.log(decryptedHex); const prvKeyObj = rsa.KEYUTIL.getKey(privateKeyPEM); const decrypted = rsa.KJUR.crypto.Cipher.decrypt(decryptedHex, prvKeyObj); console.log("Decrypted Plaintext:", decrypted); var json = pm.response.json(); json.data.aesKey = decrypted; pm.response.setBody(json); ``` ### Response #### Success Response (200) - **code** (integer) - Response status code, 200 indicates success. - **msg** (string) - Success message. - **flag** (boolean) - Indicates if the operation was successful. - **traceId** (string) - Trace ID for debugging. - **data** (object) - Contains encryption details. - **enabled** (boolean) - Indicates if encryption is enabled. - **clientPublicKeyEncryptSymmetricKey** (string) - The symmetric key encrypted with the client's public RSA key. - **aesKey** (string) - The decrypted symmetric AES key (available after post-processing). #### Response Example ```json { "code": 200, "msg": "成功", "flag": true, "traceId": "", "data": { "enabled": true, "clientPublicKeyEncryptSymmetricKey": "mdxfGftnTaEjjpRIbXgsne9Dk8OvSGmOgTmQYE35xnQpZPMX7gzYq0gTAfNbDDOGyXKXdFcPpsDgSW4F0+1z3XSiqUv8OggRntAlUrXiefo24qxMbHBkxwL+l5Wy3kr90QmIANyHi4KXUsC3goXBnmUi9L/aRBl1d0BKSZsQq+g=", "aesKey": "hnz7cx5vbEUU9GlZ" } } ``` ``` -------------------------------- ### 启用 yue-library 默认配置 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/log/快速开始.md 在 application.yml 或 bootstrap.yml 文件中配置 spring.profiles.active 为 yue。 ```yaml spring: profiles: group: "yue": "yue-library-web,yue-library-data-mybatis,yue-library-data-redis" active: yue ... ``` -------------------------------- ### 配置 logback 标准模板 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/log/快速开始.md 在 application.yml 文件中添加 logging.config 配置以启用内置的 logback 配置。 ```yaml logging: config: classpath:yue-logback-spring.xml ``` -------------------------------- ### Service Layer CRUD Operations Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/Mapper、Service、Controller示例.md Implements service layer logic using MyBatis-Plus's ServiceImpl for common CRUD operations like insert, delete, update, and query. Includes pagination example. ```java import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.yl.base.result.R; import com.yl.base.result.Result; import com.yl.example.entity.TableExample; import com.yl.example.ipo.TableExampleIPO; import com.yl.example.mapper.TableExampleMapper; import com.yl.base.utils.ServletUtils; import com.yl.base.utils.Convert; import org.springframework.stereotype.Service; import java.util.ArrayList; import java.util.List; @Service public class TableExampleService extends ServiceImpl { // 插入数据 public Result insert(TableExampleIPO tableExampleIPO) { TableExample tableExample = Convert.toJavaBean(tableExampleIPO, TableExample.class); super.save(tableExample); return R.success(tableExample); } // 删除数据 public Result deleteById() { boolean b = super.removeById(666666L); return R.success(b); } // 更新数据 public Result updateById() { boolean b = super.updateById(new TableExample()); return R.success(b); } // 查询数据 public Result getById() { TableExample tableExample = super.getById(666666L); return R.success(tableExample); } // 分页 public Result page(String fieldOne, String fieldTwo) { PageHelper.startPage(ServletUtils.getRequest()); List list = super.lambdaQuery() .eq(TableExample::getFieldOne, fieldOne) .eq(TableExample::getFieldTwo, fieldTwo) .list(); PageInfo pageInfo = PageInfo.of(list); return R.success(pageInfo); } // 更多方法示例 public void example() { // insert super.save(new TableExample()); super.saveOrUpdate(new TableExample()); super.saveBatch(new ArrayList<>()); super.saveOrUpdateBatch(new ArrayList<>()); // delete super.removeById(666666L); super.removeByIds(new ArrayList<>()); // update super.updateById(new TableExample()); super.updateBatchById(new ArrayList<>()); // query super.getById(666666L); super.list(); // 更多 super.lambdaQuery(); super.getBaseMapper(); } } ``` -------------------------------- ### Get Data by ID Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/规范示例.md Retrieves a specific data record by its unique identifier. ```APIDOC ## GET /auth/{version}/tableExample/{id} ### Description Retrieves a data record by its ID. ### Method GET ### Endpoint /auth/{version}/tableExample/{id} ### Parameters #### Path Parameters - **id** (Long) - Required - The unique identifier of the data record to retrieve. ### Response #### Success Response (200) - **Result** - The result of the operation, potentially containing the retrieved TableExample object. ``` -------------------------------- ### Activating yue-library Profile Source: https://github.com/yl-yue/yue-library/blob/master/docs/auth/Actuator安全.md This configuration snippet shows how to activate the 'yue-library-auth-client' profile in your application's YAML file to enable the yue-library security optimizations. ```yaml spring: profiles: group: "yue": "yue-library-auth-client" active: yue ... ``` -------------------------------- ### Idempotent API Response (Success) Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/分布式锁与接口幂等性.md Example of a successful API response when the request is not a duplicate. ```json { "code": 200, "msg": "成功", "flag": true, "traceId": "", "data": { "role": "admin", "userStatus": "normal", "cellphone": "18523246334" } } ``` -------------------------------- ### Create a Test Controller Source: https://github.com/yl-yue/yue-library/blob/master/docs/README.md This controller demonstrates how to create a RESTful API endpoint using Yue Library's enhanced features, such as automatic JSON parameter parsing. ```java import com.alibaba.fastjson.JSONObject; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/quickstart") public class QuickstartController { @GetMapping("/get") public Result get(JSONObject paramJson) { return R.success(paramJson); } } ``` -------------------------------- ### Get Validator Instance Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/校验.md Obtain an instance of the Validator through dependency injection or a static method. ```java import javax.validation.Validator; import org.springframework.beans.factory.annotation.Autowired; // ... @Autowired private Validator validator; // or // Validator.getValidatorAndSetParam(email).email("email"); ``` -------------------------------- ### Idempotent API Response (Duplicate) Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/分布式锁与接口幂等性.md Example of an API response indicating a duplicate request, preventing further processing. ```json { "code": 436, "msg": "请勿重复操作", "flag": false, "traceId": "", "data": "【幂等性】幂等校验失败,请求校验参数 key: all,请求校验参数 value: all" } ``` -------------------------------- ### Console Exception Log Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/统一异常处理.md Example of the console log output when an exception is handled by the unified exception handler. ```log ai.yue.library.base.exception.ParamException: 异常测试 at ai.yue.library.template.simple.controller.doc.example.ExceptionController.exception(ExceptionController.java:25) at ai.yue.library.template.simple.controller.doc.example.ExceptionController$$FastClassBySpringCGLIB$$17435ec5.invoke(:-1) at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:218) at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:750) 2020-02-10 22:21:09.986 WARN 33636 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolved [ai.yue.library.base.exception.ParamException: 异常测试] ``` -------------------------------- ### Unified Exception Response Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/统一异常处理.md Example of a unified JSON response for an exception, including code, message, and data. ```json { "code": 433, "msg": "参数校验未通过,请参照API核对后重试", "flag": false, "data": "异常测试" } ``` -------------------------------- ### 实体类 `TableExampleStandard` 示例 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/企业租户tenant_co_id.md 定义了包含 `tenantCoId` 和 `tenantSysId` 字段的实体类,用于 Mybatis 的数据映射。 ```java import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.ToString; import lombok.experimental.SuperBuilder; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableName; @Data @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) @SuperBuilder(toBuilder = true) @EqualsAndHashCode(callSuper = true) @TableName(value = "table_example_standard", autoResultMap = true) public class TableExampleStandard extends BaseEntity { private static final long serialVersionUID = 6404495051119680239L; @TableField(fill = FieldFill.INSERT) String tenantCoId; @TableField(fill = FieldFill.INSERT) String tenantSysId; } ``` -------------------------------- ### Redis 简单使用示例 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/快速开始.md 演示了如何注入 Redis 类并使用其提供的简单命令(如 get, set, delete)、Map 操作、List 操作、分布式锁以及获取 Redisson 客户端。 ```java @Repository public class DataRedisExampleDAO { @Autowired Redis redis;// 直接注入即可 /** * Redis使用示例 */ public void example() { String key = "key"; // value操作 redis.get(key); redis.set(key, "value"); redis.delete(key); // map操作 RMap map = redis.getMap(key); map.get("mapKey"); map.put("mapKey", "str"); // list操作 RList list = redis.getList(key); list.get(0); list.add("str"); // 分布式锁 String lockKey = "lockKey"; int lockTimeoutMs = 3600; LockInfo lock = redis.lock(lockKey, lockTimeoutMs); // 加锁 redis.unlock(lock); // 解锁 // 获得redisson客户端 Redisson redisson = redis.getRedisson(); } } ``` -------------------------------- ### Enable Default yue-library Configuration Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/快速开始.md Optionally, enable yue-library's default configurations, such as printing executable SQL, by setting the active profile in your application.yml or bootstrap.yml. ```yaml spring: profiles: group: "yue": "yue-library-data-mybatis" active: yue ``` -------------------------------- ### MyBatis-Plus Mapper Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/Mapper、Service、Controller示例.md A basic MyBatis-Plus Mapper interface extending BaseMapper for CRUD operations on the TableExample entity. ```java import org.apache.ibatis.annotations.Mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.yl.example.entity.TableExample; @Mapper public interface TableExampleMapper extends BaseMapper { } ``` -------------------------------- ### Add yue-library-web Dependency Source: https://github.com/yl-yue/yue-library/blob/master/docs/auth/LAN接口安全.md Include the yue-library-web dependency to enable the LAN interface security features. No additional dependencies are required. ```xml ai.ylyue yue-library-web ``` -------------------------------- ### Data Source Configuration Variations Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/动态数据源.md Illustrates different ways to structure data source configurations, including multi-master/multi-slave, pure multi-database, and mixed configurations. ```yaml spring: datasource: dynamic: datasource: master_1: master_2: slave_1: slave_2: slave_3: ``` ```yaml spring: datasource: dynamic: datasource: mysql: oracle: sqlserver: postgresql: h2: ``` ```yaml spring: datasource: dynamic: datasource: master: slave_1: slave_2: oracle_1: oracle_2: ``` -------------------------------- ### Thymeleaf i18n Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/i18n.md Integrate i18n directly into Thymeleaf templates using the `#{...}` syntax for dynamic text. ```html 用户登陆 ``` -------------------------------- ### Get Symmetric Key Source: https://github.com/yl-yue/yue-library/blob/master/docs/base-crypto/密钥交换加解密.md Obtain a symmetric key for encrypting/decrypting business data. This endpoint requires configuration `yue.crypto.key-exchange.enable-controller=true` to be effective. ```APIDOC ## POST /open/v2.6/keyExchange/getSymmetricKey ### Description Requests a symmetric key for secure communication. The key is generated by the server and encrypted using the client's public key. ### Method POST ### Endpoint /open/v2.6/keyExchange/getSymmetricKey ### Parameters #### Request Body - **sessionKey** (string) - Required - A session key used to store the generated symmetric key (e.g., token, userId, deviceId). - **exchangeKeyType** (string) - Required - The type of key exchange. Enum values: `RSA_AES`, `SM2_SM4`. - **clientPublicKey** (string) - Required - The public key generated by the client, which the server will use to encrypt the symmetric key. ### Request Example ```json { "sessionKey": "23ef1f9418e84cc884187e1720ac1529", "exchangeKeyType": "RSA_AES", "clientPublicKey": "MIGfMA0GCSqGSIb3DQEBAQUAA4GNAD......2ENHcBoIvEPUwIDAQAB" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the encrypted symmetric key and other relevant information. - **encryptedSymmetricKey** (string) - The symmetric key encrypted with the client's public key. - **sessionKey** (string) - The session key used. - **exchangeKeyType** (string) - The type of key exchange used. #### Response Example ```json { "code": 200, "message": "Success", "data": { "encryptedSymmetricKey": "...", "sessionKey": "23ef1f9418e84cc884187e1720ac1529", "exchangeKeyType": "RSA_AES" } } ``` ``` -------------------------------- ### Performance Test Results Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/类型转换器.md Presents performance benchmarks comparing yue-library's Convert with Spring's native conversion for various data sources (Map, JSON, JavaBean). The results highlight the superior performance of Convert, especially for JSON to JavaBean conversions. ```text 10000条map数据查询耗时:1310 10000条Json数据查询耗时:1304 10000条JavaBean数据查询,使用Spring原生转换耗时:3218 10000条JavaBean数据查询,使用yue-library Convert转换耗时:1885 10000条Json数据转换JavaBean耗时:600 10000条map数据查询耗时:1213 10000条Json数据查询耗时:1228 10000条JavaBean数据查询,使用Spring原生转换耗时:2956 10000条JavaBean数据查询,使用yue-library Convert转换耗时:1797 10000条Json数据转换JavaBean耗时:561 10000条map数据查询耗时:1297 10000条Json数据查询耗时:1253 10000条JavaBean数据查询,使用Spring原生转换耗时:3088 10000条JavaBean数据查询,使用yue-library Convert转换耗时:1849 10000条Json数据转换JavaBean耗时:581 ``` -------------------------------- ### Vue i18n JSON Structure Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/i18n.md Example of a JSON structure for internationalization data used in Vue.js applications, organized by module and component. ```json { "login": { "text": { "title": "系统登录", "prompt": "如无管理员账号,请先创建管理员" }, "field": { "username": "账号", "password": "密码", "captcha": "验证码" }, "button": { "login": "登录" } } } ``` -------------------------------- ### Output of CompletableFuture Execution Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/线程池.md The expected console output when running the CompletableFuture examples with AsyncUtils, showing the order of thread execution and the final results. ```text 异步线程执行1,线程名:utils-exec-2 异步线程执行2,线程名:utils-exec-3 异步线程执行3,线程名:utils-exec-1 3 1 2 ``` -------------------------------- ### Test Endpoint Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/SqlService.md Demonstrates various SQL query methods including single query, parameterized query, multiple SQL execution, and simple type retrieval. ```APIDOC ## POST /data/mybatis/sqlService/test ### Description Executes a series of predefined SQL queries to test different functionalities of the SqlService, such as retrieving JSON objects, Java beans, lists of objects, and handling multiple SQL statements. ### Method POST ### Endpoint /data/mybatis/sqlService/test ### Request Body None ### Response #### Success Response (200) - **queryForJson** (JSONObject) - Result of a single SQL query returning a JSON object. - **queryForJavaBean** (TableExampleStandard) - Result of a single SQL query mapped to a Java bean. - **queryForJsonList** (List) - Result of a parameterized SQL query returning a list of JSON objects. - **queryForJavaBeanList** (List) - Result of a SQL query returning a list of Java beans. - **queryForSimpleType** (Long) - Result of a SQL query returning a single primitive type. - **execMultiSqlForJsonList** (List) - Result of executing multiple SQL statements. #### Response Example { "queryForJson": {}, "queryForJavaBean": {}, "queryForJsonList": [], "queryForJavaBeanList": [], "queryForSimpleType": 0, "execMultiSqlForJsonList": [] } ``` -------------------------------- ### 引入 data-log 模块 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/log/快速开始.md 在父项目的 pom.xml 文件中添加 yue-library-data-log 依赖。 ```xml ai.ylyue yue-library-data-log ``` -------------------------------- ### Idempotent API with @Idempotent Annotation Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/分布式锁与接口幂等性.md Apply the @Idempotent annotation to an API endpoint to prevent duplicate submissions. This example uses a POST request. ```java @Idempotent @PostMapping("/test") public Result test(JSONObject paramJson) { return R.success(paramJson); } ``` -------------------------------- ### Execute Various SQL Queries with SqlService Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/SqlService.md Demonstrates different methods of SqlService for querying data, including single results, lists of JSON objects, Java beans, and simple types. Also shows how to execute multiple SQL statements. ```java @RestController @RequestMapping("/data/mybatis/sqlService") public class SqlServiceController { @Resource SqlService sqlService; @PostMapping("/test") public Result test() { String sql = """ SELECT * FROM table_example_standard LIMIT 1 """ ; String sqlMap = """ SELECT * FROM table_example_standard WHERE id = #{param.id} """ ; JSONObject param = new JSONObject(); param.put("id", 0); String sqlList = """ SELECT * FROM table_example_standard LIMIT 1; SELECT * FROM table_example_standard LIMIT 1; SELECT * FROM table_example_standard_error LIMIT 1; show databases; """ ; JSONObject queryForJson = sqlService.queryForJson("mysql", sql, null); TableExampleStandard queryForJavaBean = sqlService.queryForJavaBean("mysql", sql, null, TableExampleStandard.class); List queryForJsonList = sqlService.queryForJsonList("mysql", sqlMap, param); List queryForJavaBeanList = sqlService.queryForJavaBeanList("mysql", sql, null, TableExampleStandard.class); Long queryForSimpleType = sqlService.queryForSimpleType("mysql", sql, null, Long.class); List execMultiSqlForJsonList = sqlService.execMultiSqlForJsonList("mysql", sqlList, null, null); JSONObject result = new JSONObject(); result.put("queryForJson", queryForJson); result.put("queryForJavaBean", queryForJavaBean); result.put("queryForJsonList", queryForJsonList); result.put("queryForJavaBeanList", queryForJavaBeanList); result.put("queryForSimpleType", queryForSimpleType); result.put("execMultiSqlForJsonList", execMultiSqlForJsonList); return R.success(result); } @PostMapping("/ds") public Result ds(String dsName) { String sql = """ SHOW databases; """ ; List dsNameResult = sqlService.queryForJsonList(dsName, sql, null); List bd_dinky = sqlService.queryForJsonList("bd_dinky", sql, null); List doris = sqlService.queryForJsonList("doris", sql, null); JSONObject result = new JSONObject(); result.put(dsName, dsNameResult); result.put("bd_dinky", bd_dinky); result.put("doris", doris); return R.success(result); } @PostMapping("/execMultiSqlForJsonList") public Result execMultiSqlForJsonList() { String sqlList = """ SELECT * FROM table_example_standard; SELECT * FROM table_example_standard LIMIT 1; SELECT * FROM table_example_eliminate; SELECT * FROM table_example_standard_error LIMIT 1; show databases; """ ; List execMultiSqlForJsonList = sqlService.execMultiSqlForJsonList("mysql", sqlList, null, PageIPO.builder().pageNum(1).pageSize(5).build()); return R.success(execMultiSqlForJsonList); } } ``` -------------------------------- ### Database Entity Example Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/mybatis/Mapper、Service、Controller示例.md Defines a database table mapping entity with fields and MyBatis-Plus annotations. Supports automatic conversion between snake_case and camelCase. ```java import lombok.Data; import lombok.NoArgsConstructor; import lombok.AllArgsConstructor; import lombok.ToString; import lombok.EqualsAndHashCode; import lombok.experimental.SuperBuilder; import com.baomidou.mybatisplus.annotation.FieldFill; import com.baomidou.mybatisplus.annotation.TableField; import com.yl.base.entity.BaseEntity; @Data @NoArgsConstructor @AllArgsConstructor @ToString(callSuper = true) @EqualsAndHashCode(callSuper = true) @SuperBuilder(toBuilder = true) public class TableExample extends BaseEntity { private static final long serialVersionUID = 6404495051119680239L; @TableField(fill = FieldFill.INSERT) String tenantSysId; String tenantCoId; String fieldOne; String fieldTwo; String fieldThree; } ``` -------------------------------- ### Another Successful API Version Response Source: https://github.com/yl-yue/yue-library/blob/master/docs/base/RESTful.md Another example of a successful API response for a different version, confirming the correct data retrieval. ```json { "code": 200, "msg": "成功", "flag": true, "data": "get4:v4" } ``` -------------------------------- ### Get White List Source: https://github.com/yl-yue/yue-library/blob/master/docs/base-crypto/密钥交换加解密.md Retrieves the list of endpoints that are whitelisted and bypass key exchange encryption/decryption. This endpoint requires configuration `yue.crypto.key-exchange.enable-controller=true` to be effective. ```APIDOC ## GET /open/v2.6/keyExchange/getWhiteList ### Description Retrieves the list of API endpoints that are excluded from the key exchange encryption and decryption process. ### Method GET ### Endpoint /open/v2.6/keyExchange/getWhiteList ### Response #### Success Response (200) - **data** (array) - A list of strings, where each string is a path pattern that bypasses key exchange. #### Response Example ```json { "code": 200, "message": "Success", "data": [ "/open/v2.6/keyExchange/**", "/actuator/**" ] } ``` ``` -------------------------------- ### 关闭日志表自动创建 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/log/快速开始.md 在 application.yml 中设置 yue.data.log.auto-create-table 为 false 以禁用自动建表功能。 ```yaml yue: data: log: auto-create-table: false ``` -------------------------------- ### Configure FastJson Response Converter Source: https://github.com/yl-yue/yue-library/blob/master/docs/web/响应消息转换器.md Enable FastJson as the response message converter. This configuration is a basic setup to activate FastJson for message conversion. ```yaml yue: web: http-message-converter: fastjson: enabled: true # 使用fastjson作为响应消息转换器 ``` -------------------------------- ### 引入 data-redis 模块 Source: https://github.com/yl-yue/yue-library/blob/master/docs/data/redis/快速开始.md 在父项目的 pom.xml 文件中添加 yue-library-data-redis 的依赖。 ```xml ai.ylyue yue-library-data-redis ```