Spring Boot中使用Consul,并解决集群中唯一ID命名问题

创建一个普通的springboot项目,Dependencies中选择Web->Spring Web Starter 以及 Spring Cloud Discovery->Consul Discovery,生成的pom.xml如下所示



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.1.6.RELEASE
         
    
    com.example
    demo
    0.0.1-SNAPSHOT
    demo
    Demo project for Spring Boot

    
        1.8
        Greenwich.SR1
    

    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.cloud
            spring-cloud-starter-consul-discovery
        

        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-actuator
        
    

    
        
            
                org.springframework.cloud
                spring-cloud-dependencies
                ${spring-cloud.version}
                pom
                import
            
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
            
        
    



在applicaiton.ml中添加如下配置

spring:
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        healthCheckPath: /health #健康检查路径
        healthCheckInterval: 15s #健康检查时间间隔
        instance-id: myconsul #唯一ID,在consul中不能重复
        enabled: true 
        service-name: datacenter-coreservice #服务名,同一服务名下可有多个节点
        tags: name=hr# 类似于注释,官网说是类似于元数据,我也不懂,不过可以自己解析成需要的数据
      enabled: true

创建一个Controller提供健康检查的接口

@RestController
public class ConsulController {
    @GetMapping("/health")
    public String health(){
        return "health";
    }
}

配置完以后启动项目就会向consul 服务器注册,不过要记得开启consul服务哦!

windows中consul的安装与本地启动
https://blog.csdn.net/j903829182/article/details/80960802

如果需要自己获取consul 服务器的信息,下面的博客有consul下的常用接口地址:

consul的各种接口地址:
https://blog.csdn.net/u010246789/article/details/51871051

如果需要搭建consul 集群,可参考以下博客:

linux 搭建consul集群:
https://blog.csdn.net/qq_25934401/article/details/82459486#commentBox
https://www.cnblogs.com/shanyou/p/6286207.html

解决集群中唯一ID命名问题

默认注册consul的服务id为服务名-端口号,相同的服务名和端口号注册会覆盖;

解决方式一:
添加随机数

 instance-id: myconsul${random.uuid} #缺点很明显,可读性差,而且在不同版本consul中,有的重启后不会自动删除之前的不存在的id

解决方式二:
代码中自定义ID,加上IP等信息则唯一

import com.ecwid.consul.v1.ConsulClient;
import com.ecwid.consul.v1.agent.model.NewService;
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.cloud.consul.serviceregistry.ConsulRegistration;
import org.springframework.cloud.consul.serviceregistry.ConsulServiceRegistry;

/**
 * 自定义consul注册id
 */
public class RpsConsulServiceRegistry extends ConsulServiceRegistry {
    private static ILog logger = LogManager.getLogger(RpsConsulServiceRegistry.class);
    @Autowired
    private CustomConfig customConfig;

    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());
        
       //在linux服务器上ip格式为10-20-33-258 这种格式,需要修改为10.20.33.258 
        if (!"DEV".equals(customConfig.getEnv())) {
            reg.getService().setAddress(reg.getHost().replace("-", "."));
        }
        //使用代码注册后,yml配置中的注册信息则会失效,需要自己添加健康检查等配置
        NewService.Check check = new NewService.Check();
        check.setHttp("http://" + reg.getHost() + ":" + reg.getPort() + "/health");
        check.setInterval("10s");
        check.setTimeout("1s");
        check.setMethod("GET");
        reg.getService().setCheck(check);
        super.register(reg);
    }
}

放入容器


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;

@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);
    }
}

解决方法参考博客
https://www.cnblogs.com/zhucww/p/10770327.html

你可能感兴趣的:(springboot)