### Java Main Classes for PIG Microservice Startup Order
Source: https://wiki.pig4cloud.com/deployment/quick-start
This list outlines the recommended sequence for starting the core PIG microservices by running their respective Main methods in an IDE like IDEA. Services like "pig-register", "pig-auth", "pig-upms-biz", and "pig-gateway" are essential for initial setup. Optional services such as "pig-codegen", "pig-monitor", and "pig-quartz" can be started later based on project requirements.
```Java
1. pig-register/PigNacosApplication.java
2. pig-auth/PigAuthApplication.java
3. pig-upms-biz/PigAdminApplication
4. pig-gateway/PigGatewayApplication.java
使用代码生成、监控时再启动以下项目
5. pig-codegen/PigCodeGenApplication
6. pig-monitor/PigMonitorApplication
7. pig-quartz/PigQuartzApplication
```
--------------------------------
### Install Pig-UI Frontend Dependencies via npm
Source: https://wiki.pig4cloud.com/deployment/quick-start
Install all necessary Node.js package dependencies for the Pig-UI frontend application. The command utilizes the npmmirror registry to mitigate potential network issues during the installation process, ensuring all required modules are successfully downloaded.
```bash
npm install --registry=https://registry.npmmirror.com
```
--------------------------------
### Check and Manage Node.js Version for Pig-UI
Source: https://wiki.pig4cloud.com/deployment/quick-start
Verify the installed Node.js version, which should ideally be 18 for Pig-UI frontend compatibility. If a different version is present, use the 'n' command to switch to Node.js 18, ensuring the correct environment for dependency installation and application execution.
```bash
node -v
n 18
```
--------------------------------
### Start Pig-UI Frontend Development Server
Source: https://wiki.pig4cloud.com/deployment/quick-start
Launch the development server for the Pig-UI frontend application. This command compiles and serves the application, making it accessible locally via a web browser, typically at http://localhost:8888, for testing and development purposes.
```bash
npm run dev
```
--------------------------------
### Install Dependencies and Run PIG Monolithic Frontend
Source: https://wiki.pig4cloud.com/deployment/boot
These commands are used to check the Node.js version, install project dependencies, and start the frontend development server. Node.js version 18 is required for compatibility. The `npm install` command uses a Chinese mirror for potentially faster downloads.
```Bash
node -v
npm install --registry=https://registry.npmmirror.com
npm run dev
```
--------------------------------
### Install RocketMQ using Docker Compose
Source: https://wiki.pig4cloud.com/dev/integration/pig-rocketmq-integration
This snippet provides the necessary commands to set up RocketMQ locally using Docker Compose. It involves cloning the official `rocketmq-docker-compose` repository, modifying the broker configuration to specify the host IP, and then starting the RocketMQ services in detached mode.
```Shell
git clone https://github.com/pig-mesh/rocketmq-docker-compose
```
```Shell
vim ./broker.conf
```
```Shell
docker-compose up -d
```
--------------------------------
### Prepare KubeSphere Environment for PIG Deployment
Source: https://wiki.pig4cloud.com/deployment/k8s
This snippet provides commands to set up a KubeSphere environment. It uses the `kk` tool to install KubeSphere version 3.4.0 with Kubernetes version 1.22.12, which is a prerequisite for deploying PIG applications. Ensure you have `curl` installed and network access to KubeSphere's installation resources.
```Shell
export KKZONE=cn
curl -sfL https://get-kk.kubesphere.io | VERSION=v3.0.13 sh -
chmod +x kk
./kk create cluster --with-kubernetes v1.22.12 --with-kubesphere v3.4.0
```
--------------------------------
### Clone Pig-UI Frontend Source Code
Source: https://wiki.pig4cloud.com/deployment/quick-start
Download the Pig-UI frontend project source code from its Gitee repository. This command initiates the cloning process, creating a local copy of the repository essential for further deployment steps.
```bash
git clone https://gitee.com/log4j/pig-ui.git
```
--------------------------------
### Install and Run TongRDS MC Control Center
Source: https://wiki.pig4cloud.com/dev/integration/pig-tongrds-integration
This snippet provides the necessary shell commands to extract the TongRDS MC (Management Center) control center package, navigate into its directory, and start the server. Ensure you have obtained and placed the required 'licence' file before attempting to start the service.
```Shell
tar -zxvf TongRDS-2.2.1.6.MC.tar.gz
cd pcenter
cd bin
./StartServer.sh
```
--------------------------------
### Git Clone PIG Microservice Project
Source: https://wiki.pig4cloud.com/deployment/quick-start
This snippet provides the Git command to clone the PIG microservice project repository from Gitee. This is the first step to obtain the source code for deployment and begin setting up your development environment.
```Git
git clone https://gitee.com/log4j/pig.git
```
--------------------------------
### SQL Commands for PIG Database Initialization
Source: https://wiki.pig4cloud.com/deployment/quick-start
These SQL commands are used to initialize the core PIG database ("pig.sql") and the Nacos configuration database ("pig_config.sql"). It is mandatory to use MySQL 5.7.8+ (or 8) with utf8mb4 character set and utf8mb4_general_ci collation for proper functionality.
```SQL
-- 核心数据库
source db/pig.sql;
-- nacos 配置
source db/pig_config.sql;
```
--------------------------------
### YAML Configuration for PIG Registry Database
Source: https://wiki.pig4cloud.com/deployment/quick-start
This YAML snippet illustrates the database connection configuration for the "pig-register" module, typically found in "pig-register/application.yml". Users must modify the "user", "password", and "url" fields to match their specific MySQL setup. Remember to enclose passwords with special characters in single quotes. Additionally, Redis and other MySQL configurations (for "pig-upms-biz-dev.yml", "pig-codegen-dev.yml", "pig-quartz-dev.yml") need to be updated in their respective Nacos Data IDs.
```YAML
db:
num: 1
user: ${MYSQL-USER:root} #修改:用户名
password: ${MYSQL-PWD:root} #修改:密码,特殊字符使用 '包裹'
url:
0: jdbc:mysql://${MYSQL-HOST:pig-mysql}:${127.0.0.1:3306}/${MYSQL-DB:pig_config}?characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=false&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=GMT%2B8&nullCatalogMeansCurrent=true&allowPublicKeyRetrieval=true
```
--------------------------------
### Install and Configure MySQL 8 for PIG Data Storage
Source: https://wiki.pig4cloud.com/deployment/linux
This snippet guides through the installation and initial configuration of MySQL 8 on CentOS 7. It covers setting up the MySQL repository, installing the server, modifying the configuration to allow case-insensitive table names, restarting the service, and securely setting the root password while enabling remote access.
```bash
wget http://vip.pigx.top/mysql80-community-release-el7-11.noarch.rpm -O mysql80-community-release-el7-7.noarch.rpm
rpm -ivh mysql80-community-release-el7-7.noarch.rpm
yum install -y mysql mysql-server
# 修改配置文件
vim /etc/my.cnf
lower_case_table_names=1
# 重启 mysql
systemctl restart mysqld
# 查看默认密码
grep password /var/log/mysqld.log
# mysql client 链接 mysql
mysql -uroot -p
```
```sql
alter user 'root'@'localhost' identified by 'ZxcRoot123!@#';
set global validate_password.check_user_name=0;
set global validate_password.policy=0;
set global validate_password.length=1;
alter user 'root'@'localhost' identified by 'root';
# 修改为允许远程访问
use mysql;
update user set host = '%' where user = 'root';
FLUSH PRIVILEGES;
```
--------------------------------
### Start ELK Services Using Docker Compose
Source: https://wiki.pig4cloud.com/dev/integration/pig-elk-integration
Execute this command in the directory containing your `docker-compose.yml` file to start all defined ELK services in detached mode. Note that Elasticsearch may take several minutes to fully initialize.
```Bash
docker-compose up -d
```
--------------------------------
### Example: 'Failed to configure a DataSource' Startup Error Log
Source: https://wiki.pig4cloud.com/dev/faq/service-startup/failed-to-configure-datasource
This log snippet shows the typical error message when a Spring Boot application, like a PIG microservice, fails to start due to an unconfigured or improperly configured data source. The key indicators are 'APPLICATION FAILED TO START' and 'Failed to configure a DataSource: 'url' attribute is not specified', suggesting a missing database URL or driver.
```Log
***************************
APPLICATION FAILED TO START
***************************
Description:
Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1
```
--------------------------------
### Install Logstash JSON Lines Codec Plugin
Source: https://wiki.pig4cloud.com/dev/integration/pig-elk-integration
These commands guide you through installing the `logstash-codec-json_lines` plugin, which is necessary for Logstash to correctly parse JSON formatted logs. It involves entering the Logstash container, installing the plugin, and then restarting the Logstash service for changes to take effect.
```Bash
# 进入 logstash 容器
docker exec -it logstash /bin/bash
# 进入 bin 目录
cd /bin/
# 安装插件
logstash-plugin install logstash-codec-json_lines
# 退出容器
exit
# 重启 logstash 服务
docker restart logstash
```
--------------------------------
### Install NGINX on CentOS
Source: https://wiki.pig4cloud.com/deployment/linux
Commands to install NGINX on CentOS after configuring the repositories. It uses `yum-utils` to enable the mainline repository and then installs NGINX.
```Bash
yum install -y yum-utils
yum-config-manager --enable nginx-mainline
yum install -y nginx
```
--------------------------------
### Initialize CentOS 7 for PIG Deployment
Source: https://wiki.pig4cloud.com/deployment/linux
This snippet initializes a CentOS 7 system by downloading and executing a setup script from pigx.top. This script prepares the operating system with common configurations and dependencies required for PIG application deployment.
```bash
curl -O http://vip.pigx.top/os7init.sh
sh os7init.sh pig4cloud
```
--------------------------------
### Install Docker CE on CentOS for PIG v3
Source: https://wiki.pig4cloud.com/deployment/docker
This snippet provides commands to install Docker CE on CentOS 7, including adding the Alibaba Cloud Docker CE repository, updating yum cache, installing Docker, and starting the Docker service. It also includes a command to verify the Docker version, which must be 19.x+ to support PIG v3's layered images.
```Bash
# step 1: Install necessary system tools
sudo yum install -y yum-utils device-mapper-persistent-data lvm2
# Step 2: Add software repository information
sudo yum-config-manager --add-repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
# Step 3: Update and install Docker-CE
sudo yum makecache fast
sudo yum -y install docker-ce
# Step 4: Start Docker service
sudo service docker start
# PIG v3 uses layered images, Docker version must be 19.x+
docker --version
```
--------------------------------
### Compile Existing PIG Project with Maven
Source: https://wiki.pig4cloud.com/dev/archetype
This command compiles and installs the existing PIG microservice project into your local Maven repository. It is a crucial first step before generating new project archetypes, ensuring all necessary dependencies are available.
```Maven
mvn clean install
```
--------------------------------
### Example of Direct RedisTemplate Usage in Java
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Demonstrates how to inject and use `RedisTemplate` to perform direct Redis operations, such as retrieving a value for a given key using `opsForValue().get()`.
```Java
@Autowired
private RedisTemplate redisTemplate;
Object codeObj = redisTemplate.opsForValue().get(key);
```
--------------------------------
### Start PIG Backend Services
Source: https://wiki.pig4cloud.com/deployment/linux
Commands to start the PIG backend services in the background using `nohup`. It includes separate commands for microservice and monolithic versions, ensuring UTF-8 encoding.
```Bash
# 微服务版本启动命令
nohup java -Dfile.encoding=utf-8 -jar pig-register.jar > /dev/null 2>&1 &
nohup java -Dfile.encoding=utf-8 -jar pig-monitor.jar > /dev/null 2>&1 &
nohup java -Dfile.encoding=utf-8 -jar pig-gateway.jar > /dev/null 2>&1 &
nohup java -Dfile.encoding=utf-8 -jar pig-auth.jar > /dev/null 2>&1 &
nohup java -Dfile.encoding=utf-8 -jar pig-upms-biz.jar > /dev/null 2>&1 &
# 单体版本启动命令
nohup java -Dfile.encoding=utf-8 -jar pig-boot.jar > /dev/null 2>&1 &
```
--------------------------------
### Build and Start PIG Docker Containers
Source: https://wiki.pig4cloud.com/deployment/docker
This snippet provides Docker Compose commands to build images and start containers for the PIG application. It advises against using the '-d' (detached) flag for the first startup to easily observe any potential errors in the console.
```Docker Compose
# Build images
docker compose build
# Start containers (-d for detached mode, recommended to omit for first run to check errors)
docker compose up -d
```
--------------------------------
### PIG: Configure Menu Paths for Dynamic Routing
Source: https://wiki.pig4cloud.com/dev/frontend/route-management
This configuration example illustrates how to define multiple menu entries that point to the same underlying component but with different dynamic parameters. Each entry uses a unique parameter in its path (e.g., `:1`, `:2`) to differentiate content or behavior when the component is loaded. This allows for flexible reuse of components across various menu items.
```Configuration
AAA /admin/user/index/:1
BBB /admin/user/index/:2
CCC /admin/user/index/:3
```
--------------------------------
### Send RocketMQ Test Message in Java
Source: https://wiki.pig4cloud.com/dev/integration/pig-rocketmq-integration
This Java snippet provides an example of sending a simple test message to a RocketMQ topic. It demonstrates the use of `RocketMQTemplate` within a Spring Boot test context to publish a string message to 'test-topic-1'.
```Java
@SpringBootTest
class DemoApplicationTests {
@Autowired
private RocketMQTemplate rocketMQTemplate;
@Test
void contextLoads() {
rocketMQTemplate.convertAndSend("test-topic-1", "Hello, World!");
}
}
```
--------------------------------
### Java Example for TongRDS Redis Operations
Source: https://wiki.pig4cloud.com/dev/integration/pig-tongrds-integration
This Java code snippet presents a basic service class that illustrates how to perform common Redis operations (setting and getting key-value pairs) using Spring Data Redis's `StringRedisTemplate`. It demonstrates dependency injection and simple data manipulation with TongRDS.
```Java
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class RedisService {
private final StringRedisTemplate redisTemplate;
public RedisService(StringRedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
public void setKey(String key, String value) {
redisTemplate.opsForValue().set(key, value);
}
public String getKey(String key) {
return redisTemplate.opsForValue().get(key);
}
}
```
--------------------------------
### Install and Run TongRDS Service Node
Source: https://wiki.pig4cloud.com/dev/integration/pig-tongrds-integration
This snippet outlines the shell commands to extract the TongRDS Node service package, navigate to its executable directory, and initiate the service. This node is responsible for handling the distributed data caching operations.
```Shell
tar -zxvf TongRDS-2.2.1.6.Node.tar.gz
cd pmemdb/bin
./StartServer.sh
```
--------------------------------
### Shell: Start SkyWalking OAP Server
Source: https://wiki.pig4cloud.com/dev/integration/pig-skywalking-integration
This command initiates the SkyWalking OAP (Observability Analysis Platform) server and UI. It's a prerequisite for collecting and visualizing trace data from your applications. Ensure SkyWalking is downloaded and extracted before running this command.
```Shell
sudo bin/startup.sh
```
--------------------------------
### Run PIG Frontend Docker Container
Source: https://wiki.pig4cloud.com/deployment/docker
This snippet provides the command to start the PIG frontend application using Docker Compose. It emphasizes that the backend application must be running before starting the frontend, and Docker Compose automatically handles container host resolution.
```Docker Compose
cd pig-ui/docker
# Ensure backend application is already running before starting frontend
docker compose up -d
```
--------------------------------
### Vue Query Tree Component: Basic Usage Implementation
Source: https://wiki.pig4cloud.com/dev/frontend/left-query-tree
This section demonstrates the fundamental integration of the `query-tree` component, covering both its template usage and script setup. It illustrates how to bind the `query` prop for data fetching and handle node clicks, along with the necessary component import and reactive state management. This setup is essential for displaying hierarchical data with interactive elements.
```HTML
```
```JavaScript
const QueryTree = defineAsyncComponent(
() => import("/@/components/QueryTree/index.vue")
);
const state = reactive({
queryList: (name: String) => {
return api({
name: name,
});
},
});
const handleNodeClick = (e: any) => {};
```
--------------------------------
### API Documentation for Redis Set Operations
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Details the methods for managing Redis Set data types, including retrieving, checking existence, adding, adding with time, getting size, removing, and finding differences between sets.
```APIDOC
[{"methodName": "sGet", "description": "根据 key 获取 Set 中的所有值", "parameters": [{"name": "key", "description": "键"}]}, {"methodName": "sHasKey", "description": "根据 value 从一个 set 中查询,是否存在", "parameters": [{"name": "key", "description": "键"}, {"name": "value", "description": "值"}]}, {"methodName": "sSet", "description": "将数据放入 set 缓存", "parameters": [{"name": "key", "description": "键"}, {"name": "values", "description": "值 可以是多个"}]}, {"methodName": "sSetAndTime", "description": "将 set 数据放入缓存", "parameters": [{"name": "key", "description": "键"}, {"name": "time", "description": "时间 (秒)"}, {"name": "values", "description": "值 可以是多个"}]}, {"methodName": "sGetSetSize", "description": "获取 set 缓存的长度", "parameters": [{"name": "key", "description": "键"}]}, {"methodName": "setRemove", "description": "移除值为 value 的", "parameters": [{"name": "key", "description": "键"}, {"name": "values", "description": "值 可以是多个"}]}, {"methodName": "sDifference", "description": "获集合 key1 和集合 key2 的差集元素", "parameters": [{"name": "key", "description": "键"}, {"name": "otherKey", "description": "集合 key2 的键"}]}]
```
--------------------------------
### Install JDK 17 on CentOS for PIG Applications
Source: https://wiki.pig4cloud.com/deployment/linux
This snippet installs JDK 17 on CentOS 7 using an RPM package from Azul Zulu. It also includes commands to install font configuration utilities, which are often necessary for Java applications with graphical components or specific text rendering requirements.
```bash
wget https://cdn.azul.com/zulu/bin/zulu17.44.15-ca-jdk17.0.8-linux.x86_64.rpm
rpm -ivh zulu17.44.15-ca-jdk17.0.8-linux.x86_64.rpm
java -version
yum install -y fontconfig mkfontscale
```
--------------------------------
### Install Redis on CentOS for PIG Caching
Source: https://wiki.pig4cloud.com/deployment/linux
This snippet provides the commands to install Redis on a CentOS system. It includes installing the Redis package via yum and then restarting the Redis service to ensure it is running and available for use by PIG applications for caching or session management.
```bash
yum install redis
systemctl restart redis
```
--------------------------------
### Build PIG Frontend for Docker Deployment
Source: https://wiki.pig4cloud.com/deployment/docker
This snippet outlines the steps to build the PIG frontend application for Docker deployment. It includes commands to install dependencies and execute the build process, which generates minified and obfuscated code in the 'pig-ui/docker/dist' directory.
```npm
# Install dependencies
npm install
# Execute build command
npm run build:docker
```
--------------------------------
### Add RocketMQ Dependency to PIG Project POM
Source: https://wiki.pig4cloud.com/dev/integration/pig-rocketmq-integration
This snippet shows how to include the `rocketmq-spring-boot3-starter` dependency in your PIG project's `pom.xml`. This Maven dependency is crucial for enabling RocketMQ integration features within your Spring Boot 3 application.
```XML
com.pig4cloud.plugin
rocketmq-spring-boot3-starter
2.2.3
```
--------------------------------
### Configure NGINX Repository for CentOS
Source: https://wiki.pig4cloud.com/deployment/linux
This snippet shows how to add the NGINX stable and mainline repositories to your CentOS system's yum configuration. This is a prerequisite for installing NGINX using yum.
```INI
vim /etc/yum.repos.d/nginx.repo
[nginx-stable]
name=nginx stable repo
baseurl=http://nginx.org/packages/centos/$releasever/$basearch/
gpgcheck=1
enabled=1
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
[nginx-mainline]
name=nginx mainline repo
baseurl=http://nginx.org/packages/mainline/centos/$releasever/$basearch/
gpgcheck=1
enabled=0
gpgkey=https://nginx.org/keys/nginx_signing.key
module_hotfixes=true
```
--------------------------------
### Install RabbitMQ with Docker
Source: https://wiki.pig4cloud.com/dev/integration/pig-rabbitmq-integration
This snippet provides the Docker command to quickly deploy a RabbitMQ instance. It maps ports 5672 for AMQP and 15672 for the management UI, and names the container 'rabbitmq'.
```Shell
docker run -d -p 5672:5672 -p 15672:15672 --name rabbitmq rabbitmq:management
```
--------------------------------
### Configure Maven Dependency for Pig4cloud Common Core
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
To enable Redis caching capabilities, include the `pig-common-core` artifact from `com.pig4cloud` group in your project's Maven dependencies.
```XML
com.pig4cloud
pig-common-core
```
--------------------------------
### Spring Cache Annotation Property Descriptions
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Describes common properties used with Spring Cache annotations like `value`, `key`, `condition`, and `unless`, explaining their purpose and usage with SpEL expressions.
```APIDOC
[{"property": "value", "description": "缓存的名称,在 spring 配置文件中定义,必须指定至少一个"}, {"property": "key", "description": "缓存的 key,可以为空,如果指定要按照 SpEL 表达式编写"}, {"property": "condition", "description": "缓存的条件,可以为空,使用 SpEL 编写,返回 true 或者 false"}, {"property": "unless", "description": "否定缓存,当条件结果为 true 时,就不会缓存"}]
```
--------------------------------
### Spring Cache @CacheEvict Annotation Example
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Illustrates the use of `@CacheEvict` annotation to clear cache entries. The example shows clearing the 'user' cache for a specific `id` after a deletion operation.
```Java
@CacheEvict(value = "user", key = "#id")
public void deleteById(Long id) {
userRepository.deleteById(id);
}
```
--------------------------------
### Spring Cache @Cacheable Annotation Example
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Illustrates the use of `@Cacheable` annotation to cache method results based on input parameters. The example shows caching a `User` object by its `id`.
```Java
@Cacheable(value = "user", key = "#id")
public User findById(Long id) {
return userRepository.findById(id).orElse(null);
}
```
--------------------------------
### Git: Clone PIG Project Repository
Source: https://wiki.pig4cloud.com/dev/integration/sql/nacos
This snippet provides the Git command to clone the forked PIG project repository from Gitee to your local development environment. This is the essential second step after forking, enabling local modifications and development.
```Git
git clone https://gitee.com/{您的用户名}/pig.git
```
--------------------------------
### Vue.js: Initializing `useTable` State with `reactive`
Source: https://wiki.pig4cloud.com/dev/frontend/table-component
Illustrates how to define the initial state object (`BasicTableProps`) using Vue's `reactive` function, which is then passed to the `useTable` composable for table configuration. This setup provides the necessary parameters for table operations.
```TypeScript
const state: BasicTableProps = reactive({
queryForm: {},
pageList: pageList,
});
```
--------------------------------
### Add Pig Dynamic Data Source Maven Dependency
Source: https://wiki.pig4cloud.com/dev/function/pig-dynamic-datasource
This snippet demonstrates how to include the `pig-common-datasource` Maven dependency in your business service's `pom.xml`. This dependency provides the necessary components for integrating dynamic data source functionality into your Pig project.
```XML
com.pig4cloud
pig-common-datasource
```
--------------------------------
### Download PIG Monolithic Server Code with Git
Source: https://wiki.pig4cloud.com/deployment/boot
This command clones the PIG server-side source code repository from Gitee. Ensure you select the correct branch for the monolithic architecture. This is the first step to set up the backend service for the PIG monolithic application.
```Bash
git clone https://gitee.com/log4j/pig.git
```
--------------------------------
### Test GET Parameter XSS Filtering in Spring Boot
Source: https://wiki.pig4cloud.com/dev/function/pig-xss-filter
This snippet demonstrates how a Spring Boot application handles GET requests with potentially malicious parameters. It shows a simple GET endpoint that returns the input parameter, followed by a curl command to test if XSS content in the URL parameter is filtered. The expected behavior is that the XSS content is filtered or sanitized.
```Java
@GetMapping("/xss")
public String xss(String params){
return params;
}
```
```Curl
curl --location --request GET 'http://localhost:8080/xss?params=%3Cscript%3Ealert(%27xxx%27)%3C/script%3E'
```
--------------------------------
### Prepare Frontend Deployment Directory
Source: https://wiki.pig4cloud.com/deployment/linux
Commands to prepare the deployment directory for the PIG frontend (pig-ui). This involves creating the directory, copying compiled assets, and removing default NGINX configuration.
```Bash
mkdir -p /data/pig-ui && cp -r dist/* /data/pig-ui
cd /etc/nginx/conf.d && rm -f default.conf
vim pig.conf
```
--------------------------------
### Download and Extract Nacos Server Release Package
Source: https://wiki.pig4cloud.com/dev/basics/nacos-server-implementation
This snippet demonstrates how to download a specific version of Nacos Server, extract it, and navigate to its binary directory using curl and tar commands. This is the standard way to prepare Nacos for execution from a pre-built package.
```Shell
curl -O https://github.com/alibaba/nacos/releases/download/1.3.2/nacos-server-1.3.2.tar.gz
tar -zxvf nacos-server-1.3.2.tar.gz
cd nacos/bin
```
--------------------------------
### Download PIG Monolithic Frontend Code with Git
Source: https://wiki.pig4cloud.com/deployment/boot
This command clones the PIG frontend source code repository from Gitee. The `-b master` flag specifies the master branch for the frontend application. This is the initial step to prepare the frontend for deployment and interaction with the monolithic backend.
```Bash
git clone https://gitee.com/log4j/pig-ui.git -b master
```
--------------------------------
### SQL: Create PIG Demo Database and Table
Source: https://wiki.pig4cloud.com/dev/crud
This SQL script initializes the `pig_demo` database and creates a `demo` table within it. The `demo` table is designed with a `bigint` primary key and includes fields for user information and audit timestamps, serving as the foundational data structure for the microservice's CRUD operations.
```SQL
-- 创建测试库
create database `pig_demo` default character set utf8mb4 collate utf8mb4_general_ci;
USE pig_demo;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- 创建测试表
DROP TABLE IF EXISTS `demo`;
-- 数据表要求,主键设置为 bigint, 字段下划线命名
CREATE TABLE `demo` (
`id` bigint NOT NULL COMMENT '主键',
`username` varchar(255) DEFAULT NULL COMMENT '用户名',
`nicename` varchar(255) DEFAULT NULL COMMENT '昵称',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人',
`update_time` datetime DEFAULT NULL COMMENT '修改时间',
`update_by` varchar(64) DEFAULT NULL COMMENT '更新人',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 ROW_FORMAT=DYNAMIC COMMENT='demo 表';
```
--------------------------------
### API Documentation for Redis Hash Operations
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Details the methods available for interacting with Redis Hash data types, including getting, setting, deleting, checking existence, and incrementing/decrementing values within a hash.
```APIDOC
[{"methodName": "hget", "description": "HashGet", "parameters": [{"name": "key", "description": "键,不能为 null"}, {"name": "hashKey", "description": "项,不能为 null"}]}, {"methodName": "hmget", "description": "获取 hashKey 对应的所有键值", "parameters": [{"name": "key", "description": "键"}]}, {"methodName": "hmset", "description": "HashSet", "parameters": [{"name": "key", "description": "键"}, {"name": "map", "description": "对应多个键值"}]}, {"methodName": "hset", "description": "向一张 hash 表中放入数据,如果不存在将创建", "parameters": [{"name": "key", "description": "键"}, {"name": "item", "description": "项"}, {"name": "value", "description": "值"}]}, {"methodName": "hdel", "description": "删除 hash 表中的值", "parameters": [{"name": "key", "description": "键,不能为 null"}, {"name": "item", "description": "项,可以使多个,不能为 null"}]}, {"methodName": "hHasKey", "description": "判断 hash 表中是否有该项的值", "parameters": [{"name": "key", "description": "键,不能为 null"}, {"name": "item", "description": "项,不能为 null"}]}, {"methodName": "hincr", "description": "hash 递增", "parameters": [{"name": "key", "description": "键"}, {"name": "item", "description": "项"}, {"name": "by", "description": "要增加几 (大于 0)"}]}, {"methodName": "hdecr", "description": "hash 递减", "parameters": [{"name": "key", "description": "键"}, {"name": "item", "description": "项"}, {"name": "by", "description": "要减少记 (小于 0)"}]}]
```
--------------------------------
### Build Nacos Server from Source Code with Maven
Source: https://wiki.pig4cloud.com/dev/basics/nacos-server-implementation
This snippet outlines the steps to clone the Nacos GitHub repository, navigate into it, and build the project using Maven. The command uses the -Prelease-nacos profile, skips tests, and performs a clean install, resulting in a runnable server package in the distribution/target directory. This method is useful for UI customization and ensuring version consistency.
```Shell
git clone https://github.com/alibaba/nacos.git
cd nacos/
mvn -Prelease-nacos -Dmaven.test.skip=true clean install -U
ls -al distribution/target/
cd distribution/target/nacos-server-$version/nacos/bin
```
--------------------------------
### API Documentation for Redis Sorted Set Operations
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Details the methods for managing Redis Sorted Set data types, including adding with time, retrieving by score or range (ascending/descending), and getting set size.
```APIDOC
[{"methodName": "zSetAndTime", "description": "将 zSet 数据放入缓存", "parameters": [{"name": "key", "description": "键"}, {"name": "time", "description": "时间"}, {"name": "tuples", "description": "值"}]}, {"methodName": "zRangeByScore", "description": "Sorted set:有序集合获取", "parameters": [{"name": "key", "description": "键"}, {"name": "min", "description": "最小分数"}, {"name": "max", "description": "最大分数"}]}, {"methodName": "zRange", "description": "Sorted set:有序集合获取 正序", "parameters": [{"name": "key", "description": "键"}, {"name": "start", "description": "开始位置"}, {"name": "end", "description": "结束位置"}]}, {"methodName": "zReverseRange", "description": "Sorted set:有序集合获取 倒叙", "parameters": [{"name": "key", "description": "键"}, {"name": "start", "description": "开始位置"}, {"name": "end", "description": "结束位置"}]}, {"methodName": "zGetSetSize", "description": "获取 zSet 缓存的长度", "parameters": [{"name": "key", "description": "键"}]}]
```
--------------------------------
### Initialize PIG Application Database
Source: https://wiki.pig4cloud.com/deployment/linux
Commands to initialize the MySQL database for the PIG application. This involves connecting to MySQL and sourcing the core database and Nacos configuration SQL files.
```SQL
mysql -uroot -proot
-- 核心数据库
source db/pig.sql;
-- nacos配置
source db/pig_config.sql;
```
--------------------------------
### API Documentation for Redis List Operations
Source: https://wiki.pig4cloud.com/dev/function/redis-cache-usage
Details the methods for managing Redis List data types, including retrieving content by range or index, getting list size, adding, updating by index, and removing elements.
```APIDOC
[{"methodName": "lGet", "description": "获取 list 缓存的内容", "parameters": [{"name": "key", "description": "键"}, {"name": "start", "description": "开始索引"}, {"name": "end", "description": "结束索引 (0 到 -1 代表所有值)"}]}, {"methodName": "lGetListSize", "description": "获取 list 缓存的长度", "parameters": [{"name": "key", "description": "键"}]}, {"methodName": "lGetIndex", "description": "通过索引获取 list 中的值", "parameters": [{"name": "key", "description": "键"}, {"name": "index", "description": "索引"}]}, {"methodName": "lSet", "description": "将 list 放入缓存", "parameters": [{"name": "key", "description": "键"}, {"name": "value", "description": "值"}]}, {"methodName": "lUpdateIndex", "description": "根据索引修改 list 中的某条数据", "parameters": [{"name": "key", "description": "键"}, {"name": "index", "description": "索引"}, {"name": "value", "description": "值"}]}, {"methodName": "lRemove", "description": "移除 N 个值为 value", "parameters": [{"name": "key", "description": "键"}, {"name": "count", "description": "移除多少个"}, {"name": "value", "description": "值"}]}]
```
--------------------------------
### Java: Configure SkyWalking Agent for JAR Startup
Source: https://wiki.pig4cloud.com/dev/integration/pig-skywalking-integration
This command demonstrates how to attach the SkyWalking Java Agent to a PIG microservice (e.g., pig-upms) when starting it as a JAR file. It enables distributed tracing by specifying the agent path, service name, and SkyWalking collector address. Ensure the skywalking-agent.jar is accessible from the application's directory.
```Java
nohup java -Xms512m -Xmx3500m -javaagent:skywalking-agent.jar \
-Dskywalking.agent.service_name=pig-upms \
-Dskywalking.collector.backend_service=ip:11800 \
-jar pig-upms-biz.jar \
-Djava.security.egd=file:/dev/./urandom 2>&1 &
```
--------------------------------
### Manage State in TypeScript with Pinia
Source: https://wiki.pig4cloud.com/dev/frontend/data-state-management
This snippet demonstrates how to interact with the Pinia store directly within a TypeScript file. It shows examples of both dispatching an action and committing a mutation to update the application's state, specifically for managing `keepAliveNames` cache.
```TypeScript
import { store } from "/@/store/index.ts";
// dispatch
store.dispatch("keepAliveNames/setCacheKeepAlive", cacheList);
// 或者 commit
// store.commit("keepAliveNames/getCacheKeepAlive", cacheList);
```
--------------------------------
### Deploy MinIO Docker Container for PIG OSS
Source: https://wiki.pig4cloud.com/dev/function/pig-oss-upload
This snippet provides a Docker command to run a MinIO server instance. It sets up port mapping, container name, and initial root user credentials (lengleng/lengleng) for accessing the MinIO console. This specific version is Apache 2.0 licensed for commercial use.
```Shell
# 注意版本号,此版本为 Apache 2.0 协议可以商用
docker run -p 9000:9000 --name minio1 \\
-e "MINIO_ROOT_USER=lengleng" \\
-e "MINIO_ROOT_PASSWORD=lengleng" \\
minio/minio:RELEASE.2021-04-22T15-44-28Z server /data
```
--------------------------------
### Access Pinia State in Vue Components
Source: https://wiki.pig4cloud.com/dev/frontend/data-state-management
This example illustrates how to access and react to Pinia store state within a Vue 3 component using the `useStore` hook and `computed` properties. It specifically retrieves theme configuration to conditionally render content.
```Vue
在 .vue 中使用
```
--------------------------------
### Create PIG V3 Monolithic Demo Database Table
Source: https://wiki.pig4cloud.com/dev/boot
This SQL script creates a 'demo' table within the 'pig' database, designed for testing and secondary development. It ensures a clean slate by dropping the table if it exists and defines essential fields like ID, username, password, and a soft delete flag.
```SQL
-- 创建测试库
USE pig;
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- 创建测试表
DROP TABLE IF EXISTS `demo`;
CREATE TABLE `demo` (
`id` bigint NOT NULL COMMENT '编号',
`username` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '用户名',
`password` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT NULL COMMENT '密码',
`del_flag` char(1) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin DEFAULT '0' COMMENT '删除标记',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin ROW_FORMAT=DYNAMIC COMMENT='demo 表';
```
--------------------------------
### Logout from PIG Unified Authentication
Source: https://wiki.pig4cloud.com/dev/auth/pig-authorization-code
This HTTP GET request URL allows a user to log out from the unified identity authentication system provided by PIG. Accessing this endpoint will terminate the user's session within the authentication server.
```HTTP
http://localhost:3000/oauth2/logout
```
--------------------------------
### Deploy Sentinel Dashboard using Docker
Source: https://wiki.pig4cloud.com/dev/function/sentinel-console
This Docker command deploys the Sentinel dashboard, mapping port 5020 on the host to port 8858 within the container. The dashboard can then be accessed at http://localhost:5020 using the default credentials sentinel/sentinel. Ensure Docker is installed and running before executing this command.
```Shell
docker run --name sentinel -d -p 5020:8858 -d royalwang/sentinel-dashboard:1.8.4
```
--------------------------------
### Overview of Common Frontend/Backend Authentication Methods
Source: https://wiki.pig4cloud.com/dev/auth/token-jwt-oauth2-session
Lists the prevalent authentication strategies used in modern web development for securing client-server communication. This provides a quick reference to common approaches like session-cookie, various token-based methods, and OAuth2.0.
```Conceptual
Common Frontend/Backend Authentication Methods:
- Session-Cookie
- Token authentication (including JWT, SSO)
- OAuth2.0 (Open Authorization)
```
--------------------------------
### Test POST Form Parameter XSS Filtering in Spring Boot
Source: https://wiki.pig4cloud.com/dev/function/pig-xss-filter
This example illustrates XSS filtering for POST requests with application/x-www-form-urlencoded content. It provides a Spring Boot POST endpoint that echoes the input parameter and a curl command to send a form-encoded XSS payload. The system should filter or sanitize the XSS content before returning it.
```Java
@PostMapping("/xss")
public String xss(String params){
return params;
}
```
```Curl
curl --location --request POST 'http://localhost:8080/xss' \
--header 'Content-Type: application/x-www-form-urlencoded' \
--data-urlencode 'params='
```
--------------------------------
### Build PIG Application Source Code
Source: https://wiki.pig4cloud.com/deployment/linux
This section provides commands to build the PIG application source code. It includes separate Maven commands for microservice and monolithic versions, and an npm command for frontend compilation.
```Maven
# 微服务版本打包
mvn clean install -Pcloud
# 单体版本打包
mvn clean install -Pboot
```
```Node.js
npm run build
```
--------------------------------
### Globally Import Vuex Modules in PIG Frontend
Source: https://wiki.pig4cloud.com/dev/frontend/data-state-management
This TypeScript snippet illustrates the automatic global import mechanism for Vuex modules in the PIG framework. It uses Vite's `import.meta.globEager` to dynamically load and consolidate all modules from the `./modules` directory into a single object for the Vuex store, simplifying state management setup.
```TypeScript
const modulesFiles = import.meta.globEager("./modules/*.ts");
const pathList: string[] = [];
for (const path in modulesFiles) {
pathList.push(path);
}
const modules = pathList.reduce(
(modules: { [x: string]: any }, modulePath: string) => {
const moduleName = modulePath.replace(/^\.\/modules\/(.*)\.\w+$/, "$1");
const value = modulesFiles[modulePath];
modules[moduleName] = value.default;
return modules;
},
{}
);
```
--------------------------------
### Add Spring Boot Starter Security Maven Dependency
Source: https://wiki.pig4cloud.com/dev/function/monitor-security
This XML snippet demonstrates how to include the `spring-boot-starter-security` dependency in your Maven `pom.xml` file. This dependency provides core Spring Security functionalities, enabling authentication and authorization features in your Spring Boot application.
```XML
org.springframework.boot
spring-boot-starter-security
```
--------------------------------
### Initiate OAuth2 Authorization Code Flow Request
Source: https://wiki.pig4cloud.com/dev/auth/pig-authorization-code
This HTTP GET request URL is used to initiate the OAuth2 authorization code flow. It directs the user to the authentication server, requesting an authorization code for the specified client ('test') with the given scope and redirect URI. Ensure the redirect URI is not 'localhost' for this mode.
```HTTP
http://localhost:3000/oauth2/authorize?scope=server&client_id=test&response_type=code&redirect_uri=https://pig4cloud.com
```
--------------------------------
### Implement Access Token Authentication Flow
Source: https://wiki.pig4cloud.com/dev/auth/token-jwt-oauth2-session
Describes the standard process for token-based authentication, from client login request to server-issued token and subsequent resource access using the token in HTTP headers. This method promotes a stateless server architecture.
```Conceptual
Access Token:
- An access token is a credential required to access resource interfaces (APIs).
- Simple token composition: uid (unique user identifier), time (current timestamp), sign (signature, a fixed-length hexadecimal string compressed from the token's first few bits using a hash algorithm).
- Characteristics:
+ Server-side statelessness, good scalability.
+ Supports mobile devices.
+ Secure.
+ Supports cross-application calls.
Token authentication flow:
1. The client requests login with a username and password.
2. The server receives the request and verifies the username and password.
3. Upon successful verification, the server issues a token and sends it to the client.
4. The client receives the token and stores it (e.g., in a cookie or localStorage).
5. The client must include the server-issued token with every subsequent request for resources.
6. The server receives the request, verifies the token carried by the client. If verification is successful, it returns the requested data to the client.
Key points:
- Every request must carry the token, typically placed in the HTTP Header.
- Token-based user authentication is a server-side stateless authentication method; the server does not store token data. It trades token parsing computation time for session storage space, thereby reducing server pressure and frequent database queries.
- Tokens are entirely managed by the application, allowing them to bypass the same-origin policy.
```
--------------------------------
### Implement Caching with Spring's @Cacheable Annotation
Source: https://wiki.pig4cloud.com/dev/integration/pig-multi-level-cache
Use the @Cacheable annotation on methods whose results you want to cache. This example demonstrates caching the get method's return value based on the key parameter. The value attribute specifies the cache name, and key defines the cache key, ensuring efficient data retrieval from the multi-level cache.
```Java
@Cacheable(value = "get", key = "#key")
@GetMapping("/get")
public String get(String key) {
return "success";
}
```
--------------------------------
### Create LiteFlow Rule XML File
Source: https://wiki.pig4cloud.com/dev/integration/pig-liteflow-integration
This snippet provides an example of a LiteFlow rule XML file, `demo-rule.xml`, defining a simple conditional chain. This file specifies the flow of execution for different nodes based on conditions, enabling declarative business process orchestration within the LiteFlow engine.
```XML
THEN(
IF(x, a),
b
);
```