Netty 注册到 nacos (注册中心)、zookeeper等
简单描述:应该叫 Java 应用程序 注册到Nacos。因为是基于现有项目架构(使用了Netty)所以叫Netty 注册到 nacos
注册nacos
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
也可以使用
<dependency>
<groupId>com.alibaba.nacos</groupId>
<artifactId>nacos-client</artifactId>
<version>1.1.4</version>
</dependency>
看过nacos源码的朋友,注册很简单,2行代码。
在 nacos-api NamingService 中存在。
举其中一种
/**
* Register a instance to service
*
* @param serviceName name of service
* @param ip instance ip
* @param port instance port
* @throws NacosException
*/
void registerInstance(String serviceName, String ip, int port) throws NacosException;
需要 一个名称,IP,端口
具体实现:
public void init() {
try {
//获取nacos服务
NamingService namingService = NamingFactory.createNamingService("127.0.0.1:8848");
//将服务注册到注册中心
namingService.registerInstance("springboot-netty", "127.0.0.1", Integer.valueOf("8848"));
} catch (NacosException e) {
log.error("注册nacos失败", e);
}
}
现在是硬编码:也可使用注解加载 IP, 端口,spring.application.name
自动注册
1、SpringbootNettyApplication 实现 CommandLineRunner 函数接口,在 run(String... args) 中加载 init()就OK了
2、SpringCloud一样通过注解注册,自己实现就可以了
3、如果使用的Spring Boot 2.x 可以使用 ApplicationStartedEventListener 获取 spring.application.name 等,完成自动注册。
代码:
@Slf4j
@Component
public class ApplicationStartedEventListener implements ApplicationListener<ApplicationStartedEvent> {
String name = applicationStartedEvent.getApplicationContext().getEnvironment().getProperty("spring.application.name");
}
再次说明:整个项目 已经抛弃了 spring-boot-starter-web
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
注册 zookeeper
具体实现一样,init() 方法中 改成 zookeeper的注册方式就可以了,这里不再阐述。