前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >微服务注册中心:Consul——服务注册

微服务注册中心:Consul——服务注册

作者头像
程序员架构进阶
发布2021-07-05 19:02:29
2.2K0
发布2021-07-05 19:02:29
举报
文章被收录于专栏:架构进阶架构进阶

系列文章:

微服务架构:网关概念与 zuul

微服务网关:Spring Cloud Gateway —— Zuul

微服务网关:Spring Cloud Config- 配置中心

微服务网关方案:Kong & Nacos

Nacos 实践

微服务网关:Nacos 源码实践(二)

微服务注册中心:Consul——概念与基础操作

一 简介

微服务注册中心:Consul——概念与基础操作介绍了 consul 的安装和基本操作,本篇开始在 consul 上进行服务注册与发现,语言使用 Java,框架使用 Spring Boot 整合 Consul。

二 Spring Boot 整合 Consul

通常 demo 比较好找,导入后观察需要引入哪些依赖,然后启动。最多微调版本和配置问题即可。

2.1 网上 demo

打脸来的如此迅速,百度上搜了一堆,最后发现都是官方文档的翻译,版本不清,代码不全,尝试几个未果。再次感叹现在很多文章的质量。

2.2 官方文档

不得已还是先尝试查看官方文档,Spring Cloud Consul是基于 3.0.2 版本,给出的集成 demo。不过很遗憾,官方给出的 sample 地址,访问一直是 404 状态。

上面 Consul Sample 的查看结果:

2.3 spring-cloud 的 github

考虑下一种渠道,寻找官方github。官方的 pom.xml 配置建议如下:

代码语言:javascript
复制
<project>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>{spring-boot-version}</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-consul-discovery</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
  </dependencies>
  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>
  <build>
    <plugins>
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
      </plugin>
    </plugins>
  </build>
</project>

事实上,springboot 的版本选择过程中也遇到不少问题,几个典型的错误如下(为了节省空间,只截取了关键错误信息):

2.3.1 启动报错信息 1

代码语言:javascript
复制
Description:

An attempt was made to call a method that does not exist. The attempt was made from the following location:

    org.springframework.cloud.client.discovery.health.DiscoveryCompositeHealthIndicator.<init>(DiscoveryCompositeHealthIndicator.java:41)

The following method did not exist:

    org.springframework.boot.actuate.health.CompositeHealthIndicator.<init>(Lorg/springframework/boot/actuate/health/HealthAggregator;)V

The method's class, org.springframework.boot.actuate.health.CompositeHealthIndicator, is available from the following locations:

    jar:file:/Users/lijingyong/.m2/repository/org/springframework/boot/spring-boot-actuator/2.2.6.RELEASE/spring-boot-actuator-2.2.6.RELEASE.jar!/org/springframework/boot/actuate/health/CompositeHealthIndicator.class

It was loaded from the following location:

    file:/Users/lijingyong/.m2/repository/org/springframework/boot/spring-boot-actuator/2.2.6.RELEASE/spring-boot-actuator-2.2.6.RELEASE.jar


Action:

Correct the classpath of your application so that it contains a single, compatible version of org.springframework.boot.actuate.health.CompositeHealthIndicator


Process finished with exit code 1

2.3.2 报错 2

代码语言:javascript
复制
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration]: Factory method 'consulRegistration' threw exception; nested exception is java.lang.IllegalArgumentException: Consul service ids must not be empty, must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen: null
  at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
  at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:651) ~[spring-beans-5.2.5.RELEASE.jar:5.2.5.RELEASE]
  ... 96 common frames omitted
Caused by: java.lang.IllegalArgumentException: Consul service ids must not be empty, must start with a letter, end with a letter or digit, and have as interior characters only letters, digits, and hyphen: null
  at org.springframework.cloud.consul.serviceregistry.ConsulAutoRegistration.normalizeForDns(ConsulAutoRegistration.java:178) ~[spring-cloud-consul-discovery-2.2.1.RELEASE.jar:2.2.1.RELEASE]

2.4 一个可用 demo

根据官方说明,并参考另一个 demo:https://github.com/RobbieXie/springboot-consul 后,整理如下,不过是使用的较旧版本 springboot,可以根据需要更新到适合的版本信息。

关键配置和代码:

2.4.1 pom.xml

代码语言:javascript
复制
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>springboot-consul</artifactId>
    <description>Spring Boot整合consul示例</description>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>com.orbitz.consul</groupId>
            <artifactId>consul-client</artifactId>
            <version>1.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.ecwid.consul</groupId>
            <artifactId>consul-api</artifactId>
            <version>1.3.0</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>bintray</name>
            <url>http://jcenter.bintray.com</url>
        </repository>
    </repositories>
</project>

2.4.2 应用启动类 SpringBootConsulApplication

代码语言:javascript
复制
package com.flamingskys.learn.springboot.consul;

import com.flamingskys.learn.springboot.consul.service.ConsulService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import javax.annotation.PreDestroy;

@SpringBootApplication
@EnableAutoConfiguration
public class SpringBootConsulApplication {

    @Value("${consul.instanceId}")
    private String instanceId;

    @Bean
    public String getInstanceId(){
        return instanceId;
    }

    @Autowired
    private ConsulService consulService;

    public static void main(String[] args) {
        SpringApplication.run(SpringBootConsulApplication.class, args);
    }

    @PreDestroy
    public void beforeExit(){
        System.out.println("-----------------------------BEFORE  EXIT--------------------------------");
        consulService.deregisterService(instanceId);
    }
}

2.4.3 资源配置 application.properties

代码语言:javascript
复制

spring.application.name=first-consul-client

consul.host=127.0.0.1
consul.port=8500
consul.instanceId=${spring.application.name}:${spring.application.instanceid:${random.value}}

spring.cloud.consul.discovery.heartbeat.enabled=true
应用启动后,查看 console 上注册的服务列表,first-consul-client 就是我们的服务:

完整代码已上传到了gitee。可关注公众号:

随时获取更新。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2021-05-27,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 程序员架构进阶 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一 简介
  • 二 Spring Boot 整合 Consul
    • 2.1 网上 demo
      • 2.2 官方文档
        • 2.3 spring-cloud 的 github
          • 2.3.1 启动报错信息 1
          • 2.3.2 报错 2
          • 2.4.1 pom.xml
      相关产品与服务
      微服务引擎 TSE
      微服务引擎(Tencent Cloud Service Engine)提供开箱即用的云上全场景微服务解决方案。支持开源增强的云原生注册配置中心(Zookeeper、Nacos 和 Apollo),北极星网格(腾讯自研并开源的 PolarisMesh)、云原生 API 网关(Kong)以及微服务应用托管的弹性微服务平台。微服务引擎完全兼容开源版本的使用方式,在功能、可用性和可运维性等多个方面进行增强。
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档