dawdler-server
Module introduction
dawdler-server is the concrete implementation of the dawdler container side. It provides listeners for container startup and services, filters, server configuration, injected service listeners, class loaders, and AOP implementation.
1. Add the dependency in pom
<groupId>club.dawdler</groupId>
<artifactId>dawdler-server</artifactId>
2. Server configuration
2.1 server-conf.xml description
server-conf.xml is the core configuration file of the dawdler server.
Example configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<config>
<keyStore
keyStorePath="dawdler.keystore"
password="jackson.song1948@anywide"></keyStore><!--
keyStorePath keystore path, password password -->
<server host="0.0.0.0" tcp-port="9527"
shutdownWhiteList="127.0.0.1,localhost" shutdownHost="127.0.0.1" tcp-shutdownPort="19530"
tcp-backlog="200" tcp-sendBuffer="163840" tcp-receiveBuffer="163840"
tcp-keepAlive="false" tcp-noDelay="false" maxThreads="200" queueCapacity="1024" maxInFlightPerSession="-1" keepAliveMilliseconds="0" virtualThread="false"
auth-timeout="3000" max-connections="2048" max-connections-per-ip="128" max-pending-auth-connections="512"
auth-failure-threshold="0" auth-failure-window="60000" auth-failure-backoff="1000" auth-failure-backoff-max="60000"
auth-rate-per-ip="0" auth-burst-per-ip="0" auth-rate="0" auth-burst="0" auth-tracked-ips="8192"
max-tracked-ips-per-ip-quota="0">
</server>
<!-- tcp-port the port on which the server starts, shutdownWhiteList the whitelist allowed to shut down the service, shutdownHost the bind address of the shutdown service port, tcp-shutdownPort the port number for shutting down the server
maxThreads the size of the business processing thread pool, default 200, queueCapacity the thread pool queue size, default 1024 (aligned with the client processing queue; exceeding it triggers a busy rejection with fast failure), maxInFlightPerSession the per-session in-flight request limit, default -1 (unlimited), keepAliveMilliseconds the timeout for idle threads in the thread pool to wait for work, default 0, the rest are TCP settings, virtualThread whether to enable virtual threads
auth-timeout the wall-clock deadline for unauthenticated connections (milliseconds), default 3000, heartbeats do not extend it; max-connections the global connection limit, default 2048; max-connections-per-ip the per-IP connection limit, default 128; max-pending-auth-connections the limit of pending unauthenticated connections, default 512. The three limit settings set to 0 mean unlimited
For authentication anti-brute-force parameters see "Authentication anti-brute-force parameters (optional)" below in the same section, all 0 means disabled, by default all are disabled to preserve existing behavior -->
<global-auth>
<user username="global_user" password="global_password" />
<user username="global_user_1" password="global_password" />
</global-auth>
<!-- Globally common users; the username attribute on the user node is the username, password is the password. -->
<module-auth>
<module name="user-service">
<user username="user1" password="user1password" />
<user username="user2" password="user2password" />
</module>
<module name="order-service">
<user username="order_user1" password="user1password" />
</module>
</module-auth><!-- Users under a module; name on module specifies the module name, the username attribute on the user node is the username, password is the password -->
<health-check check="on" scheme="https" port="19001" backlog="0" username="jackson" password="jackson.song">
<elasticSearch check="on" />
<jedis check="on" />
<rabbit check="on" />
<dataSource check="on" />
<config check="on" />
</health-check>
</config>
Attribute description:
keyStore node
This is the keystore configuration, used for HTTPS health checks. keyStorePath is the keystore path, password is the password. The keystore type automatically follows the JDK default (JKS on JDK8, PKCS12 on JDK9+); a keystore generated with the keytool default is sufficient. RPC authentication uses a challenge-response mechanism and requires no keystore.
server node configuration
host="0.0.0.0" the IP address of the server side supports IPV6, IPV6="::", IPV4="0.0.0.0". dawdler binds the IP automatically based on the configuration; if a specific IP is needed, just configure that IP directly.
tcp-port="9527" port number
shutdownWhiteList="127.0.0.1,localhost" shutdownWhiteList is the whitelist of IPs allowed to shut down the service, separated by commas; generally no change is needed. Unless there is a requirement to stop the service remotely. Entries support IP or hostname, and loopback addresses (localhost/127.0.0.1/::1) are mutually accessible; if configured as an empty string, the shutdown service port is not started (stop can then only be performed via JMX or kill); entries that cannot be resolved are skipped and a warn log is recorded.
shutdownHost="127.0.0.1" the bind address of the shutdown service port; the default 127.0.0.1 is only reachable locally. When remote stopping is required, explicitly configure it as "0.0.0.0" (or a specific NIC IP) and allow the remote source IPs through shutdownWhiteList.
tcp-shutdownPort="19530" the port number for shutting down the service
tcp-backlog="200" specifies the length of the socket connection queue
tcp-sendBuffer="163840" TCP send buffer
tcp-receiveBuffer="163840" TCP receive buffer
tcp-keepAlive="false" keep long connections alive
tcp-noDelay="false" disable Nagle's algorithm
maxThreads=200 the size of the business processing thread pool
queueCapacity=1024 the queue size of the business processing thread pool; when the queue is full a busy rejection is triggered (ServerBusyException fast failure); when adjusting for higher throughput, also evaluate the client timeout configuration accordingly
maxInFlightPerSession=-1 the concurrent in-flight request limit per session (per connection), preventing one slow-consuming connection from exhausting the global concurrency pool; -1 means unlimited (default, relying only on the global thread pool/queue capacity), 0 means automatic based on maxThreads/8 (at least 16), a positive number is an explicit limit. When exceeded, the request returns `server busy (session in-flight limit reached), please retry later` (ServerBusyException, the connection is not closed)
virtualThread whether to enable virtual threads
auth-timeout="3000" the wall-clock deadline for unauthenticated connections (milliseconds); heartbeats and any reads do not extend this time, default 3000
max-connections="2048" the global connection limit, 0 means unlimited
max-connections-per-ip="128" the per-IP connection limit, 0 means unlimited
max-pending-auth-connections="512" the limit of pending unauthenticated connections, 0 means unlimited
##### Authentication anti-brute-force parameters (optional)
Each RPC authentication check runs PBKDF2 with 600,000 iterations, a millisecond-level slow operation. The parameters below are used to block malicious authentication traffic at the **admission stage**,
so that an attacker cannot saturate the authentication path (and business threads) with a large number of connections. Any configuration with all 0 means disabled; by default all are disabled to preserve existing behavior;
it is recommended to enable the first two groups as needed in production:
```txt
auth-failure-threshold="0" per-IP authentication failure backoff threshold: once failures from the same IP reach this count within the window, backoff begins; default 0 (disabled), 3~5 is recommended
auth-failure-window="60000" failure counting window (milliseconds), default 60000
auth-failure-backoff="1000" backoff base (milliseconds), default 1000; the backoff duration of the n-th over-threshold failure is base << (n-threshold)
auth-failure-backoff-max="60000" backoff cap (milliseconds), default 60000
auth-rate-per-ip="0" per-IP authentication rate (tokens per second), default 0 (disabled); when enabled it is recommended to pair it with auth-burst-per-ip
auth-burst-per-ip="0" per-IP token bucket capacity, default 0 (disabled)
auth-rate="0" global authentication rate (tokens per second), default 0 (disabled)
auth-burst="0" global token bucket capacity, default 0 (disabled)
auth-tracked-ips="8192" the upper limit of IPs recorded in the backoff and rate-limiting state table, default 8192, preventing attackers from exhausting memory by switching source IPs
max-tracked-ips-per-ip-quota="0" the upper limit of IPs in the per-IP connection counting table, default 0 (unlimited);
an entry is deleted once its count drops to zero (the table size never exceeds the number of active connections); when the limit is exceeded, the IP with the smallest count is evicted to make room for the new IP, and established connections are unaffected
Decision order: when a new connection is established, the failure backoff is checked first (rejected directly during the penalty period), then the authentication rate token is deducted, and only then is the connection quota applied. Authentication failures (including failing to complete authentication within auth-timeout) are recorded in the backoff, and a successful authentication immediately clears the count for that IP. In addition, authentication frames are handled by a dedicated authentication thread pool (thread count = min(4, CPU cores), bounded queue 256), not shared with business threads, so even if authentication is fully occupied, business requests on already-authenticated connections can still be processed normally.
global-auth node
Used to configure global users for the entire dawdler server; the username attribute on the user node is the username, password is the password. Global users can be used for authenticating client calls to all services deployed inside this server.
module-auth node
Used to configure users under a specified module; name on module specifies the module name, the username attribute on the user node is the username, password is the password.
health-check node
Used to configure health checks, which can serve as k8s liveness and readiness for the service. If Basic Authentication is configured, add the Authorization header information via the header.
Besides the /health health-check endpoint, the server also provides /live (liveness) and /ready (readiness) endpoints with k8s probe semantics. Both share Basic Authentication with /health, and their URIs can be overridden via the dawdler.server.health.liveUri/dawdler.server.health.readyUri configuration (defaults /live//ready); see Cloud-native k8s integration for details.
check="on" enables health checks, off disables them. When disabled, the http/https service is not started.
scheme="http" provides the HTTP service; it can be set to https, using the keystore in keyStore as the https certificate; the keystore type follows the JDK default (JKS on JDK8, PKCS12 on JDK9+).
port="19001" the port number for providing the http/https service
backlog="0" specifies the length of the socket connection queue, default 0, a system-level limit.
username="jackson" username; if this attribute is not filled in, the authentication module is not enabled.
password="jackson.song" password; if this attribute is not filled in, the authentication module is not enabled.
uri="/health" the URI of the health check, default /health.
timeout="5000" the timeout in milliseconds for health checks of a single component, default 5000; on timeout it is reported as DOWN and the component details carry a timeout note, without blocking the health endpoint.
Below are the component nodes for which health checks are supported; if check is set to off or the node is omitted, no health check is triggered.
elasticSearch es check
jedis redis check
rabbit rabbitmq check
dataSource data source check
config config center check
2.2 Creating a certificate with keytool
The dawdler example uses a certificate created with keytool; on the server side it is configured in the keyStore node of the server-conf file for HTTPS health checks. The keystore type automatically follows the JDK default (JKS on JDK8, PKCS12 on JDK9+); a keystore generated with the keytool default is sufficient. RPC authentication uses a challenge-response mechanism and requires no certificate.
The command to create a certificate with keytool is as follows:
keytool -validity 65535 -genkey -v -alias srchen -keyalg RSA -keystore dawdler.keystore -dname "CN=jackson,OU=互联网事业部,O=anywide,L=DALIAN,ST=LIAONING,c=CN" -storepass suxuan696@gmail.com -keypass jackson.song
keytool command description
Keytool is a Java data certificate management tool; a brief description follows.
-genkey generate a key
-alias alias
-keyalg key algorithm
-keysize key length
-validity validity period
-keystore storage path and name of the generated keystore
-keypass key passphrase
-storepass keystore passphrase
-dname owner information, CN: name; OU: organizational unit name; O: organization name; L: province/city/autonomous region name; C: country/region code
3. dawdler server startup/destroy listeners
Implement the DawdlerServiceListener interface; the @Order annotation is supported for ascending ordering. The contextInitialized method is called on server initialization and the contextDestroyed method is called on server destruction. Both methods are called when services deployed under dawdler server's deploys start and are destroyed.
The @ListenerConfig annotation is used for DawdlerServiceListener; it identifies whether execution is asynchronous and supports setting a delay time.
Use cases: DawdlerServiceListener implementation classes run when dawdler starts and is destroyed and can be used to initialize and destroy resources. The asynchronous case exists to prevent resource initialization from stalling container startup, and the delay time exists to postpone invoking the current listener until other resources have finished loading.
public @interface ListenerConfig {
long delayMsec() default 0L;// delayTime in milliseconds, effective only under asynchronous execution
boolean asyn() default false;// whether to execute asynchronously
}
Example 1:
public class UserServiceStartupListener implements DawdlerServiceListener{
@Override
public void contextDestroyed(DawdlerContext dawdlerContext) throws Exception {
System.out.println("UserServiceStartupListener contextDestroyed:"+dawdlerContext.getDeployClassPath());
}
@Override
public void contextInitialized(DawdlerContext dawdlerContext) throws Exception {
System.out.println("UserServiceStartupListener contextInitialized:"+dawdlerContext.getDeployClassPath());
}
}
Example 2:
//Start asynchronously with a 3-second delay
@ListenerConfig(asyn=true,delayMsec=3000)
public class UserServiceAsyncStartupListener implements DawdlerServiceListener{
@Override
public void contextDestroyed(DawdlerContext dawdlerContext) throws Exception {
System.out.println("UserServiceAsyncStartupListener contextDestroyed:"+dawdlerContext.getDeployClassPath());
}
@Override
public void contextInitialized(DawdlerContext dawdlerContext) throws Exception {
System.out.println("UserServiceAsyncStartupListener contextInitialized:"+dawdlerContext.getDeployClassPath());
}
}
4. dawdler service filters
Implement the DawdlerFilter interface and the doFilter method; the @Order annotation is supported for ascending ordering. All service calls pass through the filter.
Example:
public class MyFilter implements DawdlerFilter{
@Override
public void doFilter(RequestBean request, ResponseBean response, FilterChain chain) throws Exception {
chain.doFilter(request, response);
}
}
5. dawdler service creation listeners
Implement the DawdlerServiceCreateListener interface and the create method. The @Order annotation is supported for ascending ordering. This method is called when a service entity class is initialized; in the singleton case it is created when the server starts, while in the multi-instance case it is called when invoked. Whether it is a singleton is set via the @Service annotation on the server side; single defaults to true, meaning singleton.
Example of using InjectServiceCreateListener in dawdler-server-plug-mybatis:
public class InjectServiceCreateListener implements DawdlerServiceCreateListener {
private static final Logger logger = LoggerFactory.getLogger(InjectServiceCreateListener.class);
private SqlSession sqlSession = SingleSqlSessionFactory.getInstance().getSqlSession();
@Override
public void create(Object service, boolean single, DawdlerContext dawdlerContext) {
inject(service, dawdlerContext);
}
private void inject(Object service, DawdlerContext dawdlerContext) {
Field[] fields = service.getClass().getDeclaredFields();
for (Field field : fields) {
Resource resource = field.getAnnotation(Resource.class);
if (!field.getType().isPrimitive()) {
Class<?> serviceClass = field.getType();
field.setAccessible(true);
try {
if (resource != null && serviceClass.isInterface()) {
field.set(service, sqlSession.getMapper(serviceClass));
}
} catch (Exception e) {
logger.error("", e);
}
}
}
}
}
6. How to use AOP
dawdler's AOP is based on the AspectJ weaver: bytecode weaving is completed when the dawdler custom class loader loads a class (before defineClass), i.e., load-time weaving, but the weaving point is embedded in dawdler's class loader and does not depend on -javaagent; unlike Spring's runtime proxy approach using cglib/JDK dynamic proxies, calls after weaving are direct code with no proxy forwarding overhead.
Scope: all classes deployed on the dawdler server side
Example (intercepting ServiceImpl):
Note: both files below need to be created on the server side
- Create META-INF\aop.xml
<aspectj>
<aspects>
<aspect name="com.anywide.yyg.user.aop.UserServiceAspect"/>
</aspects>
</aspectj>
- Create the com.anywide.yyg.user.aop.UserServiceAspect class
@Aspect
public class UserServiceAspect {
@Around("execution(* com.anywide.yyg.user.service.impl .*.selectUserList(..))")
public Object logAround(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("start ...\tlogAround" + pjp.getSignature().getName());
Object o = null;
try {
o = pjp.proceed();
} catch (Throwable t) {
throw t;
}
Object[] args = pjp.getArgs();
System.out.println("over:\t" + args);
return o;
}
}
The read-write splitting in dawdler-server-plug-mybatis is also implemented with AOP; see Switching database connections via AOP.
7. Health checks
The dawdler server provides health check functionality; the URI defaults to /health; refer to the health-check node configuration.
Example:
wget https://192.168.43.137:19001/health
Returns:
{"status":"UP","chain-service":{"status":"UP","rabbit":{"status":"UP"},"jedis":{"status":"UP"},"dataSource":{"status":"UP"}},"wallet-service":{"status":"UP","rabbit":{"rabbitmq":{"version":"3.9.10","status":"UP"},"status":"UP"},"jedis":{"jedis":{"version":"redis_version:6.2.1","status":"UP"},"status":"UP"},"elasticSearch":{"myEs":{"clusterName":"elasticsearch","numberOfNodes":1,"numberOfDataNodes":1,"activePrimaryShards":2,"activeShards":2,"relocatingShards":0,"initializingShards":0,"unassignedShards":0,"status":"UP"},"status":"UP"},"dataSource":{"write1":{"status":"UP"},"read1":{"status":"UP"},"status":"UP"},"config":{"consul":{"info":"fedora-dc1-1.12.0","status":"UP"},"status":"UP"}}}
8. JMX monitoring
dawdler-server has built-in JMX MBeans, providing runtime metric monitoring and remote management capabilities, with zero external dependencies (based on the native JMX of java.lang.management).
Disabled by default; enable it via a system variable:
-Ddawdler.server.metrics.enabled=true
When enabled, MBeans are registered and instrumentation statistics are collected; when disabled, all instrumentation methods are no-ops (ENABLED is static final, so JIT constant folding can eliminate all counting and timing overhead on the hot path), and no MBeans are registered.
Latency statistics use a ring histogram over the most recent N requests, adjustable via a system property (default 1024; the value is normalized to a power of 2 within [16, 1048576]):
-Ddawdler.server.metrics.latency.window=4096
Buckets are divided by powers of 2, and percentiles take the lower bound of the bucket (i.e., the actual value falls within [percentile, 2 × percentile); the relative error at the 1ms scale is less than 0.1%); the window rolls with requests and reflects only recent traffic; for cumulative request volume see TotalRequests.
8.1 MBean list
All MBeans are registered under the club.dawdler.server domain:
| objectName | Description | Key attributes |
|---|---|---|
club.dawdler.server:type=Connection | Connection layer | ConnectionCount, PendingAuthConnectionCount, FrameTimeouts, FrameBudgetRejections, InFlightFrameBytes, MaxInFlightFrameBytes, TotalAcceptedConnections, TotalRejectedConnections, TotalClosedConnections, TotalAuthTimeouts, TotalAuthenticatedConnections, TotalClosedAuthenticatedConnections, PendingTaskCount, TotalWriteBudgetExhausted |
club.dawdler.server:type=ThreadPool | Worker thread pool | ActiveThreads, PoolSize, QueueSize, QueueCapacity, CompletedTaskCount, RejectedCount, AvailablePermits (virtual threads), MaxPermits (virtual threads) |
club.dawdler.server:type=RequestProcessor | Request processing | TotalRequests, TotalResponses, TotalErrors, TotalBusyRejections, TotalWriteBackpressureClosed, AvgProcessTimeMillis, P50ProcessTimeMillis, P95ProcessTimeMillis, P99ProcessTimeMillis, ProcessTimeSampleCount, ErrorRate, TotalAuthAttempts, TotalAuthSuccess, TotalAuthFailures, AuthSuccessRate |
club.dawdler.server:type=ServerStatus | Server status | Started, Host, TcpPort, TcpBacklog, UptimeMillis, VirtualThread, DeployedServiceCount |
club.dawdler.server:type=JvmMonitor | JVM runtime | ProcessCpuLoad, SystemCpuLoad, HeapUsedBytes, HeapCommittedBytes, HeapMaxBytes, HeapUsedPercent, NonHeapUsedBytes, NonHeapCommittedBytes, GcCollectionCount, GcCollectionTimeMillis, ThreadCount, PeakThreadCount, DaemonThreadCount, LoadedClassCount, TotalLoadedClassCount, UnloadedClassCount, JvmUptimeMillis, FindDeadlockedThreads |
JvmMonitor collects data via the JDK native ManagementFactory (plus the com.sun.management extension), with no third-party dependencies.
ServerStatus also provides two remote operations: shutdownGraceful() (graceful shutdown) and shutdownNow() (immediate shutdown), as a supplement to the listenStop socket mechanism.
In virtual thread mode, the thread pool MBean delegates to Semaphore to expose permit metrics (AvailablePermits/MaxPermits); in platform thread mode, it delegates to ThreadPoolExecutor to expose queue/thread metrics.
The details of each MBean attribute are as follows:
Connection (connection layer)
| Attribute name | Type | Description |
|---|---|---|
| ConnectionCount | int | Current number of active connections (real-time, including authenticated and pending unauthenticated) |
| PendingAuthConnectionCount | int | Number of connections that have been accepted but have not yet completed authentication (real-time) |
| FrameTimeouts | long | Cumulative number of connections closed due to whole-frame deadline timeouts (monotonically increasing since service start) |
| FrameBudgetRejections | long | Cumulative number of connections closed due to insufficient in-flight frame byte budget (monotonically increasing since service start) |
| InFlightFrameBytes | long | Number of in-flight bytes currently occupied by unfinished large frames (real-time) |
| MaxInFlightFrameBytes | long | Global in-flight frame byte budget limit (0=unlimited) |
| TotalAcceptedConnections | long | Cumulative number of accepted connections (monotonically increasing since service start) |
| TotalRejectedConnections | long | Cumulative number of connections rejected due to the global/per-IP/pending unauthenticated quotas (monotonically increasing since service start) |
| TotalClosedConnections | long | Cumulative number of closed connections (monotonically increasing since service start) |
| TotalAuthTimeouts | long | Cumulative number of connections closed for not completing authentication within auth-timeout (monotonically increasing since service start) |
| TotalAuthThrottled | long | Cumulative number of connections rejected due to per-IP authentication failure backoff (auth-failure-threshold etc.) (monotonically increasing since service start) |
| TotalAuthRateLimited | long | Cumulative number of connections rejected due to authentication rate limiting (auth-rate / auth-rate-per-ip token buckets) (monotonically increasing since service start) |
| TotalAuthenticatedConnections | long | Cumulative number of authenticated connections (monotonically increasing since service start, reusing the authentication success count) |
| TotalClosedAuthenticatedConnections | long | Cumulative number of closed authenticated connections (monotonically increasing since service start) |
| PendingTaskCount | long | Number of calls that have not yet returned a response (sum of unfinished tasks across all sessions) |
| TotalWriteBudgetExhausted | long | Cumulative number of requests/responses that were answered with a busy response due to exhaustion of the off-heap staging pool budget (monotonically increasing since service start) |
Note: The session buffer pool (DirectBufferPool) and the payload staging pool (PayloadBufferPool) no longer expose pool-level monitoring metrics; for actual off-heap usage, observe it together with the JVM native direct BufferPool (BufferPoolMXBean).
ThreadPool (worker thread pool)
| Attribute name | Type | Description |
|---|---|---|
| VirtualThreadMode | boolean | Whether in virtual thread mode (true=virtual threads, false=platform thread pool) |
| ActiveThreads | int | Number of active threads; in platform thread mode taken from ThreadPoolExecutor.getActiveCount, in virtual thread mode returns -1 |
| PoolSize | int | Current number of threads in the thread pool; in platform thread mode taken from ThreadPoolExecutor.getPoolSize, in virtual thread mode returns -1 |
| QueueSize | long | Length of the pending task queue; in platform thread mode taken from the blocking queue size, in virtual thread mode returns -1 |
| QueueCapacity | long | Task queue capacity (configured value, effective in platform thread mode) |
| CompletedTaskCount | long | Cumulative number of completed tasks; in platform thread mode taken from ThreadPoolExecutor.getCompletedTaskCount, in virtual thread mode returns -1 |
| RejectedCount | long | Cumulative number of busy rejections (task submissions rejected, data taken from ServerMetrics) |
| AvailablePermits | int | Number of available semaphore permits; in virtual thread mode taken from Semaphore.availablePermits, in platform thread mode returns -1 |
| MaxPermits | int | Maximum number of semaphore permits (maxThreads+queueCapacity in virtual thread mode, maxThreads in platform thread mode) |
RequestProcessor (request processing)
| Attribute name | Type | Description |
|---|---|---|
| TotalRequests | long | Cumulative number of requests (monotonically increasing since service start) |
| TotalResponses | long | Cumulative number of responses (monotonically increasing since service start) |
| TotalErrors | long | Cumulative number of processing exceptions (monotonically increasing since service start) |
| TotalBusyRejections | long | Cumulative number of busy rejections (rejections caused by a full thread pool or timeout) |
| TotalWriteBackpressureClosed | long | Cumulative number of connections closed due to write-back backpressure timeout (number of sessions shut down because the response write buffer kept timing out) |
| AvgProcessTimeMillis | double | Average request processing latency (milliseconds, mean of the lower bounds of sample buckets within the recent window; 0 when the window has no samples) |
| P50ProcessTimeMillis | double | P50 processing latency within the recent window (milliseconds) |
| P95ProcessTimeMillis | double | P95 processing latency within the recent window (milliseconds) |
| P99ProcessTimeMillis | double | P99 processing latency within the recent window (milliseconds) |
| ProcessTimeSampleCount | long | Cumulative number of requests entering latency statistics (monotonically increasing since service start, unaffected by window wraparound) |
| ErrorRate | double | Error rate (cumulative exceptions / cumulative requests, 0 when there are no requests) |
| TotalAuthAttempts | long | Cumulative number of authentication attempts (monotonically increasing since service start) |
| TotalAuthSuccess | long | Cumulative number of successful authentications (monotonically increasing since service start) |
| TotalAuthFailures | long | Cumulative number of failed authentications (monotonically increasing since service start) |
| AuthSuccessRate | double | Authentication success rate (cumulative successes / cumulative attempts, 0 when there are no attempts) |
ServerStatus (server status)
| Attribute name/operation | Type | Description |
|---|---|---|
| Started | boolean | Whether the server has finished starting (returns true in the accepting-connections phase) |
| Host | String | Listening host address (configured value) |
| TcpPort | int | TCP listening port (configured value) |
| TcpBacklog | int | TCP connection queue length backlog (configured value) |
| UptimeMillis | long | Uptime (milliseconds, current time minus start time; 0 when not started) |
| VirtualThread | boolean | Whether in virtual thread mode (configured value) |
| DeployedServiceCount | int | Number of deployed service modules |
| shutdownGraceful() | void | Graceful shutdown: waits for in-progress requests to complete before exiting |
| shutdownNow() | void | Immediate shutdown: does not wait for in-progress requests |
JvmMonitor (JVM runtime)
| Attribute name/operation | Type | Description |
|---|---|---|
| ProcessCpuLoad | double | CPU usage of the JVM process at the most recent sample (0.0~1.0, -1 when collection is unavailable) |
| SystemCpuLoad | double | Whole-system CPU usage at the most recent sample (0.0~1.0, -1 when collection is unavailable) |
| AvailableProcessors | int | Number of available processor cores |
| ProcessId | String | Current JVM process ID |
| HeapUsedBytes | long | Heap memory currently used (bytes) |
| HeapCommittedBytes | long | Heap memory committed (bytes) |
| HeapMaxBytes | long | Heap memory limit (bytes, -1 when unlimited) |
| HeapUsedPercent | double | Heap memory usage (used/max, 0.0~1.0, -1 when unlimited) |
| NonHeapUsedBytes | long | Non-heap memory currently used (bytes) |
| NonHeapCommittedBytes | long | Non-heap memory committed (bytes) |
| GcCollectionCount | long | Cumulative number of heap GC collections (aggregated across all collectors) |
| GcCollectionTimeMillis | long | Cumulative heap GC time (milliseconds, aggregated across all collectors) |
| ThreadCount | int | Current number of live threads |
| PeakThreadCount | int | Peak thread count (highest since JVM start) |
| DaemonThreadCount | int | Current number of daemon threads |
| findDeadlockedThreads() | long[] | Returns null if no deadlock is detected since the last deadlock detection; returns an array of deadlocked thread IDs if a deadlock is detected |
| LoadedClassCount | int | Current number of loaded classes |
| TotalLoadedClassCount | long | Cumulative total number of loaded classes |
| UnloadedClassCount | long | Cumulative total number of unloaded classes |
| JvmUptimeMillis | long | JVM uptime (milliseconds, since JVM start) |
| JavaVersion | String | Current Java version |
| InputArguments | String[] | List of JVM arguments passed when starting the JVM |
8.2 Viewing via jconsole/jvisualvm
After starting dawdler-server, connect to the local process directly with jconsole or jvisualvm, and the above metrics can be seen on the MBeans tab. Remote connections require adding JVM parameters:
-Dcom.sun.management.jmxremote.port=9500
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
8.3 Integrating Prometheus + Grafana
Bridge via jmx_exporter as a Java Agent, with zero intrusion into dawdler:
java -javaagent:./jmx_prometheus_javaagent.jar=9404:jmx-exporter-config.yml
See src/main/resources/example/jmx-exporter-config.yml for an example configuration file; it already predefines mappings from patterns of all dawdler MBeans to Prometheus metrics. 9404 is the HTTP port exposed for Prometheus scraping; access http://<host>:9404/metrics to obtain the metrics.
Port permission protection: The
/metricsHTTP port ofjmx_prometheus_javaagentnatively supports no authentication whatsoever (neither Basic Auth nor Token is available), so the agent itself cannot add authentication to this port. To protect this endpoint, the following combination is recommended:
- Bind to an intranet (LAN) IP -- write the agent parameter as
<intranet IP>:9404:jmx-exporter-config.yml(host:port:config), e.g.192.168.1.100:9404:jmx-exporter-config.yml, so that the metrics are reachable only within the intranet and not exposed to the public network;- Forward through an authenticated proxy -- if Prometheus and the server are not in the same broadcast domain, use the built-in
DawdlerHttpServer(the health-check node already supports Basic Auth) or nginx to reverse proxy/metricsto<intranet IP>:9404, letting the authentication layer intercept unauthorized access;- Firewall/network ACL -- at the host or container network layer, allow only the Prometheus server IP to access 9404, as a second line of defense.
On the Grafana side, an out-of-the-box monitoring dashboard is provided at src/main/resources/example/grafana-dashboard.json; to import it:
- Grafana → Dashboards → New → Import → upload the JSON file
- On first import, select the Prometheus data source (the dashboard top variable
DS_PROMETHEUS); thejobandinstancevariables are filled automatically from the scrape targets - The dashboard is grouped by rows: Overview (running status/uptime/error rate/active connections), request processing golden signals (QPS/latency/error rate/busy rejections/write-back backpressure closures/unfinished calls), connection layer (active connections/accept and close rates/authenticated active connections), frame protection (frame timeouts/in-flight frame byte budget/write-side off-heap budget exhaustion), worker thread pool (adapted separately for platform thread and virtual thread modes), authentication statistics, JVM runtime (CPU/heap memory/heap usage/non-heap/GC/threads)
All metric names in the dashboard correspond one-to-one with the mappings in jmx-exporter-config.yml; Counter-type metrics are converted to rates using rate(...[1m]).
9. Graceful shutdown
dawdler-server supports graceful shutdown: when stopping, it first takes all services under this container offline from the registry (no longer accepting new requests), then waits for in-flight requests to finish processing before shutting down the server.
Trigger methods:
| Trigger method | Description |
|---|---|
sh dawdler.sh stop | Triggered via the shutdown port (shutdownHost/tcp-shutdownPort); the source IP must be in the shutdownWhiteList, see server node configuration |
JMX shutdownGraceful() | Remote management operation, see ServerStatus (server status) |
kill or Ctrl+C | JVM shutdown hook, which also follows the graceful shutdown flow (except kill -9, which does not trigger the hook) |
sh dawdler.sh stopnow / JMX shutdownNow() | Immediate shutdown without waiting for in-flight requests; client requests not yet processed receive a forced-stop exception |
The graceful shutdown flow is extensible via an SPI (ContainerGracefulShutdown); components such as dawdler-server, rabbitmq, kafka, and schedule drain their own resources in @Order sequence (the wait duration of each component is controlled by the component itself), and only after all have completed (with an overall cap of 120 seconds) are connections and thread pools shut down uniformly. The timeout for dawdler-server to wait for in-flight requests is configured via the system property dawdler.server.graceful.timeout:
-Ddawdler.server.graceful.timeout=30000
| Property | Default value | Description |
|---|---|---|
| dawdler.server.graceful.timeout | 30000 | The timeout in milliseconds for dawdler-server to wait for in-flight requests to finish processing. During the wait it is woken via the idle signal notify, and it shuts down immediately once all in-flight tasks are complete; on timeout a warn log (Graceful shutdown timeout after ...) is recorded and shutdown is forced, with unfinished requests forcibly interrupted; if the waiting thread is interrupted, it likewise stops waiting and shuts down directly. |
After all SPI drains complete, connections and thread pools are shut down uniformly; the timeout for the thread pools to await termination is configured via the system property dawdler.server.shutdown.poolAwaitTimeout:
-Ddawdler.server.shutdown.poolAwaitTimeout=10000
| Property | Default value | Description |
|---|---|---|
| dawdler.server.shutdown.poolAwaitTimeout | 10000 | The timeout in milliseconds to wait for the worker thread pools to terminate during shutdown. It applies separately to the business processing thread pool (dataProcessWorkerPool) and the busy response worker (busyResponseWorker); if termination has not occurred on timeout, a warn log (... did not terminate in ...ms during shutdown, remaining tasks are abandoned.) is recorded and the remaining tasks are abandoned; if the waiting thread is interrupted, it likewise stops waiting. |