更改consul上服务注册名称,可以修改“
spring.cloud.consul.discovery.instance-id
”配置项实现但是不能获取到服务ip,此时可以在项目中实现这两个类即可按照 “服务名-ip-port” 进行注册
package com.awifi.capacity.analysis.push.config; import com.ecwid.consul.v1.ConsulClient; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cloud.consul.ConditionalOnConsulEnabled; 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; /** * @author fengxuechao * @version 0.1 * @date 2019/6/3 */ @Configuration @ConditionalOnConsulEnabled public class ConsulConfig { @Autowired(required = false) private TtlScheduler ttlScheduler; /** * 重写register方法 * * @param consulClient * @param properties * @param heartbeatProperties * @return */ @Bean public ServiceIdRegister consulServiceRegistry( ConsulClient consulClient, ConsulDiscoveryProperties properties, HeartbeatProperties heartbeatProperties) { return new ServiceIdRegister(consulClient, properties, ttlScheduler, heartbeatProperties); } }
package com.awifi.capacity.analysis.push.config; 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; /** * consul 服务id注册时根据规则命名。 * 更多参考:https://blog.csdn.net/ErickPang/article/details/84558228 * */ public class ServiceIdRegister extends ConsulServiceRegistry { public ServiceIdRegister(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); } }