某项目中,需要在启动时在zk节点实例和父节点中写入元数据。
@Slf4j
@Configuration
public class ZkConfiguration implements ApplicationRunner {
@Value("${spring.application.name}")
private String applicationName;
@Bean
public ServiceInstanceRegistration serviceInstanceRegistration(
ApplicationContext context, ZookeeperDiscoveryProperties properties) {
String host = properties.getInstanceHost();
if (!StringUtils.hasText(host)) {
throw new IllegalStateException("instanceHost must not be empty");
}
properties.getMetadata().put(StatusConstants.INSTANCE_STATUS_KEY, properties.getInitialStatus());
properties.getMetadata().put("instanceInfo", "aa");
ZookeeperInstance zookeeperInstance = new ZookeeperInstance(context.getId(),
applicationName, properties.getMetadata());
ServiceInstanceRegistration.RegistrationBuilder builder = ServiceInstanceRegistration.builder().address(host)
.name(applicationName).payload(zookeeperInstance)
.uriSpec(properties.getUriSpec());
if (properties.getInstanceSslPort() != null) {
builder.sslPort(properties.getInstanceSslPort());
}
if (properties.getInstanceId() != null) {
builder.id(properties.getInstanceId());
}
return builder.build();
}
@Resource
CuratorFramework client;
@Override
public void run(ApplicationArguments args) throws Exception {
Map<String, String> serviceMetadata = new HashMap<>();
serviceMetadata.put("serviceInfo", "bb");
client.setData().forPath( "/root/" + applicationName, JSON.toJSONString(serviceMetadata).getBytes(StandardCharsets.UTF_8));
}
}