1. 程式人生 > 實用技巧 >【轉】consul 服務id註冊時根據規則命名

【轉】consul 服務id註冊時根據規則命名

原文連結:https://blog.csdn.net/ErickPang/article/details/84558228 更改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);
    }
}