### Get Page Initialization Data for Editor Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this GET request to fetch initial data required for opening the DIY page装修 editor. Specify the 'page_type'. ```bash curl -X GET "http://localhost:8080/adminapi/diy/init?page_type=index" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` -------------------------------- ### Android Installation Permissions Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/webroot/runtime/uni-app/src/uni_modules/rt-uni-update/readme.md If the progress bar shows but the APK does not automatically prompt for installation on Android, ensure your app includes the necessary installation permissions. These are typically required for offline builds; cloud builds may handle this automatically. ```xml ``` ```xml ``` -------------------------------- ### Preview Generated Code Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this GET request to preview the code that will be generated for a specific configuration ID. ```bash curl -X GET "http://localhost:8080/adminapi/generator/preview/5" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` -------------------------------- ### List Custom DIY Pages Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this GET request to paginate and retrieve a list of custom DIY pages. Specify 'page' and 'page_size' for pagination. ```bash curl -X GET "http://localhost:8080/adminapi/diy/diy?page=1&page_size=10" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` -------------------------------- ### Android Installation Permissions Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/uni-app/src/uni_modules/rt-uni-update/readme.md Specifies the necessary Android permissions required for installing packages. Add these to your project's `AndroidManifest.xml` if you encounter issues with automatic installation after downloading APKs, especially with offline packaging. ```xml ``` ```xml ``` -------------------------------- ### HTML Content Example Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/index.html Demonstrates how to include raw HTML content within the editor. This allows for structured content like divs and spans. ```html
这里是HTML标签
``` -------------------------------- ### Admin Environment and Build Commands (Bash) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Configuration for development environment variables and commands for installing dependencies, running the development server, and building the production package for the Admin module. Also includes commands for the Web (Nuxt3) and Uni-app modules. ```bash # admin/.env.development — 开发环境配置 VITE_APP_BASE_API=http://localhost:8080 VITE_APP_UPLOAD_URL=http://localhost:8080/adminapi/upload/image # 安装依赖并启动开发服务器 cd admin npm install npm run dev # 开发模式,访问 http://localhost:5173 # 构建生产包(输出到 webroot/public/admin/) npm run build # 启动 PC 端(Nuxt3) cd web npm install npm run dev # 访问 http://localhost:3000 npm run build # 生产构建 # 启动移动端(UNI-APP,使用 HBuilderX 或 CLI) cd uni-app npm install # 编译为 H5 npm run dev:h5 # 编译为微信小程序(需配置 appId) npm run dev:mp-weixin ``` -------------------------------- ### Plugin Management API Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt APIs for managing plugins, including local installation, cloud installation from the marketplace, and uninstallation. ```APIDOC ## GET /adminapi/addon/local ### Description Retrieves a list of locally available plugins. ### Method GET ### Endpoint `/adminapi/addon/local` ### Parameters #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ## GET /adminapi/addon/list ### Description Retrieves a paginated list of plugins, filterable by type. ### Method GET ### Endpoint `/adminapi/addon/list` ### Parameters #### Query Parameters - **page** (integer) - Required - The page number for pagination. - **page_size** (integer) - Required - The number of items per page. - **type** (string) - Optional - The type of plugins to list (e.g., 'app'). - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ## GET /adminapi/addon/list/install ### Description Retrieves a list of installed plugins. This endpoint does not require authentication. ### Method GET ### Endpoint `/adminapi/addon/list/install` ## POST /adminapi/addon/install/{addonName} ### Description Installs a local plugin. ### Method POST ### Endpoint `/adminapi/addon/install/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to install. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ## POST /adminapi/addon/cloudinstall/{addonName} ### Description Installs a plugin from the Niucloud cloud application market. ### Method POST ### Endpoint `/adminapi/addon/cloudinstall/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to install from the cloud market. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ## GET /adminapi/addon/cloudinstall/{addonName} ### Description Queries the installation progress of a cloud-installed plugin. ### Method GET ### Endpoint `/adminapi/addon/cloudinstall/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to check progress for. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ### Response #### Success Response (200) - **data** (object) - Installation progress details. - **status** (string) - Current status of the installation (e.g., 'installing'). - **progress** (integer) - Percentage of completion. - **message** (string) - Status message. #### Response Example ```json { "data": { "status": "installing", "progress": 60, "message": "正在编译..." } } ``` ## GET /adminapi/addon/install/check/{addonName} ### Description Checks the environment for plugin installation readiness. ### Method GET ### Endpoint `/adminapi/addon/install/check/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to check. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ## POST /adminapi/addon/download/{addonName} ### Description Downloads a plugin package. ### Method POST ### Endpoint `/adminapi/addon/download/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to download. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. #### Request Body - **version** (string) - Required - The version of the plugin to download. ### Request Example ```bash curl -X POST "http://localhost:8080/adminapi/addon/download/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{"version":"1.2.0"}' ``` ## POST /adminapi/addon/uninstall/{addonName} ### Description Uninstalls a plugin. ### Method POST ### Endpoint `/adminapi/addon/uninstall/{addonName}` ### Parameters #### Path Parameters - **addonName** (string) - Required - The name of the addon to uninstall. #### Query Parameters - **token** (string) - Required - The authentication token. - **site-id** (string) - Required - The ID of the site. ``` -------------------------------- ### Formula Support Example Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/webroot/public/admin/ueditor/index.html Shows how UEditorPlus renders mathematical formulas using LaTeX syntax. The image is generated from a URL with the formula as a parameter. ```html ``` -------------------------------- ### File Upload API Response Example Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt This is an example of the JSON response received after a successful file upload via the admin API, detailing the file's access URL and its storage location. ```json { "code": 1, "data": { "url": "https://your-oss.aliyuncs.com/upload/images/2024/abc.jpg", "location": "upload/images/2024/abc.jpg" } } ``` -------------------------------- ### Plugin Management API Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Manages the lifecycle of plugins, including installation (local and cloud), uninstallation, and status checks. Supports dynamic extension of system functionality. ```bash # 获取本地已有插件列表 curl -X GET "http://localhost:8080/adminapi/addon/local" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```bash # 分页查询插件列表 curl -X GET "http://localhost:8080/adminapi/addon/list?page=1&page_size=10&type=app" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```bash # 获取已安装插件列表(无需登录) curl -X GET "http://localhost:8080/adminapi/addon/list/install" ``` ```bash # 本地安装插件 curl -X POST "http://localhost:8080/adminapi/addon/install/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```bash # 云安装插件(从云市场下载并安装) curl -X POST "http://localhost:8080/adminapi/addon/cloudinstall/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```bash # 查询云安装进度 curl -X GET "http://localhost:8080/adminapi/addon/cloudinstall/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```json # 响应:{ "data": { "status": "installing", "progress": 60, "message": "正在编译..." } } ``` ```bash # 检测插件安装环境 curl -X GET "http://localhost:8080/adminapi/addon/install/check/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```bash # 下载插件包 curl -X POST "http://localhost:8080/adminapi/addon/download/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{"version":"1.2.0"}' ``` ```bash # 卸载插件 curl -X POST "http://localhost:8080/adminapi/addon/uninstall/shop" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` -------------------------------- ### HTML Content Example Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/webroot/public/admin/ueditor/index.html Displays a simple HTML structure within the editor. UEditor supports rendering standard HTML tags. ```html
这里是HTML标签
``` -------------------------------- ### Unified Payment Interface (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use the PayLoader to get payment drivers (wechat/alipay/balance) and initiate payments. Handles payment parameters and asynchronous notifications. ```java package com.niucloud.pay; import com.niucloud.pay.model.PayModelResult; import com.niucloud.pay.model.PayParam; import com.niucloud.pay.model.AsyncNotifyParam; import com.niucloud.pay.model.AsyncNotifyModelResult; import com.niucloud.pay.driver.BasePay; import com.niucloud.pay.driver.PayLoader; import org.springframework.stereotype.Service; import java.math.BigDecimal; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @Service public class OrderPayServiceImpl { public PayModelResult createPayOrder(Integer orderId, String payType, String channel) { // 获取支付驱动(wechat/alipay/balance) BasePay payDriver = PayLoader.getDriver(payType); // 构建支付参数 PayParam payParam = new PayParam(); payParam.setOrderSn("ORDER202401010001"); payParam.setAmount(new BigDecimal("99.00")); payParam.setTitle("商品订单支付"); payParam.setNotifyUrl("https://yourdomain.com/api/pay/notify/" + payType); payParam.setChannel(channel); // miniapp/h5/app/pc // 发起支付,返回前端拉起支付所需参数 PayModelResult result = payDriver.pay(payParam); // result 包含:prepayId、timeStamp、nonceStr、paySign 等微信支付参数 return result; } // 处理支付异步通知回调 public void handleAsyncNotify(String payType, HttpServletRequest request, HttpServletResponse response) { BasePay payDriver = PayLoader.getDriver(payType); AsyncNotifyParam notifyParam = new AsyncNotifyParam(); AsyncNotifyModelResult notifyResult = payDriver.asyncNotify(notifyParam, request, response); if (notifyResult.isSuccess()) { // 更新订单状态为已支付 orderService.updatePayStatus(notifyResult.getOrderSn(), "paid"); } } } ``` ```shell # === 配置支付参数(后台API) === curl -X POST "http://localhost:8080/adminapi/pay/config" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{ "pay_type": "wechat", "mch_id": "1600000000", "mch_secret_key": "your_api_v3_key", "mch_public_cert_path": "/resource/certs/apiclient_cert.pem", "mch_secret_cert": "/resource/certs/apiclient_key.pem" }' ``` -------------------------------- ### Plugin Module Entry Point Annotation (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use @SpringModuleApplication to declare a plugin's unique identifier. The framework scans and loads installed plugins dynamically, registering resources like Beans, routes, and scheduled tasks. ```java // === 定义一个商城插件的主启动类 === @SpringModuleApplication("shop") // value 为插件唯一标识符 @ComponentScan(basePackages = "com.niu.shop") public class ShopApplication { // 插件入口,框架会自动发现并加载 } ``` ```java // === 插件中的 Controller 与核心框架完全一致 === @RestController @RequestMapping("/adminapi/shop/goods") @SaCheckLogin @Description("商品管理") public class GoodsController { @Resource private IGoodsService goodsService; @GetMapping("/goods") @Description("商品列表") public Result> list(@Validated PageParam pageParam, @Validated GoodsSearchParam searchParam) { return Result.success(goodsService.list(pageParam, searchParam)); } @PostMapping("/goods") @Description("添加商品") public Result add(@Validated @RequestBody GoodsAddParam param) { goodsService.add(param); return Result.success(); } } ``` ```sql -- === 插件 SQL 初始化(在 resources/db/migrations 目录下) === -- V1__create_goods_table.sql CREATE TABLE `niu_goods` ( `id` int(11) NOT NULL AUTO_INCREMENT, `site_id` int(11) NOT NULL COMMENT '站点ID', `title` varchar(255) NOT NULL COMMENT '商品名称', `price` decimal(10,2) NOT NULL DEFAULT '0.00' COMMENT '价格', `status` tinyint(1) NOT NULL DEFAULT '1' COMMENT '状态 1上架 0下架', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (`id`), KEY `idx_site_id` (`site_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品表'; ``` -------------------------------- ### Listen to Custom Event (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Example of creating an event listener that extends 'AbstractListener' and uses '@EventCallback' to handle specific events. Supports filtering events by 'appSign'. ```java // === 监听事件(在积分插件中监听)=== @Component @EventListen(appSign = "points") // 只监听 points 应用的事件 public class OrderPayEventListener extends AbstractListener { @Override @EventCallback public void onEvent(Event event) { if (event instanceof OrderPayEvent) { OrderPayEvent payEvent = (OrderPayEvent) event; // 处理积分赠送逻辑 Integer orderId = (Integer) payEvent.getContent(); pointsService.grantPoints(payEvent.getSiteId(), orderId); } } } ``` -------------------------------- ### Admin Language Packs (JSON) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Examples of English and Chinese language packs for the Admin interface. These JSON files define translations for menu items and other UI elements. ```json // admin/src/app/lang/en/auth.menu.json — 英文语言包示例 { "menu": "Menu Management", "role": "Role Management", "user": "User Management", "permission": "Permission Settings" } ``` ```json // admin/src/app/lang/zh-cn/auth.menu.json — 中文语言包 { "menu": "菜单管理", "role": "角色管理", "user": "用户管理", "permission": "权限设置" } ``` -------------------------------- ### Basic Usage of FireworkEffect Component Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/uni-app/src/components/firework-effect/README.md Demonstrates how to integrate and configure the FireworkEffect component in a Uni-App template and script. Includes examples for showing simple fireworks and red packet rain with custom durations. ```vue ``` -------------------------------- ### Create Code Generation Configuration Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this POST request to configure settings for code generation, specifying table details and desired class/function names. ```bash curl -X POST "http://localhost:8080/adminapi/generator/generator" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{ "tableName": "niu_order", "tableComment": "订单", "addon": "shop", "className": "Order", "functionName": "订单" }' ``` -------------------------------- ### Initialize WebUploader for Image Uploads Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/dialogs/wordimage/wordimage.html Creates a WebUploader instance for handling image uploads. Configures accepted file types, SWF path, server URL, file field name, and upload limits. Compression options can be enabled based on editor settings. ```javascript var uploader = WebUploader.create({ accept: { title: 'Images', extensions: acceptExtensions, mimeTypes: 'image/*' }, swf: '../../third-party/webuploader/Uploader.swf', server: actionUrl, fileVal: editor.getOpt('imageFieldName'), duplicate: true, fileSingleSizeLimit: imageMaxSize, // 默认 2 M threads: 1, compress: editor.getOpt('imageCompressEnable') ? { width: imageCompressBorder, height: imageCompressBorder, // 图片质量,只有type为`image/jpeg`的时候才有效。 quality: 90, // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. allowMagnify: false, // 是否允许裁剪。 crop: false, // 是否保留头部meta信息。 preserveHeaders: true } : false }); ``` -------------------------------- ### Get Selected Text Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/index.html Retrieves the text currently selected by the user within the editor. Useful for context-aware operations. ```javascript function getSelectText() { var range = UE.getEditor('editor').selection.getRange(); range.select(); var txt = UE.getEditor('editor').selection.getText(); alert(txt) } ``` -------------------------------- ### Switch Theme Template Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this PUT request to switch the theme template for DIY pages. Specify the desired 'template' and 'mode' (e.g., 'light' or 'dark'). ```bash curl -X PUT "http://localhost:8080/adminapi/diy/change" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{"template":"default","mode":"light"}' ``` -------------------------------- ### Create New Custom DIY Page Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this POST request to create a new custom DIY page. Provide a title, page type, background color, and content structure. ```bash curl -X POST "http://localhost:8080/adminapi/diy/diy" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{ "title": "首页装修", "page_type": "index", "page_bg_color": "#ffffff", "content": [] }' ``` -------------------------------- ### File Upload (UploadProvider) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Abstracts file uploads through a strategy pattern, with built-in implementations for local storage, Alibaba Cloud OSS, Qiniu Cloud, and Tencent Cloud COS. Configuration via annotations automatically switches between providers. ```APIDOC ## File Upload (UploadProvider) ### Multi-Cloud Storage Upload Interface The framework abstracts file uploads through a strategy pattern, with built-in implementations for local storage, Alibaba Cloud OSS, Qiniu Cloud, and Tencent Cloud COS, automatically switching through annotation configuration. ```java // === Custom extension storage driver (implement the interface) === @UploadProvider(name = "minio") // Declare driver name with annotation @Component public class MinioUploadProvider extends AbstractUploadProvider implements IUploadProvider { @Override public UploadModelResult upload(UploadModel uploadModel) { // Upload to MinIO... String location = "images/2024/" + UUID.randomUUID() + ".jpg"; // minioClient.putObject(...) UploadModelResult result = new UploadModelResult(); result.setLocation(location); result.setUrl(getAccessUrl(location)); // Use parent class method to construct the full access URL return result; } @Override public boolean delete(String location) { // minioClient.removeObject(...) return true; } } // === Backend Management - Upload File API === // Upload image (multipart/form-data) curl -X POST "http://localhost:8080/adminapi/upload/image" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -F "file=@/path/to/image.jpg" \ -F "type=image" // Response: // { // "code": 1, // "data": { // "url": "https://your-oss.aliyuncs.com/upload/images/2024/abc.jpg", // "location": "upload/images/2024/abc.jpg" // } // } ``` ``` -------------------------------- ### Define Custom Event (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Example of defining a custom event class that extends the base 'Event' class. Include necessary fields and constructors. ```java // === 定义自定义事件 === public class OrderPayEvent extends Event { private Integer orderId; private BigDecimal amount; public OrderPayEvent(Integer orderId, BigDecimal amount) { this.orderId = orderId; this.amount = amount; } // getter/setter... } ``` -------------------------------- ### Initialize WebUploader for Image Uploads Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/webroot/runtime/admin/public/ueditor/dialogs/wordimage/wordimage.html Initializes the WebUploader instance for handling image uploads. Configures accepted file types, SWF path, server URL, file field name, duplication, size limits, threads, and compression settings. ```javascript var uploader, actionUrl = editor.getActionUrl(editor.getOpt('imageActionName')), acceptExtensions = (editor.getOpt('imageAllowFiles') || []).join('').replace(/\./g, ',').replace(/^\ podľa/, ''), imageMaxSize = editor.getOpt('imageMaxSize'), imageCompressBorder = editor.getOpt('imageCompressBorder'); uploader = WebUploader.create({ accept: { title: 'Images', extensions: acceptExtensions, mimeTypes: 'image/*' }, swf: '../../third-party/webuploader/Uploader.swf', server: actionUrl, fileVal: editor.getOpt('imageFieldName'), duplicate: true, fileSingleSizeLimit: imageMaxSize, // 默认 2 M threads: 1, compress: editor.getOpt('imageCompressEnable') ? { width: imageCompressBorder, height: imageCompressBorder, // 图片质量,只有type为`image/jpeg`的时候才有效。 quality: 90, // 是否允许放大,如果想要生成小图的时候不失真,此选项应该设置为false. allowMagnify: false, // 是否允许裁剪。 crop: false, // 是否保留头部meta信息。 preserveHeaders: true } : false }); ``` -------------------------------- ### Initialize UEditorPlus Editor Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/webroot/runtime/admin/public/ueditor/index.html Creates a UEditorPlus editor instance with specified configurations. Use this to set up the editor on a specific HTML element. ```javascript var ue = UE.getEditor('editor',{ // autoHeightEnabled: false, }); ``` -------------------------------- ### Initialize Content Import Module Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/dialogs/contentimport/contentimport.html Initializes the content import module with specified options and callbacks. Ensure the DOM is ready before calling this function. ```javascript utils.domReady(function () { var options = {}; var callbacks = {}; contentImport.init(options, callbacks); }); ``` -------------------------------- ### Generate and Download Code Package Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this POST request to generate code, either directly writing it or packaging it for download. Specify 'generateType' as '1' for direct write or '2' for package download. ```bash curl -X POST "http://localhost:8080/adminapi/generator/download" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{"ids":[5],"generateType":"2"}' ``` -------------------------------- ### Redis Cache Operations (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Demonstrates basic Redis cache operations using CacheFactory and CacheHelper. Keys are automatically prefixed with 'cache:' for isolation. ```java // 注入缓存工厂,获取 Redis 缓存实例 @Resource private CacheFactory cacheFactory; // 使用 CacheHelper 便捷操作 CacheHelper cache = cacheFactory.get(); // 存储缓存(永久) cache.put("user:info:1001", userInfoObject); // 存储缓存(带过期时间,单位:秒) cache.put("captcha:code:abc123", "4567", 300L); // 5分钟过期 // 读取缓存 Object userInfo = cache.get("user:info:1001"); // 删除单个缓存 cache.remove("user:info:1001"); // 批量删除(支持通配符模式) // 例:删除所有用户缓存 RedisCache redisCache = (RedisCache) cache; redisCache.removeBatch("user:info:*"); // 获取所有缓存 Key Collection allKeys = cache.getAllKeys(); // 获取所有缓存 Key-Value Map allData = cache.getAllKeyValues(); ``` ```java // 实际应用场景:Service 层使用缓存 @Service public class SiteServiceImpl implements ISiteService { @Resource private CacheFactory cacheFactory; public SiteInfoVo info(Integer siteId) { String cacheKey = "site:info:" + siteId; Object cached = cacheFactory.get().get(cacheKey); if (cached != null) { return (SiteInfoVo) cached; } SiteInfoVo vo = siteMapper.selectById(siteId); cacheFactory.get().put(cacheKey, vo, 3600L); // 缓存1小时 return vo; } } ``` -------------------------------- ### Manage Scheduled Jobs via Admin API Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Interact with the scheduled job management system using backend API endpoints. Use GET to query registered tasks and POST to add new scheduled jobs, specifying the task key, cron expression, and status. ```shell # 查询已注册的计划任务列表 curl -X GET "http://localhost:8080/adminapi/sys/schedule?page=1&page_size=20" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` ```shell # 新增计划任务调度(指定Cron表达式) curl -X POST "http://localhost:8080/adminapi/sys/schedule" \ -H "token: eyJhbGc..." \ -H "Content-Type: application/json" \ -d '{ "key": "order_auto_close", "cron": "0 */30 * * * ?", "status": 1 }' ``` -------------------------------- ### Copy Custom DIY Page Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this POST request to duplicate an existing custom DIY page. Provide the ID of the page to be copied. ```bash curl -X POST "http://localhost:8080/adminapi/diy/copy" \ -H "token: eyJhbGc..." \ -H "site-id: 1" \ -H "Content-Type: application/json" \ -d '{"id":1}' ``` -------------------------------- ### Core System Configuration (YAML) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Defines essential application settings including server port, database, Redis, and system parameters like token names and domain names. Production environment configurations should override development settings in `application-prod.yml`. ```yaml # webroot/jar/application.yml 核心配置示例 server: port: 8080 tomcat: max-threads: 15 max-connections: 20000 # 系统基础配置(Header 参数名称) system: admin-token-name: token # 管理员端 Token Header 名 api-token-name: token # 前端用户端 Token Header 名 admin-site-id-name: site-id # 管理员端站点ID Header 名 api-site-id-name: site-id # 前端用户端站点ID Header 名 channel-name: channel # 前端渠道 Header 名(miniapp/h5/app/pc) admin-domain: https://admin.yourdomain.com wap-domain: https://h5.yourdomain.com web-domain: https://www.yourdomain.com # application-prod.yml 生产环境专属配置 spring: datasource: url: jdbc:mysql://127.0.0.1:3306/niucloud?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai username: root password: your_db_password driver-class-name: com.mysql.cj.jdbc.Driver druid: initial-size: 10 max-active: 200 redis: host: 127.0.0.1 port: 6379 password: your_redis_password database: 0 # Sa-Token 鉴权配置 sa-token: token-name: token timeout: 2592000 # Token 有效期(秒),30天 is-concurrent: true # 允许同账号多端登录 is-share: false token-style: uuid is-log: false jwt-secret-key: niucloud-secret-key-2024 ``` -------------------------------- ### Set Custom DIY Page as Active Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Use this PUT request to designate a specific custom DIY page as the currently active one. Provide the page ID. ```bash curl -X PUT "http://localhost:8080/adminapi/diy/use/1" \ -H "token: eyJhbGc..." \ -H "site-id: 1" ``` -------------------------------- ### Extend File Upload Storage Drivers Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Implement custom file storage drivers by extending `AbstractUploadProvider` and implementing `IUploadProvider`, then annotating with `@UploadProvider(name = "your_driver_name")`. This allows integration with various storage solutions like MinIO. ```java // === 自定义扩展存储驱动(实现接口即可) === @UploadProvider(name = "minio") // 注解声明驱动名称 @Component public class MinioUploadProvider extends AbstractUploadProvider implements IUploadProvider { @Override public UploadModelResult upload(UploadModel uploadModel) { // 上传到 MinIO... String location = "images/2024/" + UUID.randomUUID() + ".jpg"; // minioClient.putObject(...) UploadModelResult result = new UploadModelResult(); result.setLocation(location); result.setUrl(getAccessUrl(location)); // 使用父类方法拼接完整访问URL return result; } @Override public boolean delete(String location) { // minioClient.removeObject(...) return true; } } ``` -------------------------------- ### Initialize Word Image Plugin Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/dialogs/wordimage/wordimage.html Initializes the word image plugin using the `wordImage.init` function after the DOM is ready. It accepts options and callbacks for customization. ```javascript utils.domReady(function () { var options = {}; var callbacks = {}; wordImage.init(options, callbacks); }); ``` -------------------------------- ### Event Publishing and Subscription (Java SDK) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Details on defining, publishing, and listening to asynchronous events for decoupled communication between plugins using the `EventPublisher`. ```APIDOC ## Event Publishing and Subscription (Java) ### Description This section describes how to implement an asynchronous event system for decoupled communication between plugins. Events automatically carry the `siteId`. ### Defining Custom Events Create a class that extends `Event` and includes relevant data. ```java public class OrderPayEvent extends Event { private Integer orderId; private BigDecimal amount; public OrderPayEvent(Integer orderId, BigDecimal amount) { this.orderId = orderId; this.amount = amount; } // getter/setter... } ``` ### Publishing Events Use `EventPublisher.publish()` to send events. ```java import org.springframework.stereotype.Service; @Service public class PayNotifyServiceImpl { public void handlePaySuccess(Integer orderId, BigDecimal amount) { // Business logic... OrderPayEvent event = new OrderPayEvent(orderId, amount); event.setName("order.pay.success"); event.setContent(orderId); // Publish event with current siteId EventPublisher.publish(event); // Or publish with a specific siteId EventPublisher.publish(event, 1); } } ``` ### Listening to Events Create a component that extends `AbstractListener` and annotates a method with `@EventCallback`. ```java import org.springframework.stereotype.Component; @Component @EventListen(appSign = "points") // Listen only to events from the 'points' app public class OrderPayEventListener extends AbstractListener { @Override @EventCallback public void onEvent(Event event) { if (event instanceof OrderPayEvent) { OrderPayEvent payEvent = (OrderPayEvent) event; // Process points granting logic Integer orderId = (Integer) payEvent.getContent(); pointsService.grantPoints(payEvent.getSiteId(), orderId); } } } ``` ``` -------------------------------- ### Initialize UEditor Editor Source: https://github.com/niuzhiyun/niucloud-admin-java/blob/master/admin/public/ueditor/index.html Initializes the UEditor editor instance with specified configurations. Use this to create a new editor on the page. ```javascript var ue = UE.getEditor('editor',{ // autoHeightEnabled: false, }); ``` -------------------------------- ### Register and Execute Scheduled Jobs Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Implement scheduled tasks by extending `AbstractJobProvider` and annotating with `@JobProvider`. These jobs can be managed dynamically (add, modify, delete, view logs) through the backend admin interface. Ensure the `key`, `name`, `describe`, and `source` attributes are correctly set for registration. ```java // === 定义计划任务(注册到指定插件模块)=== @JobProvider( key = "order_auto_close", // 任务唯一Key name = "订单自动关闭", // 任务名称 describe = "自动关闭超时未支付订单", // 任务描述 source = "shop" // 所属插件标识 ) @Component public class OrderAutoCloseJobProvider extends AbstractJobProvider { @Resource private IOrderService orderService; @Override public void exec(JobExecutionContext context) throws Exception { // 查找30分钟前未支付的订单并自动关闭 List timeoutOrderIds = orderService.findTimeoutOrders(30); for (Integer orderId : timeoutOrderIds) { orderService.closeOrder(orderId, "超时未支付自动关闭"); } log.info("自动关闭超时订单 {} 个", timeoutOrderIds.size()); } } ``` -------------------------------- ### Publish Custom Event (Java) Source: https://context7.com/niuzhiyun/niucloud-admin-java/llms.txt Demonstrates how to publish a custom event using 'EventPublisher'. Events can be published with the current site ID or a specified one. ```java // === 发布事件(在支付成功回调处)=== @Service public class PayNotifyServiceImpl { public void handlePaySuccess(Integer orderId, BigDecimal amount) { // 业务处理... // 发布订单支付成功事件,自动携带当前请求的 siteId OrderPayEvent event = new OrderPayEvent(orderId, amount); event.setName("order.pay.success"); event.setContent(orderId); EventPublisher.publish(event); // 或指定 siteId 发布 EventPublisher.publish(event, 1); } } ```