@Slf4j
@Component
@Order(Integer.MIN_VALUE)
public class NacosRegisterServiceInit implements CommandLineRunner {
@Autowired
private NacosDiscoveryProperties nacosDiscoveryProperties;
@Autowired
private NacosServiceManager nacosServiceManager;
@Override
public void run(String... args) throws Exception {
//注册服务
registerInstance(nacosDiscoveryProperties,nacosServiceManager);
//服务下线
nacosShutdownHook(nacosDiscoveryProperties,nacosServiceManager);
}
/**
* 注册服务
*
* @param nacosProperties
* @param nacosServiceManager
*/
private void registerInstance(NacosDiscoveryProperties nacosProperties, NacosServiceManager nacosServiceManager) {
String serviceName = nacosProperties.getService();
String groupName = nacosProperties.getGroup();
String clusterName = nacosProperties.getClusterName();
String ip = nacosProperties.getIp();
int nacosPort = nacosProperties.getPort();
try {
nacosServiceManager.getNamingService().registerInstance(serviceName, groupName, ip, nacosPort, clusterName);
} catch (NacosException e) {
log.error("registerInstance from nacos error", e);
}
log.info("{} start, registerInstance.serviceName:{},groupName:{},ip:{},port:{},clusterName:{}", SpringUtil.getApplicationName(), serviceName, groupName, ip, nacosPort, clusterName);
}
/**
* 注册钩子函数,停机时从nacos下线
*
* @param nacosProperties
* @param nacosServiceManager
*/
private void nacosShutdownHook(NacosDiscoveryProperties nacosProperties, NacosServiceManager nacosServiceManager) {
RuntimeUtil.addShutdownHook(() -> {
String serviceName = nacosProperties.getService();
String groupName = nacosProperties.getGroup();
String clusterName = nacosProperties.getClusterName();
String ip = nacosProperties.getIp();
int nacosPort = nacosProperties.getPort();
try {
nacosServiceManager.getNamingService().deregisterInstance(serviceName, groupName, ip, nacosPort, clusterName);
} catch (NacosException e) {
log.error("deregister from nacos error", e);
}
log.info("{} stop, deregisterNacosInstance.serviceName:{},groupName:{},ip:{},port:{},clusterName:{}", SpringUtil.getApplicationName(), serviceName, groupName, ip, nacosPort, clusterName);
});
}
}
05-07
3449
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
07-29
830
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-01
2834
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)