Spring Cloud之微服务注册中心Consul

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第13天,点击查看活动详情

一、Consul

Consul概述

Consul是HashiCorp公司推出的开源产品,用于实现分布式系统的服务发现、服务隔离、服务配置,这些功能中的每一个都可以根据需要单独使用,也可以同时使用所有功能。

与其它分布式服务注册与发现的方案相比,Consul的方案更“一站式”——内置了服务注册与发现框架、分布一致性协议实现、健康检查、Key/Value 存储、多数据中心方案,不再需要依赖其它工具。

安装及使用Consul

下载https://www.consul.io/downloads

解压consul压缩包,并进入consul所在目录
在这里插入图片描述
cmd下执行如下命令:

1.开发者模式,数据存放内存中

consul agent -dev
复制代码

2.服务模式,可以保留操作数据

consul agent -server -ui -bootstrap -data-dir D:\Development\consul\data -node=node1 -bind=127.0.0.1
复制代码
agent: 启动Agent进程

server:启动server模式

bootstrap:节点是server-Leader ,每个数据中心只能运行一台服务器

ui:启动Web UI管理器,默认开放端口8500

node:节点的名称,集群中必须是唯一的,默认是该节点的主机名

data-dir: 数据存放路径

bind:consul服务侦听地址
复制代码
D:\Development\consul>consul agent -server -ui -bootstrap -data-dir D:\Development\consul\data -node=node1 -bind=127.0.0.1
==> Starting Consul agent...
           Version: '1.10.3'
           Node ID: '0907bff1-3c02-59a5-dd91-1af0b8544984'
         Node name: 'node1'
        Datacenter: 'dc1' (Segment: '<all>')
            Server: true (Bootstrap: true)
       Client Addr: [127.0.0.1] (HTTP: 8500, HTTPS: -1, gRPC: -1, DNS: 8600)
      Cluster Addr: 127.0.0.1 (LAN: 8301, WAN: 8302)
           Encrypt: Gossip: false, TLS-Outgoing: false, TLS-Incoming: false, Auto-Encrypt-TLS: false

==> Log data will now stream in as it occurs:

T13:58:06.545+0800 [WARN]  agent: BootstrapExpect is set to 1; this is the same as Bootstrap mode.
T13:58:06.593+0800 [WARN]  agent: bootstrap = true: do not enable unless necessary
T13:58:07.007+0800 [WARN]  agent.auto_config: BootstrapExpect is set to 1; this is the same as Bootstrap mode.
T13:58:07.007+0800 [WARN]  agent.auto_config: bootstrap = true: do not enable unless necessary
T13:58:07.035+0800 [INFO]  agent.server.raft: initial configuration: index=1 servers="[{Suffrage:Voter ID:0907bff1-3c02-59a5-dd91-1af0b8544984 Address:127.0.0.1:8300}]"
T13:58:07.035+0800 [INFO]  agent.server.raft: entering follower state: follower="Node at 127.0.0.1:8300 [Follower]" leader=
T13:58:07.040+0800 [INFO]  agent.server.serf.wan: serf: EventMemberJoin: node1.dc1 127.0.0.1
T13:58:07.043+0800 [INFO]  agent.server.serf.lan: serf: EventMemberJoin: node1 127.0.0.1
T13:58:07.043+0800 [INFO]  agent.router: Initializing LAN area manager
T13:58:07.044+0800 [INFO]  agent.server: Adding LAN server: server="node1 (Addr: tcp/127.0.0.1:8300) (DC: dc1)"
T13:58:07.044+0800 [WARN]  agent: grpc: addrConn.createTransport failed to connect to {dc1-127.0.0.1:8300 0 node1 <nil>}. Err :connection error: desc = "transport: Error while dialing dial tcp 127.0.0.1:0->127.0.0.1:8300: operation was canceled". Reconnecting...
T13:58:07.044+0800 [INFO]  agent.server: Handled event for server in area: event=member-join server=node1.dc1 area=wan
T13:58:07.044+0800 [WARN]  agent: grpc: addrConn.createTransport failed to connect to {dc1-127.0.0.1:8300 0 node1.dc1 <nil>}. Err :connection error: desc = "transport: Error while dialing dial tcp 127.0.0.1:0->127.0.0.1:8300: operation was canceled". Reconnecting...
T13:58:07.046+0800 [INFO]  agent: Started DNS server: address=127.0.0.1:8600 network=udp
T13:58:07.046+0800 [INFO]  agent: Started DNS server: address=127.0.0.1:8600 network=tcp
T13:58:07.049+0800 [INFO]  agent: Starting server: address=127.0.0.1:8500 network=tcp protocol=http
T13:58:07.050+0800 [WARN]  agent: DEPRECATED Backwards compatibility with pre-1.9 metrics enabled. These metrics will be removed in a future version of Consul. Set `telemetry { disable_compat_1.9 = true }` to disable them.
T13:58:07.050+0800 [INFO]  agent: started state syncer
T13:58:07.050+0800 [INFO]  agent: Consul agent running!
复制代码

浏览器访问: http://localhost:8500
在这里插入图片描述

二、SpringCloud集成Consul

A、服务生产者

添加依赖

		<!--健康检查依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
复制代码

配置application.properties

server.port=8888
spring.application.name=consul-test
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name}
复制代码

提供服务

@RestController
public class TestController {

    @GetMapping("/test")
    public String test() {
        return "test success";
    }
}
复制代码

启动测试

启动Application,查看Consul的UI控制台界面
在这里插入图片描述
设置JVM参数:-DSERVER.PORT=9999,再启动一个实例

在这里插入图片描述

B、消费服务者

集成Feign:创建FeignClient项目,用于调用服务

添加依赖坐标

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR8</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
复制代码

创建调用接口

创建ConsulFeignClientTest接口

//指定调用的服务名称
@FeignClient("consul-test")
public interface ConsulFeignClientTest {

	@GetMapping("/test")
    public String test();
}
复制代码

配置application.properties

server.port=7777
spring.application.name=fegin
spring.cloud.consul.host=127.0.0.1
spring.cloud.consul.port=8500
spring.cloud.consul.discovery.service-name=${spring.application.name}
spring.cloud.consul.discovery.register=false #不需要注册到consul,只需要去发现服务然后进行调用即可
复制代码

开启FeignClient

启动类添加@EnableFeignClients注解

@SpringBootApplication
@EnableFeignClients
public class FeignAppliction {
	public static void main(String[] args) {
		SpringApplication.run(FeignAppliction.class,args);
	}
}
复制代码

测试

    @Autowired
    private ConsulFeignClientTest consulFeignClientTest;

    @Test
    public void test(){
        String test = consulFeignClientTest.test();
        System.out.println(test);
    }
复制代码

三、Consul配置中心支持

Consul不仅能用来服务注册和发现,还支持Key/Value键值对的存储,可以用来做配置中心,并且支持动态刷新,这样可以将工程中的配置信息保存在Cosul中。

添加依赖

 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>
复制代码

配置bootstrap.yml

新建配置文件bootstrap.yml ,bootstrap.yml优先application.yml加载

spring:
  application:
    name: consul
  profiles:
    active: dev
  cloud:
    consul:
      host: 127.0.0.1
      port: 8500
      discovery:
        serviceName: ${spring.application.name}
      # 以下consul的config对应key值为:config/consul,dev/data
      config:
        enabled: true # 设置config是否启用,默认为true,从consul配置中心读取配置
        format: yaml # 设置配置的值的格式,可以yaml和properties
        prefix: config # 设置配的基本目录,如config,即key的前缀
        defaultContext: consul # 设置默认的配置,被所有的应用读取,一般为应用名称
        data-key: data
复制代码

添加配置到Consul

将原来application.yml配置文件改名为application-dev.yml,并将该文件中的配置注释复制保存到
Consul中

key值为:config/consul,dev/data

内容为: application-dev.yml中的配置内容
复制代码

在这里插入图片描述

注意: consul支持的K/V存储的Value值不能超过512KB

consul动态刷新

consul config作为配置中心时,是支持动态刷新的,动态刷新即当配置中心的配置发生改变,应用配置服务端能够动态及时的更新配置数据信息

@RestController
public class TestController {

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

    @GetMapping("/test")
    public String test() {
        return consul;
    }
}
复制代码

在这里插入图片描述
在consul配置中心修改consul项的值

consul: 0.0.5
复制代码
  INFO 54344 --- [TaskScheduler-1] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
  INFO 54344 --- [TaskScheduler-1] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
  INFO 54344 --- [TaskScheduler-1] o.s.cloud.commons.util.InetUtils         : Cannot determine local hostname
  INFO 54344 --- [TaskScheduler-1] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
  INFO 54344 --- [TaskScheduler-1] b.c.PropertySourceBootstrapConfiguration : Located property source: [BootstrapPropertySource {name='bootstrapProperties-config/consul,dev/'}, BootstrapPropertySource {name='bootstrapProperties-config/consul/'}]
  INFO 54344 --- [TaskScheduler-1] o.s.boot.SpringApplication               : The following profiles are active: dev
  INFO 54344 --- [TaskScheduler-1] o.s.boot.SpringApplication               : Started application in 4.541 seconds (JVM running for 417.332)
  INFO 54344 --- [TaskScheduler-1] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [consul]
复制代码

在这里插入图片描述

四、Consul配置参数概览

spring.application.name=consul-config
# 指定consul的地址
spring.cloud.consul.host = 127.0.0.1
# 指定consul的端口,默认8500
spring.cloud.consul.port = 8500

#指定服务的实例id(唯一)
spring.cloud.consul.discovery.instance-id=${spring.application.name}
# 指定consul服务的名称
spring.cloud.consul.discovery.service-name=consul-config
# 是否启用服务发现
spring.cloud.consul.discovery.enabled=true
# 是否启用服务注册
spring.cloud.consul.discovery.register=true
# 是否服务停止时取消注册
spring.cloud.consul.discovery.deregister=true
# 在注册时使用consul IP,而不是hostname
spring.cloud.consul.discovery.prefer-ip-address=true

# 健康检查url
spring.cloud.consul.discovery.health-check-url=http://localhost:8081/actuator/health
# 健康检查的频率, 默认 10 秒
spring.cloud.consul.discovery.health-check-interval=10s
# 健康检查失败多长时间后,取消注册
spring.cloud.consul.discovery.health-check-critical-timeout=5s

# 启用配置中心
spring.cloud.consul.config.enabled=true
# 表示consul上面文件的格式 有四种 YAML PROPERTIES KEY-VALUE FILES
spring.cloud.consul.config.format=properties
#表示consul上面的KEY值(或者说文件的名字) 默认是data
spring.cloud.consul.config.data-key=data
#prefix设置配置值的基本文件夹
spring.cloud.consul.config.prefix=config
# 表示如果没有发现配置,是否抛出异常,true为是,false为否,当为false时,consul会打印warn级别的日志信息
spring.cloud.consul.config.fail-fast=false
#defaultContext设置所有应用程序使用的文件夹名称,指定consul配置的配置文件父路径
spring.cloud.consul.config.defaultContext=consul-config
#profileSeparator设置用于使用配置文件在属性源中分隔配置文件名称的分隔符的值
spring.cloud.consul.config.profileSeparator=,
复制代码

猜你喜欢

转载自juejin.im/post/7129338704618864670