nacos 配置中心ConfigService 和 注册中心NamingService
·
1.配置中心
DeployConfig.java
package com.example.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.nacos.config.DeployConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
public static void main(String[] args) throws Exception {
// nacos server地址
String serverAddr = "127.0.0.1:38848";
String namespace = "public";
String group = "DEFAULT_GROUP";
long timeoutMs = 3000;
// 配置中心例子
String dataId = "deploy";
// 注册中心例子
String serviceName = "portal";
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
// 连上注册中心
ConfigService configService = NacosFactory.createConfigService(properties);
// 连上配置中心
NamingService namingService = NamingFactory.createNamingService(properties);
AtomicReference<DeployConfig> currentConfig = new AtomicReference<>(null);
// 从配置中心取到数据
String bootstrap = configService.getConfig(dataId, group, timeoutMs);
if (hasText(bootstrap)) {
DeployConfig parsed = parseYaml(bootstrap);
currentConfig.set(parsed);
log.info("Initial config loaded: {}", parsed);
} else {
log.warn("No initial config found. dataId={}, group={}, namespace={}", dataId, group, namespace);
}
// 监听配置中心数据变更
configService.addListener(dataId, group, new AbstractListener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
try {
if (isDeleteEvent(configService, dataId, group, timeoutMs, configInfo)) {
DeployConfig old = currentConfig.getAndSet(null);
log.warn("Deploy config deleted in Nacos. oldValue={}", old);
onConfigDeleted(old);
return;
}
DeployConfig parsed = parseYaml(configInfo);
DeployConfig old = currentConfig.getAndSet(parsed);
log.info("Deploy config changed. oldValue={}, newValue={}", old, parsed);
} catch (Exception e) {
log.error("Failed to handle nacos config callback.", e);
}
}
});
// 监听注册中心变更
watchServiceInstances(namingService, serviceName, group);
// 钩子监听服务的改变
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
configService.shutDown();
} catch (NacosException e) {
log.error("Shutdown nacos configService failed.", e);
}
try {
namingService.shutDown();
} catch (NacosException e) {
log.error("Shutdown nacos namingService failed.", e);
}
}));
log.info(
"Listening nacos now. serverAddr={}, namespace={}, dataId={}, group={}, serviceName={}",
serverAddr,
namespace,
dataId,
group,
serviceName);
new CountDownLatch(1).await();
}
private static void watchServiceInstances(NamingService namingService, String serviceName, String group)
throws NacosException {
List<Instance> initial = namingService.selectInstances(serviceName, group, true);
logInstances("Initial service instances", serviceName, group, initial);
namingService.subscribe(serviceName, group, new EventListener() {
@Override
public void onEvent(Event event) {
if (!(event instanceof NamingEvent namingEvent)) {
return;
}
logInstances("Service instances changed", namingEvent.getServiceName(), group, namingEvent.getInstances());
}
});
}
private static void logInstances(String title, String serviceName, String group, List<Instance> instances) {
log.info("{} - serviceName={}, group={}, count={}", title, serviceName, group, instances.size());
// 打印出所有的元数据
for (Instance instance : instances) {
log.info(
"instance: ip={}, port={}, healthy={}, ephemeral={}, weight={}, metadata={}, serviceName={}",
instance.getIp(),
instance.getPort(),
instance.isHealthy(),
instance.isEphemeral(),
instance.getWeight(),
instance.getMetadata(),
instance.getServiceName());
}
}
private static boolean isDeleteEvent(
ConfigService configService, String dataId, String group, long timeoutMs, String callbackContent)
throws NacosException {
if (hasText(callbackContent)) {
return false;
}
String latest = configService.getConfig(dataId, group, timeoutMs);
return !hasText(latest);
}
private static DeployConfig parseYaml(String yaml) throws Exception {
return YAML_MAPPER.readValue(yaml, DeployConfig.class);
}
private static boolean hasText(String text) {
return text != null && !text.isBlank();
}
private static void onConfigDeleted(DeployConfig oldValue) {
log.warn("[DELETE EVENT] deploy config removed, old cache cleared. oldValue={}", oldValue);
}
}
2.代码
package com.example.nacos;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.example.nacos.config.DeployConfig;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger log = LoggerFactory.getLogger(Main.class);
private static final ObjectMapper YAML_MAPPER = new ObjectMapper(new YAMLFactory());
public static void main(String[] args) throws Exception {
// nacos server地址
String serverAddr = "127.0.0.1:38848";
String namespace = "public";
String group = "DEFAULT_GROUP";
long timeoutMs = 3000;
// 配置中心例子
String dataId = "deploy";
// 注册中心例子
String serviceName = "portal";
Properties properties = new Properties();
properties.setProperty(PropertyKeyConst.SERVER_ADDR, serverAddr);
// 注册中心
ConfigService configService = NacosFactory.createConfigService(properties);
// 配置中心
NamingService namingService = NamingFactory.createNamingService(properties);
AtomicReference<DeployConfig> currentConfig = new AtomicReference<>(null);
// 从配置中心取到数据
String bootstrap = configService.getConfig(dataId, group, timeoutMs);
if (hasText(bootstrap)) {
DeployConfig parsed = parseYaml(bootstrap);
currentConfig.set(parsed);
log.info("Initial config loaded: {}", parsed);
} else {
log.warn("No initial config found. dataId={}, group={}, namespace={}", dataId, group, namespace);
}
// 监听配置中心数据变更
configService.addListener(dataId, group, new AbstractListener() {
@Override
public Executor getExecutor() {
return null;
}
@Override
public void receiveConfigInfo(String configInfo) {
try {
if (isDeleteEvent(configService, dataId, group, timeoutMs, configInfo)) {
DeployConfig old = currentConfig.getAndSet(null);
log.warn("Deploy config deleted in Nacos. oldValue={}", old);
onConfigDeleted(old);
return;
}
DeployConfig parsed = parseYaml(configInfo);
DeployConfig old = currentConfig.getAndSet(parsed);
log.info("Deploy config changed. oldValue={}, newValue={}", old, parsed);
} catch (Exception e) {
log.error("Failed to handle nacos config callback.", e);
}
}
});
// 注册中心
watchServiceInstances(namingService, serviceName, group);
// 钩子监听服务的改变
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
try {
configService.shutDown();
} catch (NacosException e) {
log.error("Shutdown nacos configService failed.", e);
}
try {
namingService.shutDown();
} catch (NacosException e) {
log.error("Shutdown nacos namingService failed.", e);
}
}));
log.info(
"Listening nacos now. serverAddr={}, namespace={}, dataId={}, group={}, serviceName={}",
serverAddr,
namespace,
dataId,
group,
serviceName);
new CountDownLatch(1).await();
}
private static void watchServiceInstances(NamingService namingService, String serviceName, String group)
throws NacosException {
List<Instance> initial = namingService.selectInstances(serviceName, group, true);
logInstances("Initial service instances", serviceName, group, initial);
namingService.subscribe(serviceName, group, new EventListener() {
@Override
public void onEvent(Event event) {
if (!(event instanceof NamingEvent namingEvent)) {
return;
}
logInstances("Service instances changed", namingEvent.getServiceName(), group, namingEvent.getInstances());
}
});
}
private static void logInstances(String title, String serviceName, String group, List<Instance> instances) {
log.info("{} - serviceName={}, group={}, count={}", title, serviceName, group, instances.size());
// 打印出所有的元数据
for (Instance instance : instances) {
log.info(
"instance: ip={}, port={}, healthy={}, ephemeral={}, weight={}, metadata={}",
instance.getIp(),
instance.getPort(),
instance.isHealthy(),
instance.isEphemeral(),
instance.getWeight(),
instance.getMetadata());
}
}
private static boolean isDeleteEvent(
ConfigService configService, String dataId, String group, long timeoutMs, String callbackContent)
throws NacosException {
if (hasText(callbackContent)) {
return false;
}
String latest = configService.getConfig(dataId, group, timeoutMs);
return !hasText(latest);
}
private static DeployConfig parseYaml(String yaml) throws Exception {
return YAML_MAPPER.readValue(yaml, DeployConfig.class);
}
private static boolean hasText(String text) {
return text != null && !text.isBlank();
}
private static void onConfigDeleted(DeployConfig oldValue) {
log.warn("[DELETE EVENT] deploy config removed, old cache cleared. oldValue={}", oldValue);
}
}
更多推荐


所有评论(0)