### Prometheus and Grafana Setup (Shell)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Instructions for running Prometheus and Grafana Docker containers and configuring Prometheus to scrape metrics from the application. Access the exposed metrics endpoint for visualization.
```shell
# Start Prometheus
docker run -d -p 9090:9090 --name prometheus prom/prometheus
# Add scrape job to prometheus.yml
# scrape_configs:
# - job_name: 'dynamic-thread-pool-job'
# scrape_interval: 5s
# metrics_path: '/actuator/prometheus'
# static_configs:
# - targets: ['host.docker.internal:29999']
# Start Grafana
docker run -d -p 3000:3000 --name=grafana grafana/grafana
# Access metrics at http://localhost:29999/actuator/prometheus
# Metrics prefix: dynamic_thread_pool_*
```
--------------------------------
### Run Hippo4j Server with Docker
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/ops/server-docker.md
Starts the Hippo4j Server container using the default H2 database.
```shell
docker run -d -p 6691:6691 --name hippo4j-server hippo4j/hippo4j-server
```
--------------------------------
### Run Hippo4j Server with MySQL
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/ops/server-docker.md
Starts the Hippo4j Server container configured to use a MySQL database. Ensure DATASOURCE_HOST is set to a reachable IP address.
```shell
docker run -d -p 6691:6691 --name hippo4j-server \
-e DATASOURCE_MODE=mysql \
-e DATASOURCE_HOST=xxx.xxx.xxx.xxx \
-e DATASOURCE_PORT=3306 \
-e DATASOURCE_DB=hippo4j_manager \
-e DATASOURCE_USERNAME=root \
-e DATASOURCE_PASSWORD=root \
hippo4j/hippo4j-server
```
--------------------------------
### Full Configuration Example for Config Center Mode
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Comprehensive application.yml configuration for Hippo4j in Config Center Mode, covering notification platforms, configuration center specifics, web container thread pools, global alarms, and dynamic thread pool definitions.
```yaml
# application.yml - Full configuration example
spring:
profiles:
active: dev
dynamic:
thread-pool:
enable: true
banner: true
collect: true
check-state-interval: 3000
# Notification platforms
notify-platforms:
- platform: 'WECHAT'
token: your-wechat-token
- platform: 'DING'
token: your-dingtalk-token
secret: your-dingtalk-secret
- platform: 'LARK'
token: your-lark-token
# Configuration center (choose one)
nacos:
data-id: hippo4j-config
group: DEFAULT_GROUP
config-file-type: yml
# Web container thread pool
web:
core-pool-size: 100
maximum-pool-size: 200
keep-alive-time: 1000
# Global alarm settings
alarm: true
active-alarm: 80
capacity-alarm: 80
alarm-interval: 8
receives: user-id-or-phone
# Dynamic thread pool definitions
executors:
- thread-pool-id: 'message-consume'
core-pool-size: 4
maximum-pool-size: 16
blocking-queue: 'LinkedBlockingQueue'
queue-capacity: 1024
execute-time-out: 1000
rejected-handler: 'AbortPolicy'
keep-alive-time: 60
allow-core-thread-time-out: true
thread-name-prefix: 'message-consume'
alarm: true
active-alarm: 80
capacity-alarm: 80
notify:
interval: 8
receives: specific-receiver
```
--------------------------------
### Configure Monitoring with Prometheus (YAML)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Enable Prometheus metrics export and configure the management server port. This setup allows Prometheus to scrape thread pool metrics exposed by the application.
```yaml
# application.yml - Monitoring configuration
management:
metrics:
export:
prometheus:
enabled: true
server:
port: 29999
endpoints:
web:
exposure:
include: '*'
spring:
dynamic:
thread-pool:
monitor:
enable: true
collect-interval: 5000
collect-types: micrometer
initial-delay: 10000
thread-pool-types: dynamic,web,adapter
```
--------------------------------
### Example of Rejected Execution Handler Log Output
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/dev_manual/rejected-policy-custom.md
When the rejected execution handler is triggered, it will produce log output similar to this example, indicating that the thread pool has rejected a task.
```text
2022-08-01 21:27:49.515 ERROR 48928 --- [ateHandler.test] r$CustomErrorLogRejectedExecutionHandler : 线程池抛出拒绝策略
```
--------------------------------
### Implement Custom Rejected Execution Handler in Java
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/dev_manual/rejected-policy-custom.md
Implement the CustomRejectedExecutionHandler interface to define custom rejected execution logic. This example shows how to log an error when a task is rejected. Ensure the class is public and implements the required methods.
```java
public class ErrorLogRejectedExecutionHandler implements CustomRejectedExecutionHandler {
@Override
public Integer getType() {
return 12;
}
@Override
public RejectedExecutionHandler generateRejected() {
return new CustomErrorLogRejectedExecutionHandler();
}
public static class CustomErrorLogRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
Logger logger = LoggerFactory.getLogger(this.getClass());
logger.error("线程池抛出拒绝策略");
}
}
}
```
--------------------------------
### Build Hippo4j Docker Image
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/ops/server-docker.md
Commands to package the application and build the Docker image, including multi-platform support.
```shell
# 进入到 threadpool/server/bootstrap 工程路径下
mvn clean package -Dskip.spotless.apply=true
# 进入到 docker 工程路径下
# 默认打包是打包的 tag 是 latest
docker build -t hippo4j/hippo4j-server ../docker
# 构建多平台版本
docker buildx build --platform linux/arm64 -t hippo4j/hippo4j-server ../docker
docker buildx build --platform linux/amd64 -t hippo4j/hippo4j-server ../docker
```
--------------------------------
### Configure TTL Wrapped Executor in Spring
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Configure a dynamic thread pool wrapped with TTL for TransmittableThreadLocal support. This setup is suitable for Spring Boot applications needing advanced context propagation.
```java
package cn.hippo4j.example.config;
import cn.hippo4j.core.executor.DynamicThreadPool;
import cn.hippo4j.core.executor.support.ThreadPoolBuilder;
import com.alibaba.ttl.threadpool.TtlExecutors;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class TtlConfig {
@Bean
@DynamicThreadPool
public Executor ttlWrappedExecutor() {
String threadPoolId = "ttl-executor";
ThreadPoolExecutor executor = ThreadPoolBuilder.builder()
.threadPoolId(threadPoolId)
.threadFactory(threadPoolId)
.dynamicPool()
.corePoolSize(4)
.maximumPoolSize(16)
.capacity(1024)
.executeTimeOut(800)
.waitForTasksToCompleteOnShutdown(true)
.awaitTerminationMillis(5000)
.build();
// Wrap with TTL for TransmittableThreadLocal support
return TtlExecutors.getTtlExecutor(executor);
}
}
```
--------------------------------
### Build Custom Hippo4j Server Docker Image (Maven)
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/version-1.5.0/user_docs/ops/server-docker.md
Builds a custom Docker image for the Hippo4j server using Maven. This command should be run from the hippo4j-server/hippo4j-bootstrap directory.
```shell
# 进入到 hippo4j-server/hippo4j-bootstrap 工程路径下
mvn clean package -Dskip.spotless.apply=true
# 默认打包是打包的 tag 是 latest
docker build -t hippo4j/hippo4j-server ../hippo4j-bootstrap
```
--------------------------------
### 配置动态线程池监控
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
在 application.yml 中配置 Actuator 端点暴露及 Hippo4j 监控采集参数。
```yaml
management:
metrics:
export:
prometheus:
enabled: true
server:
port: 29999 # 可选配置,如果不配置该 port,直接使用 ${server.port}
endpoints:
web:
exposure:
include: '*' # 测试使用,开启了所有端点,生产环境不建议 *
spring:
dynamic:
thread-pool:
monitor:
enable: true # 是否开启采集线程池运行时数据
collect-interval: 5000 # 采集线程池运行数据频率
collect-types: micrometer # 采集线程池运行数据的类型。eg:log、micrometer。多个可以同时使用,默认 micrometer
initial-delay: 10000 # 项目启动后延迟多久进行采集
thread-pool-types: dynamic # 采集线程池的类型。eg:dynamic、web、adapter。可任意配置,默认 dynamic
```
--------------------------------
### Include All-in-One Adapter JAR for Hippo4j
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/blog/2022-06-06-hippo4j/index.md
If you prefer to avoid managing multiple JARs, you can include the 'hippo4j-spring-boot-starter-adapter-all' artifact. Hippo4j will automatically load the correct adapter based on available middleware.
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-all
1.3.0
```
--------------------------------
### Add Hippo4j Starter Dependency
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/server/hippo4j-server-start.md
Include the Hippo4j Spring Boot Starter JAR in your project's pom.xml to enable dynamic thread pool management.
```xml
cn.hippo4j
hippo4j-spring-boot-starter
1.5.0
```
--------------------------------
### Build Custom Hippo4j Server Docker Image (Maven Docker Plugin)
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/version-1.5.0/user_docs/ops/server-docker.md
Builds a custom Docker image for the Hippo4j server using the Maven Docker plugin. This command should be run from the hippo4j-server directory.
```shell
# 进入到 hippo4j-server 工程路径下
mvn clean package -DskipTests -Dskip.spotless.apply=true docker:build
```
--------------------------------
### Deploy Hippo4j Server with Docker
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Use Docker to quickly deploy the Hippo4j Server. Supports both default H2 database and MySQL configuration.
```shell
# Start Hippo4j Server with default H2 database
docker run -d -p 6691:6691 --name hippo4j-server hippo4j/hippo4j-server
# Or start with MySQL database
docker run -d -p 6691:6691 --name hippo4j-server \
-e DATASOURCE_MODE=mysql \
-e DATASOURCE_HOST=192.168.1.100 \
-e DATASOURCE_PORT=3306 \
-e DATASOURCE_DB=hippo4j_manager \
-e DATASOURCE_USERNAME=root \
-e DATASOURCE_PASSWORD=root \
hippo4j/hippo4j-server
# Access Server console at http://localhost:6691/index.html
# Default credentials: admin / 123456
```
--------------------------------
### 添加监控依赖
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
在 Maven 项目中引入 Micrometer Prometheus 注册表和 Spring Boot Actuator 依赖。
```xml
io.micrometer
micrometer-registry-prometheus
org.springframework.boot
spring-boot-starter-actuator
```
--------------------------------
### 服务端动态刷新队列容量
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/dev_manual/queue-custom.md
在服务端处理线程池动态刷新时,仅支持对支持容量调整的队列进行修改。
```java
// ServerThreadPoolDynamicRefresh#handleQueueChanges
// 仅支持容量调整,不支持队列类型切换
if (parameter.getCapacity() != null) {
if (BlockingQueueManager.canChangeCapacity(executor.getQueue())) {
boolean success = BlockingQueueManager.changeQueueCapacity(
executor.getQueue(), parameter.getCapacity());
if (success) {
log.info("Queue capacity changed to: {} for thread pool: {}",
parameter.getCapacity(), parameter.getTpId());
}
}
}
```
--------------------------------
### Build Docker Image with Maven Plugin
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/ops/server-docker.md
Uses the maven docker plugin to build the image directly from the project directory.
```shell
# 进入到 threadpool/server/bootstrap 工程路径下
mvn clean package -DskipTests -Dskip.spotless.apply=true docker:build
```
--------------------------------
### Add Hippo4j Framework Adapters (XML)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Include these dependencies to enable Hippo4j's integration with specific frameworks like Dubbo, RabbitMQ, or RocketMQ. Alternatively, use the all-in-one adapter for broader compatibility.
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-dubbo
1.5.0
```
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-rabbitmq
1.5.0
```
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-rocketmq
1.5.0
```
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-all
1.5.0
```
--------------------------------
### 启动 Prometheus 服务
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
使用 Docker 快速部署 Prometheus 实例。
```shell
docker run -d -p 9090:9090 --name prometheus prom/prometheus
```
--------------------------------
### 启动 Grafana 服务
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
使用 Docker 部署 Grafana 以进行数据可视化。
```shell
docker run -d -p 3000:3000 --name=grafana grafana/grafana
```
--------------------------------
### 添加 Prometheus 抓取任务
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
在 prometheus.yml 的 scrape_configs 节点下配置目标地址。
```yaml
scrape_configs:
- job_name: 'dynamic-thread-pool-job'
scrape_interval: 5s
metrics_path: '/actuator/prometheus'
static_configs:
- targets: [ '127.0.0.1:29999' ]
```
--------------------------------
### Maven Dependency for Config Center Mode
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Include the Hippo4j Config Spring Boot Starter dependency for integration with configuration centers like Nacos, Apollo, Zookeeper, etc.
```xml
cn.hippo4j
hippo4j-config-spring-boot-starter
1.5.0
```
--------------------------------
### Configure Hippo4j Server Connection
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/server/hippo4j-server-start.md
Configure application properties to connect to the Hippo4j server, specifying server address, credentials, and tenant/project IDs. The project ID should match the application name.
```yaml
spring:
profiles:
active: dev
application:
# 服务端创建的项目 id 需要与 application.name 保持一致
name: dynamic-threadpool-example
dynamic:
thread-pool:
# 服务端地址
server-addr: http://localhost:6691
# 用户名
username: admin
# 密码
password: 123456
# 租户 id, 对应 tenant 表
namespace: prescription
# 项目 id, 对应 item 表
item-id: ${spring.application.name}
```
--------------------------------
### Add Hippo4j SpringBoot 1x Starter Dependency
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-springboot1x-adapter.md
Include this dependency in your pom.xml to enable Hippo4j support for SpringBoot 1.5.x.
```xml
cn.hippo4j
hippo4j-config-spring-boot-1x-starter
1.5.0
```
--------------------------------
### Add Monitoring Dependencies (XML)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Include these dependencies to enable thread pool metrics collection for Prometheus. Ensure `spring-boot-starter-actuator` is also present for exposing metrics.
```xml
io.micrometer
micrometer-registry-prometheus
org.springframework.boot
spring-boot-starter-actuator
```
--------------------------------
### Configure Framework Adapters (YAML)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Configure specific thread pools for framework adapters by defining their keys, associated marks, and pool sizes. This allows for fine-grained control over adapter thread pool behavior.
```yaml
# Config mode adapter configuration
spring:
dynamic:
thread-pool:
adapter-executors:
- threadPoolKey: 'input'
mark: 'RocketMQSpringCloudStream'
corePoolSize: 10
maximumPoolSize: 20
- threadPoolKey: 'dubbo-provider'
mark: 'Dubbo'
corePoolSize: 50
maximumPoolSize: 100
```
--------------------------------
### Register Custom Rejected Execution Handler via SPI
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/dev_manual/rejected-policy-custom.md
Register your custom rejected execution handler by creating a service file in `src/main/resources/META-INF/services`. The file name should be the fully qualified name of the interface, and the file content should be the fully qualified name of your custom implementation.
```text
cn.hippo4j.common.executor.support.CustomRejectedExecutionHandler
```
```text
cn.hippo4j.example.core.handler.ErrorLogRejectedExecutionHandler
```
--------------------------------
### General Dynamic Thread Pool Configuration
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-springboot1x-adapter.md
Define global settings for dynamic thread pools, including actuator paths, server ports, and specific executor parameters.
```yaml
management:
context-path: /actuator
security:
enabled: false
server:
port: 8091
servlet:
context-path: /example
spring:
application:
name: dynamic-threadpool-example
dynamic:
thread-pool:
banner: true
check-state-interval: 5
collect-type: micrometer
config-file-type: properties
enable: true
executors:
- active-alarm: 80
alarm: true
allow-core-thread-time-out: true
blocking-queue: LinkedBlockingQueue
capacity-alarm: 80
core-pool-size: 1
execute-time-out: 1000
keep-alive-time: 6691
maximum-pool-size: 1
notify:
interval: 8
receives: chen.ma
queue-capacity: 1
rejected-handler: AbortPolicy
thread-name-prefix: message-consume
thread-pool-id: message-consume
- active-alarm: 80
alarm: true
allow-core-thread-time-out: true
blocking-queue: LinkedBlockingQueue
capacity-alarm: 80
core-pool-size: 1
execute-time-out: 1000
keep-alive-time: 6691
maximum-pool-size: 1
notify:
interval: 8
receives: chen.ma
queue-capacity: 1
rejected-handler: AbortPolicy
thread-name-prefix: message-produce
thread-pool-id: message-produce
notify-platforms:
- platform: WECHAT
token: ac0426a5-c712-474c-9bff-72b8b8f5caff
profiles:
active: dev
```
--------------------------------
### Include Third-Party Framework Adapter JARs for Hippo4j
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/blog/2022-06-06-hippo4j/index.md
Include the appropriate adapter JAR for the third-party framework you are using alongside Hippo4j server or core. The version should match your Hippo4j version.
```xml
cn.hippo4j
hippo4j-spring-boot-starter-adapter-dubbo
hippo4j-spring-boot-starter-adapter-rabbitmq
hippo4j-spring-boot-starter-adapter-rocketmq
hippo4j-spring-boot-starter-adapter-spring-cloud-stream-rocketmq
1.3.0
```
--------------------------------
### 声明 SPI 配置文件
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/dev_manual/queue-custom.md
在 META-INF/services 目录下创建接口全限定名文件,并填入实现类的全限定名。
```text
cn.hippo4j.common.executor.support.CustomBlockingQueue
```
```text
com.example.queue.MyArrayBlockingQueue
```
--------------------------------
### Server Mode Configuration
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Configure Hippo4j Server Mode connection details in application.yml, including server address, credentials, namespace, and item ID.
```yaml
# application.yml
spring:
application:
name: dynamic-threadpool-example
dynamic:
thread-pool:
server-addr: http://localhost:6691
username: admin
password: 123456
namespace: prescription
item-id: ${spring.application.name}
```
--------------------------------
### Add JVM Configuration for Spring Boot 3
Source: https://github.com/opengoofy/hippo4j/blob/develop/examples/threadpool-example/server/adapter-rabbitmq-spring-boot3/README.md
When using Spring Boot 3 with JDK 17+, add this JVM argument to your startup configuration to enable necessary Java base module access.
```jvm
--add-opens java.base/java.util.concurrent=ALL-UNNAMED
```
--------------------------------
### Implement Custom RejectedExecutionHandlers
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Define custom rejection policies to handle thread pool saturation. These implementations allow for logging, blocking, or custom task management when the queue is full.
```java
package cn.hippo4j.example.handler;
import lombok.extern.slf4j.Slf4j;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
// Built-in: RunsOldestTaskPolicy - runs oldest task, adds new task to queue
public class RunsOldestTaskPolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
BlockingQueue workQueue = executor.getQueue();
Runnable firstWork = workQueue.poll();
boolean newTaskAdd = workQueue.offer(r);
if (firstWork != null) {
firstWork.run();
}
if (!newTaskAdd) {
executor.execute(r);
}
}
}
// Built-in: SyncPutQueuePolicy - blocks until queue has space
@Slf4j
public class SyncPutQueuePolicy implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
if (executor.isShutdown()) {
return;
}
try {
executor.getQueue().put(r);
} catch (InterruptedException e) {
log.error("Adding Queue task to thread pool failed.", e);
}
}
}
// Custom: Error logging rejection handler
@Slf4j
public class ErrorLogRejectedExecutionHandler implements RejectedExecutionHandler {
@Override
public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
log.error("Task rejected - Pool: {}, Active: {}, Completed: {}, Task: {}, Queue: {}",
executor.getPoolSize(),
executor.getActiveCount(),
executor.getCompletedTaskCount(),
executor.getTaskCount(),
executor.getQueue().size());
// Optionally persist rejected task for retry
throw new RuntimeException("Thread pool is exhausted");
}
}
```
--------------------------------
### 队列创建与验证操作
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/dev_manual/queue-custom.md
使用 BlockingQueueTypeEnum 创建队列实例,并利用 BlockingQueueManager 进行配置验证或容量调整。
```java
// 创建队列
BlockingQueue q = BlockingQueueTypeEnum.createBlockingQueue(queueType, capacity);
// 或者通过队列名称创建
BlockingQueue q2 = BlockingQueueTypeEnum.createBlockingQueue("ArrayBlockingQueue", capacity);
// 验证队列配置
boolean valid = BlockingQueueManager.validateQueueConfig(queueType, capacity);
// 动态调整容量(仅 ResizableCapacityLinkedBlockingQueue 支持)
boolean ok = BlockingQueueManager.changeQueueCapacity(executor.getQueue(), newCapacity);
```
--------------------------------
### 编辑 Prometheus 配置
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-monitor.md
进入容器内部并编辑配置文件以添加监控任务。
```shell
# 进入 prometheus 容器内部
docker exec -it prometheus /bin/sh
# 编辑 prometheus 配置文件
vi /etc/prometheus/prometheus.yml
```
--------------------------------
### Configure Notification Alarms (YAML)
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Set up global and per-pool alarm thresholds for active threads and queue capacity. Configure notification platforms like DingTalk, WeChat Work, and Lark, specifying recipients and intervals.
```yaml
spring:
dynamic:
thread-pool:
# Global notification settings
alarm: true
active-alarm: 80 # Alert when active threads reach 80% of max
capacity-alarm: 80 # Alert when queue reaches 80% capacity
alarm-interval: 8 # Seconds between repeated alarms
# Notification platforms
notify-platforms:
# DingTalk configuration
- platform: 'DING'
token: your-dingtalk-robot-token
secret: your-dingtalk-secret # For signed robots
# WeChat Work configuration
- platform: 'WECHAT'
token: your-wechat-robot-key
# Lark/Feishu configuration
- platform: 'LARK'
token: your-lark-robot-token
# Receivers format:
# DING: phone numbers (comma separated)
# WECHAT: user_id for @ mention, or name for regular mention
# LARK: ou_xxx user ID for @ mention, or phone for regular mention
receives: '13800138000,13900139000'
executors:
- thread-pool-id: 'critical-pool'
# Per-pool alarm overrides
alarm: true
active-alarm: 70
capacity-alarm: 70
notify:
interval: 5
receives: 'critical-team-member'
```
--------------------------------
### Configure Apollo for SpringBoot 1x
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-springboot1x-adapter.md
Set up Apollo configuration properties to manage dynamic thread pools in SpringBoot 1.5.x.
```yaml
apollo:
autoUpdateInjectedSpringProperties: true
bootstrap:
eagerLoad:
enabled: true
enabled: true
namespaces: application
meta: http://127.0.0.1:8080
app:
id: dynamic-threadpool-example
spring:
dynamic:
thread-pool:
apollo:
namespace: application
```
--------------------------------
### Server-side Dynamic Queue Capacity Adjustment
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/dev_manual/queue-custom.md
This snippet demonstrates the server-side logic for handling dynamic queue capacity changes. It checks if capacity adjustment is supported and attempts to change the queue's capacity, logging the outcome.
```java
// ServerThreadPoolDynamicRefresh#handleQueueChanges
// 仅支持容量调整,不支持队列类型切换
if (parameter.getCapacity() != null) {
if (BlockingQueueManager.canChangeCapacity(executor.getQueue())) {
boolean success = BlockingQueueManager.changeQueueCapacity(
executor.getQueue(), parameter.getCapacity());
if (success) {
log.info("Queue capacity changed to: {} for thread pool: {}\n",
parameter.getCapacity(), parameter.getTpId());
}
}
}
```
--------------------------------
### 实现自定义阻塞队列类
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/dev_manual/queue-custom.md
通过实现 CustomBlockingQueue 接口定义自定义队列逻辑,推荐覆写带 capacity 入参的方法以复用服务端配置。
```java
public class MyArrayBlockingQueue implements CustomBlockingQueue {
@Override
public Integer getType() {
return 1001;
}
@Override
public String getName() {
return "MyArrayBlockingQueue";
}
@Override
public BlockingQueue generateBlockingQueue(Integer capacity) {
int effectiveCapacity = capacity == null || capacity <= 0 ? 1024 : capacity;
return new ArrayBlockingQueue<>(effectiveCapacity);
}
}
```
--------------------------------
### Define Dynamic Thread Pool Bean
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/server/hippo4j-server-start.md
Create a configuration class and define ThreadPoolExecutor beans annotated with @DynamicThreadPool. The threadPoolId is mandatory; other parameters are optional and can be dynamically fetched from the server. If server connection fails, these parameters will be used to create the thread pool.
```java
package cn.hippo4j.example;
import cn.hippo4j.core.executor.DynamicThreadPool;
import cn.hippo4j.core.executor.support.ThreadPoolBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageConsumeDynamicExecutor() {
String threadPoolId = "message-consume";
ThreadPoolExecutor messageConsumeDynamicExecutor = ThreadPoolBuilder.builder()
.threadFactory(threadPoolId)
.threadPoolId(threadPoolId)
.dynamicPool()
.build();
return messageConsumeDynamicExecutor;
}
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageProduceDynamicExecutor() {
String threadPoolId = "message-produce";
ThreadPoolExecutor messageProduceDynamicExecutor = ThreadPoolBuilder.builder()
.threadFactory(threadPoolId)
.threadPoolId(threadPoolId)
.dynamicPool()
.build();
return messageProduceDynamicExecutor;
}
}
```
--------------------------------
### Configure Specific Thread Pool with Default Inheritance
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/version-1.5.0/user_docs/getting_started/config/hippo4j-config-default.md
Configure specific thread pools by providing a `thread-pool-id`. Other configurations will be inherited from `default-executor` unless explicitly overridden.
```yaml
executors:
- thread-pool-id: message-produce
- thread-pool-id: message-consume
core-pool-size: 80
maximum-pool-size: 100
execute-time-out: 1000
notify:
interval: 6
receives: chen.ma
```
--------------------------------
### Enable Dynamic Thread Pool
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/server/hippo4j-server-start.md
Annotate your Spring Boot application's main class with @EnableDynamicThreadPool to activate Hippo4j functionality.
```java
@SpringBootApplication
@EnableDynamicThreadPool
public class ExampleApplication {
public static void main(String[] args) {
SpringApplication.run(ExampleApplication.class, args);
}
}
```
--------------------------------
### Validate Queue Configuration
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/dev_manual/queue-custom.md
Verify if the provided queue type and capacity are valid according to the system's configuration. This is a server-side validation step.
```java
// 验证队列配置
boolean valid = BlockingQueueManager.validateQueueConfig(queueType, capacity);
```
--------------------------------
### Configure Dynamic ThreadPoolExecutor with @DynamicThreadPool
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/i18n/zh/docusaurus-plugin-content-docs/current/user_docs/getting_started/config/hippo4j-config-start.md
Define thread pool configurations using `@DynamicThreadPool` annotation. `threadPoolId` is mandatory for server-side creation. Other parameters are fetched from the configuration center.
```java
package cn.hippo4j.example;
import cn.hippo4j.core.executor.DynamicThreadPool;
import cn.hippo4j.core.executor.support.ThreadPoolBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadPoolExecutor;
@Configuration
public class ThreadPoolConfig {
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageConsumeDynamicExecutor() {
String threadPoolId = "message-consume";
ThreadPoolExecutor messageConsumeDynamicExecutor = ThreadPoolBuilder.builder()
.threadFactory(threadPoolId)
.threadPoolId(threadPoolId)
.dynamicPool()
.build();
return messageConsumeDynamicExecutor;
}
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageProduceDynamicExecutor() {
String threadPoolId = "message-produce";
ThreadPoolExecutor messageProduceDynamicExecutor = ThreadPoolBuilder.builder()
.threadFactory(threadPoolId)
.threadPoolId(threadPoolId)
.dynamicPool()
.build();
return messageProduceDynamicExecutor;
}
}
```
--------------------------------
### Configure Nacos for SpringBoot 1x
Source: https://github.com/opengoofy/hippo4j/blob/develop/docs/docs/user_docs/getting_started/config/hippo4j-config-springboot1x-adapter.md
Set up Nacos configuration properties to manage dynamic thread pools in SpringBoot 1.5.x.
```yaml
spring:
cloud:
nacos:
config:
ext-config:
- data-id: hippo4j-nacos.yaml
group: DEFAULT_GROUP
refresh: true
server-addr: 127.0.0.1:8848
dynamic:
thread-pool:
config-file-type: yml
nacos:
data-id: hippo4j-nacos.yaml
group: DEFAULT_GROUP
```
--------------------------------
### Configure Dynamic Thread Pools with ThreadPoolBuilder
Source: https://context7.com/opengoofy/hippo4j/llms.txt
Use the ThreadPoolBuilder fluent API to define dynamic thread pools with custom parameters or by ID within a Spring configuration class.
```java
package cn.hippo4j.example.config;
import cn.hippo4j.core.executor.DynamicThreadPool;
import cn.hippo4j.core.executor.support.ThreadPoolBuilder;
import cn.hippo4j.common.executor.support.BlockingQueueTypeEnum;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
public class ThreadPoolConfig {
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageConsumeDynamicExecutor() {
String threadPoolId = "message-consume";
return ThreadPoolBuilder.builder()
.threadPoolId(threadPoolId)
.threadFactory(threadPoolId)
.dynamicPool()
.corePoolSize(4)
.maximumPoolSize(16)
.keepAliveTime(60, TimeUnit.SECONDS)
.capacity(1024)
.workQueue(BlockingQueueTypeEnum.LINKED_BLOCKING_QUEUE)
.rejected(new ThreadPoolExecutor.CallerRunsPolicy())
.executeTimeOut(1000)
.waitForTasksToCompleteOnShutdown(true)
.awaitTerminationMillis(5000)
.allowCoreThreadTimeOut(false)
.build();
}
// Simple dynamic pool creation by ID
@Bean
@DynamicThreadPool
public ThreadPoolExecutor messageProduceDynamicExecutor() {
return ThreadPoolBuilder.buildDynamicPoolById("message-produce");
}
// Single thread pool
@Bean
@DynamicThreadPool
public ThreadPoolExecutor singleThreadExecutor() {
return ThreadPoolBuilder.builder()
.singlePool("single-thread-pool")
.dynamicPool()
.build();
}
}
```