Sensors Data Analytics Development and Integration Documentation
Based on the SensorsConfig.java configuration class, this section provides detailed instructions on how to integrate Sensors Analytics into your project, including configuration guidelines, code integration, and usage examples.
- 16 min read
- 2026.08.04
SensorsData Analytics’ Java integration is centrally managed by the SensorsConfig configuration class: the DEBUG mode is used in the development environment for real-time validation of tracking points, while the BATCH mode is used in the production environment for batch reporting. Configurations for each environment are distributed via Nacos to prevent test data from contaminating the production project.
🎯 Sensors Data Analytics Development Integration Documentation
📖 Overview
Sensors Analytics is a professional user behavior analytics product. This document, based on the SensorsConfig.java configuration class, provides detailed instructions on how to integrate Sensors Analytics functionality into your project.
✨ Features
🏗️ Technical Architecture
Application Layer → ISensorsAnalytics → Consumer → SensorsData Server (Tracking Interface) (Data Consumer) (Data Collection)
📦 Dependency Configuration
Maven Dependencies
Add the Sensors Data SDK dependency to the project’s pom.xml:
<!-- 引入神策分析 SDK -->
<dependency>
<groupId>com.sensorsdata.analytics.javasdk</groupId>
<artifactId>SensorsAnalyticsSDK</artifactId>
<version>3.6.8</version>
</dependency>
📋 Version Compatibility
Components | Version Requirements |
|---|---|
JDK Version | 1.8+ |
Spring Boot Version | 2.x+ |
Sensors Data SDK Versions | 3.6.8 |
⚙️ Configuration Guide
Configuration Property Class
In your project, use the SensorsDataProperties class to manage Sensors Data-related configurations:
@RefreshScope
@Data
@Component
@ConfigurationProperties(prefix = "sensorsdata")
public class SensorsDataProperties {
/**
* 神策服务地址
*/
private String serverUrl;
/**
* 埋点模式
*/
private String trackMode;
/**
* 神策事件名称
*/
private String eventName;
/**
* 批量发送配置
*/
private BatchMode batch;
@Data
public static class BatchMode {
/**
* 快速批量发送模式"每次发送"条数阈值
*/
private Integer bulkSize;
/**
* 缓存队列最大条数
*/
private Integer maxCacheSize;
/**
* 超时时间(秒)
*/
private Integer timeoutSeconds;
}
}
Tracking Mode Enumeration
Supported tracking modes are defined in SensorsTrackModeEnums:
public enum SensorsTrackModeEnums implements EnumLookUp<String> {
DEBUG("debug", "测试上报"),
BATCH("batch", "批量模式"),
FAST_BATCH("fast_batch", "快速批量模式");
}
📝 Detailed Explanation of Configuration Parameters
Parameters | Type | Required | Description | Examples |
|---|---|---|---|---|
serverUrl | String | ✅ Yes | Sensors Data Server Addresses | https://api.example.com/sa?project=stage |
trackMode | String | ✅ Yes | Tracking Modes |
|
eventName | String | ❌ No | Default Event Names | d_h5_trilateral_credit_claim_click |
batch.bulkSize | Integer | ❌ No | Batch Send Count Threshold | 100 |
batch.maxCacheSize | Integer | ❌ No | Maximum Number of Entries in the Cache Queue | 10000 |
batch.timeoutSeconds | Integer | ❌ No | Timeout (seconds) | 30 |
🔧 Code Integration
Configuration Classes
Add SensorsConfig.java to your project:
/**
* @author 开发者
* @date 2025/11/11 15:55:00
*/
@Slf4j
@Configuration
public class SensorsConfig {
@Resource
private SensorsDataProperties sensorsDataProperties;
@Bean(destroyMethod = "shutdown")
public ISensorsAnalytics init() {
SensorsTrackModeEnums trackModeEnums =
EnumLookUp.getEnumInstance(SensorsTrackModeEnums.class, sensorsDataProperties.getTrackMode());
switch (trackModeEnums) {
case DEBUG:
// 注意:debug 模式数据不会写入服务器
// URL 会从 https://api.example.com/sa?project=stage
// 变为 https://api.example.com/debug?project=default
log.info("sensorsData debug mode");
return new SensorsAnalytics(new DebugConsumer(sensorsDataProperties.getServerUrl(), true));
case BATCH:
log.info("sensorsData batch mode");
return new SensorsAnalytics(new BatchConsumer(sensorsDataProperties.getServerUrl()));
}
log.info("sensorsData default mode [batch]");
return new SensorsAnalytics(new BatchConsumer(sensorsDataProperties.getServerUrl()));
}
}
Ensure that SensorsDataProperties and SensorsTrackModeEnums are included in the project’s classpath.
💻 Usage Examples
Basic Tracking Implementation
@Service
public class UserBehaviorService {
@Resource
private ISensorsAnalytics sensorsAnalytics;
@Resource
private SensorsDataProperties sensorsDataProperties;
/**
* 用户点击事件埋点
*/
public void trackUserClick(String userId, String creditApplyNo, String scene) {
Map<String, Object> properties = new HashMap<>();
properties.put("f_credit_apply_no", creditApplyNo);
properties.put("f_quotient_scene", scene);
properties.put("timestamp", System.currentTimeMillis());
// 发送埋点数据
sensorsAnalytics.track(userId, false, sensorsDataProperties.getEventName(), properties);
// 立即刷新(可选)
sensorsAnalytics.flush();
}
}
Business Scenario Examples
@Service
public class CreditApplyService {
@Resource
private ISensorsAnalytics sensorsAnalytics;
@Resource
private SensorsDataProperties sensorsDataProperties;
/**
* 授信申请成功埋点
*/
public void trackCreditApplySuccess(CreditApply creditApply, Partner partner) {
Map<String, Object> properties = new HashMap<>();
properties.put("f_credit_apply_no", creditApply.getSeqNo());
properties.put("f_quotient_scene", partner.getPartnerCode());
properties.put("f_credit_amount", creditApply.getCreditAmount());
properties.put("f_apply_time", creditApply.getCreateTime());
// 使用随机 UUID 作为匿名用户标识
String distinctId = UUID.randomUUID().toString();
sensorsAnalytics.track(distinctId, false, sensorsDataProperties.getEventName(), properties);
sensorsAnalytics.flush();
}
}
Test Code
@Test
public void testSensorsAnalytics() {
Map<String, Object> properties = new HashMap<>();
properties.put("f_credit_apply_no", "CA20251111000001");
properties.put("f_quotient_scene", "miniWallet");
properties.put("f_event_type", "click");
sensorsAnalytics.track(
UUID.randomUUID().toString(),
false,
"d_h5_trilateral_credit_claim_click",
properties
);
sensorsAnalytics.flush();
}
🔐 Configuration Examples
Development Environment Configuration
# application-dev.yml
sensorsdata:
server-url: https://api.example.com/sa?project=dev
track-mode: debug
event-name: d_h5_trilateral_credit_claim_click
batch:
bulk-size: 50
max-cache-size: 5000
timeout-seconds: 10
Test Environment Configuration
# application-test.yml
sensorsdata:
server-url: https://api.example.com/sa?project=stage
track-mode: batch
event-name: d_h5_trilateral_credit_claim_click
batch:
bulk-size: 100
max-cache-size: 10000
timeout-seconds: 30
Production Environment Configuration
# application-prod.yml
sensorsdata:
server-url: https://api.example.com/sa?project=production
track-mode: batch
event-name: d_h5_trilateral_credit_claim_click
batch:
bulk-size: 200
max-cache-size: 20000
timeout-seconds: 60
Nacos Configuration Center
If you are using the Nacos configuration center, you can add the following to the corresponding dataId:
# example-backend.yml
sensorsdata:
server-url: ${sensors.server.url:https://api.example.com/sa?project=stage}
track-mode: ${sensors.track.mode:batch}
event-name: ${sensors.event.name:d_h5_trilateral_credit_claim_click}
batch:
bulk-size: ${sensors.batch.bulk-size:100}
max-cache-size: ${sensors.batch.max-cache-size:10000}
timeout-seconds: ${sensors.batch.timeout-seconds:30}
⚠️ Important Notes
Important Notice
- Never use DEBUG mode in a production environment
- Data in DEBUG mode is not written to the server
- The server URL format is automatically modified
Normal Mode: https://api.example.com/sa?project=stage
DEBUG Mode: https://api.example.com/debug?project=default
- Some environments may not support project names in debug mode
- It is recommended to use a separate test project in the development environment
🚀 Performance Optimization
• In production environments, it is recommended to use the
batchmode• Set
bulkSizeappropriately• Set an appropriate
timeoutSeconds
- • It is recommended to execute event tracking asynchronously
- • Avoid impacting the main business workflow
- • Use a thread pool for management
- • Catch all exceptions
- • Log errors
- • Do not affect core business operations
Exception Handling Example:
try {
sensorsAnalytics.track(distinctId, isLoginId, eventName, properties);
sensorsAnalytics.flush();
} catch (Exception e) {
log.error("神策埋点失败", e);
// 不影响主业务流程
}
📊 Data Specifications
✓ Use the prefixes
f_to denote business fields- ✓ Use the underscore naming convention
✓ Examples:
f_credit_apply_no,f_quotient_scene
Type | Description | Examples |
|---|---|---|
String | User ID, Business ID, etc. | "CA20251111000001" |
Numeric Values | Amount, quantity, etc. | 10000 |
Timestamp | Using Millisecond-Level Timestamps | 1699689600000 |
distinctId- Unique user identifier
eventName- Event Name
properties- Event Properties
🔍 Troubleshooting
Frequently Asked Questions
❓ Q1: What should I do if the configuration isn't taking effect?
- Verify that the
@ConfigurationPropertiesannotation is correct - Verify the configuration file path and format
- Verify that the Nacos configuration has been pushed correctly
❓ Q2: Why can’t I see any data in DEBUG mode?
- Data in DEBUG mode is not written to the server
- Check the console log output
- Verify that the URL format is converted correctly
❓ Q3: Data Delay in Batch Mode?
- Check the
timeoutSecondsconfiguration - Manually call
flush()to send data immediately - Adjust the
bulkSizeparameter
📝 Log Debugging
Enabling Sensors Data SDK Logging:
logging:
level:
com.sensorsdata: DEBUG
com.example.backend.config.SensorsConfig: DEBUG
🏥 Health Check
@Component
public class SensorsHealthCheck {
@Resource
private ISensorsAnalytics sensorsAnalytics;
@PostConstruct
public void checkSensorsStatus() {
try {
// 发送测试事件
Map<String, Object> testProps = new HashMap<>();
testProps.put("test", "health_check");
sensorsAnalytics.track("health_check", false, "system_health_check", testProps);
log.info("神策数据分析初始化成功");
} catch (Exception e) {
log.error("神策数据分析初始化失败", e);
}
}
}
🎯 Best Practices
Code Organization
Unified Tracking Service:
properties) }
@Service
public class SensorsTrackingService {
@Resource
private ISensorsAnalytics sensorsAnalytics;
public void trackEvent(String userId, String eventName, Map<String, Object> properties) {
// 统一的埋点逻辑
}
}
Event Constant Management:
public class SensorsEventConstants {
public static final String CREDIT_APPLY_CLICK = "d_h5_trilateral_credit_claim_click";
public static final String USER_REGISTER = "d_user_register";
public static final String ORDER_CREATE = "d_order_create";
}
📊 Monitoring and Alerts
- 📈 Event Tracking Success Rate Monitoring
- ⏱️ Data Transmission Delay Monitoring
- 🚨 Anomaly Alerts
🗂️ Data Governance
📚 Appendix
List of Related Documents
📄
SensorsConfig.java- SensorsData configuration class📄
SensorsDataProperties.java- Configuration Properties Class📄
SensorsTrackModeEnums.java- Tracking Mode Enumerations