Vesta发号器源码解析——DbMachineIdProvider
数据库持有machineId的模式
相关字段和构造方法
//日志记录
private static final Logger log = LoggerFactory
.getLogger(DbMachineIdProvider.class);
//machineId的记录
private long machineId;
//jdbcTemplate
private JdbcTemplate jdbcTemplate;
//构造方法记录日志
public DbMachineIdProvider() {
//这个地方源代码中错了,应修改
//原始:
//log.debug("IpConfigurableMachineIdProvider constructed.");
//改为:
log.debug("DbMachineIdProvider constructed.");
}
初始化方法
public void init() {
//利用工具类读取主机IP
String ip = IpUtils.getHostIp();
//判断是否正确读取了IP,如果失败了,停止初始化,抛出异常
if (StringUtils.isEmpty(ip)) {
String msg = "Fail to get host IP address. Stop to initialize the DbMachineIdProvider provider.";
log.error(msg);
throw new IllegalStateException(msg);
}
//查询数据库
Long id = null;
try {
id = jdbcTemplate.queryForObject(
"select ID from DB_MACHINE_ID_PROVIDER where IP = ?",
new Object[]{ip}, Long.class);
} catch (EmptyResultDataAccessException e) {
// 记录日志忽略这个异常
log.error("No allocation before for ip {}.", ip);
}
//id查找成功,赋值后初始化完成,返回
if (id != null) {
machineId = id;
return;
}
//记录日志,失败,没能获取到ip对应的id
log.info(
"Fail to get ID from DB for host IP address {}. Next step try to allocate one.",
ip);
//分配一个id
int count = jdbcTemplate
.update("update DB_MACHINE_ID_PROVIDER set IP = ? where IP is null limit 1",
ip);
//如果更新条数大于1或者小于等于0,说明出现不合法状态,记录日志后抛异常失败,返回
if (count <= 0 || count > 1) {
String msg = String
.format("Fail to allocte ID for host IP address {}. The {} records are updated. Stop to initialize the DbMachineIdProvider provider.",
ip, count);
log.error(msg);
throw new IllegalStateException(msg);
}
//重新查询一次
try {
id = jdbcTemplate.queryForObject(
"select ID from DB_MACHINE_ID_PROVIDER where IP = ?",
new Object[]{ip}, Long.class);
} catch (EmptyResultDataAccessException e) {
//忽略异常
log.error("Fail to do allocation for ip {}.", ip);
}
//仍然没有找到,抛出异常记录日之后结束初始化
if (id == null) {
String msg = String
.format("Fail to get ID from DB for host IP address {} after allocation. Stop to initialize the DbMachineIdProvider provider.",
ip);
log.error(msg);
throw new IllegalStateException(msg);
}
//赋值,初始化完成
machineId = id;
}
字段的getter和setter
public long getMachineId() {
return machineId;
}
public void setMachineId(long machineId) {
this.machineId = machineId;
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;