监听事件
在spring-cloud-starter-alibaba-nacos-discovery中并未找到获取服务注册时进行会发布的事件,直接监听InstancesChangeEvent事件的发布,服务的上下线都会触发该事件
package com.rycem.gateway.notifier;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.event.InstancesChangeEvent;
import com.alibaba.nacos.common.notify.Event;
import com.alibaba.nacos.common.notify.NotifyCenter;
import com.alibaba.nacos.common.notify.listener.Subscriber;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.rycem.gateway.notifier.api.FeiShuRobotApi;
import com.rycem.gateway.notifier.entity.FeiShuResponse;
import com.rycem.gateway.notifier.entity.NacosInstanceOnDownLineRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.List;
@Component
public class NacosServiceInstanceChangeNotifier extends Subscriber<InstancesChangeEvent> {
@Autowired
private FeiShuRobotApi feiShuRobotApi;
@Value("${env.test}")
private Boolean test;
@PostConstruct
public void registerToNotifyCenter() {
NotifyCenter.registerSubscriber(this);
}
private boolean isWinOs() {
String os = System.getProperty("os.name").toLowerCase();
return os.contains("windows 10");
}
@Override
public void onEvent(InstancesChangeEvent instancesChangeEvent) {
String serviceName = instancesChangeEvent.getServiceName();
List<Instance> hosts = instancesChangeEvent.getHosts();
int envCode;
if (isWinOs()) {
return;
} else if (test) {
envCode = 1;
} else {
envCode = 2;
}
boolean online = hosts != null && !hosts.isEmpty();
String json = NacosInstanceOnDownLineRequest.json(online, envCode, serviceName);
try {
FeiShuResponse post = feiShuRobotApi.post(json);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
}
@Override
public Class<? extends Event> subscribeType() {
return InstancesChangeEvent.class;
}
}
评论区