package com.xiaopeng.operation.config; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * 基于 Nacos 的 UID-VIN 绑定配置实现 *

* 通过 {@code @ConfigurationProperties} 绑定 Nacos 中 {@code uid-vin-binding} 前缀的配置, * 使用 {@code @RefreshScope} 实现配置变更时自动刷新。 *

* 配置格式示例: *

 * uid-vin-binding:
 *   enabled: true
 *   mappings:
 *     "uid_10001": "LXPXXXXXXXX00001"
 *     "uid_10002": "LXPXXXXXXXX00002"
 * 
*/ @Slf4j @ConfigurationProperties(prefix = "uid-vin-binding") public class NacosUidVinBindingConfig implements UidVinBindingConfig { /** * 功能总开关,默认 false */ private boolean enabled = false; /** * UID→VIN 映射关系(当前有效配置) */ private volatile Map mappings = new HashMap<>(); @Override public String getBoundVin(String uid) { if (uid == null) { log.info("[人车订单绑定测试] getBoundVin 入参uid为null,返回null"); return null; } String vin = mappings.get(uid); log.info("[人车订单绑定测试] getBoundVin 查询绑定关系, uid={}, 结果vin={}", uid, vin); return vin; } @Override public boolean hasBoundVin(String uid) { if (uid == null) { return false; } boolean has = mappings.containsKey(uid); log.info("[人车订单绑定测试] hasBoundVin 检查绑定, uid={}, 存在={}", uid, has); return has; } @Override public Map getAllBindings() { log.info("[人车订单绑定测试] getAllBindings 当前绑定数量={}, 内容={}", mappings.size(), mappings); return Collections.unmodifiableMap(mappings); } @Override public boolean isEnabled() { log.info("[人车订单绑定测试] isEnabled 总开关状态={}", enabled); return enabled; } // ===== Setter methods for @ConfigurationProperties binding ===== public void setEnabled(boolean enabled) { log.info("[人车订单绑定测试] setEnabled 开关变更: {} -> {}", this.enabled, enabled); this.enabled = enabled; } /** * 配置绑定的 setter,Spring 在配置刷新时调用。 *

* 记录配置变更日志(变更前后绑定数量), * 配置解析异常时保留上一次有效配置并记录 ERROR 日志。 * * @param newMappings 新的 UID→VIN 映射 */ public void setMappings(Map newMappings) { try { int oldSize = this.mappings.size(); if (newMappings == null) { newMappings = new HashMap<>(); } this.mappings = new HashMap<>(newMappings); int newSize = this.mappings.size(); log.info("[人车订单绑定测试] 配置已更新,绑定数量: {} -> {}, 当前映射内容: {}", oldSize, newSize, this.mappings); } catch (Exception e) { log.error("[人车订单绑定测试] 配置解析异常,保留上一次有效配置(绑定数量={})", this.mappings.size(), e); } } }