默认注册consul的服务id为服务名-端口号,相同的服务名和端口号注册会覆盖
解决方式:
1.自定义Consul注册Id
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;
/**
* @describe: 自定义consul注册id
* @author: zhuCw
* @date: 2019/4/25 17:57
*/
public class RpsConsulServiceRegistry extends ConsulServiceRegistry {
public RpsConsulServiceRegistry(
ConsulClient client,
ConsulDiscoveryProperties properties,
TtlScheduler ttlScheduler,
HeartbeatProperties heartbeatProperties) {
super(client, properties, ttlScheduler, heartbeatProperties);
}
@Override
public void register(ConsulRegistration reg) {
// 重新设计id,此处用的是名字也可以用其他方式例如instanceid、host、uri等
reg.getService()
.setId(
reg.getService().getName() + "-" + reg.getService().getAddress() + "-" + reg.getPort());
super.register(reg);
}
}
2. 放入容器
import com.ecwid.consul.v1.ConsulClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.consul.discovery.ConsulDiscoveryProperties;
import org.springframework.cloud.consul.discovery.HeartbeatProperties;
import org.springframework.cloud.consul.discovery.TtlScheduler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @describe: TODO
* @author: zhuCw
* @date: 2019/4/25 17:57
*/
@Configuration
public class RpsConsulServiceRegistryConfig {
@Autowired(required = false)
private TtlScheduler ttlScheduler;
@Bean
public RpsConsulServiceRegistry consulServiceRegistry(
ConsulClient consulClient,
ConsulDiscoveryProperties properties,
HeartbeatProperties heartbeatProperties) {
return new RpsConsulServiceRegistry(
consulClient, properties, ttlScheduler, heartbeatProperties);
}
}