com.alibaba.cloud.ans.registry2.AnsAutoServiceRegistration Maven / Gradle / Ivy
package com.alibaba.cloud.ans.registry2;
import com.alibaba.cloud.ans.registry.AnsRegistration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.cloud.client.discovery.event.InstanceRegisteredEvent;
import org.springframework.cloud.client.serviceregistry.AutoServiceRegistration;
import org.springframework.cloud.client.serviceregistry.ServiceRegistry;
import org.springframework.context.ApplicationContext;
import org.springframework.context.SmartLifecycle;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.core.Ordered;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
/**
*
* @author yizhan
* @date 2018/5/7
*/
public class AnsAutoServiceRegistration implements AutoServiceRegistration, SmartLifecycle, Ordered {
private static final Logger logger = LoggerFactory.getLogger(AnsAutoServiceRegistration.class);
@Autowired
private AnsRegistration registration;
private int order = 0;
private AtomicBoolean running = new AtomicBoolean(false);
private AtomicInteger port = new AtomicInteger(0);
private ApplicationContext context;
private ServiceRegistry serviceRegistry;
public AnsAutoServiceRegistration(ApplicationContext context, ServiceRegistry serviceRegistry, AnsRegistration registration) {
this.context = context;
this.serviceRegistry = serviceRegistry;
this.registration = registration;
}
@Override
public void start() {
if(this.port.get() != 0) {
this.registration.setPort(port.get());
}
if(!this.running.get() && this.registration.getPort() > 0) {
this.serviceRegistry.register(this.registration);
this.context.publishEvent(new InstanceRegisteredEvent(this, this.registration));
this.running.set(true);
}
}
@Override
public void stop(){
this.serviceRegistry.deregister(this.registration);
this.running.set(false);
}
@Override
public boolean isRunning() {
return this.running.get();
}
@Override
public int getPhase() {
return 0;
}
@Override
public boolean isAutoStartup() {
return true;
}
@Override
public void stop(Runnable callback) {
this.stop();
callback.run();
}
@Override
public int getOrder() {
return this.order;
}
@EventListener(ServletWebServerInitializedEvent.class)
public void onApplicationEvent(ServletWebServerInitializedEvent event) {
int localPort = event.getWebServer().getPort();
if (this.port.get() == 0) {
logger.info("Updating port to {}", localPort);
this.port.compareAndSet(0, localPort);
start();
}
}
@EventListener({ContextClosedEvent.class})
public void onApplicationEvent(ContextClosedEvent event) {
if(event.getApplicationContext() == this.context) {
this.stop();
}
}
}