1.服务端
1.服务注册
js复制代码@Configuration
public class NettyServerStart {
@Autowired
private ServiceRegistrationScan registrationScan;
@Autowired
private NettyServer nettyServer;
@PostConstruct
public void start() {
//服务注册
registrationScan.scan();
//服务器启动
nettyServer.start();
}
}
@PostConstruct注解的作用是在依赖注入完成后,执行被注解的方法。
深入ServiceRegistrationScan
java复制代码@Component
public class ServiceRegistrationScan implements ApplicationContextAware {
@Autowired
private ServerZKit serverZKit;
@Autowired
private RpcServerConfiguration rpcServerConfiguration;
//把spring容器注入进来因为会用到它去拿我们需要暴露服务的类
private static ApplicationContext context;
public void scan() {
//创建一个根节点
serverZKit.createRootNode();
//拿到所有实现这个接口的类
Map<String, Object> beansWithAnnotation = context.getBeansWithAnnotation(MoXiuRpcServer.class);
if (!beansWithAnnotation.isEmpty()) {
//拿到当前服务器的IP地址
String realIp = IpUtil.getRealIp();
for (Object value : beansWithAnnotation.values()) {
MoXiuRpcServer annotation = value.getClass().getAnnotation(MoXiuRpcServer.class);
//拿到类似于这样的 com.moxiu.xxx
Class aClass = annotation.interfaceName();
String s = aClass.getName();
//以这个接口创建一个结点
serverZKit.createPersistentNode(s);
String childName = s + "/" + realIp +":"+ rpcServerConfiguration.getRpcPort();
//创建本机IP