服务注册中心

Consul

2019-08-10  本文已影响0人  谁家的猪

Consul学习

Consul是什么

Consul是一个服务管理软件。支持多数据中心下,分布式高可用的,服务发现和配置共享。采用 Raft 算法,用来保证服务的高可用。

安装Consul服务端

Consul和Eureka不同,Eureka只需要在项目中加入服务端依赖,就可以作为服务端使用;Consul需要从官网下载,并单独安装。

  1. 官网下载地址:https://www.consul.io/downloads.html

  2. 上传到服务器

  3. unzip consul_1.5.3_linux_amd64.zip

  4. ./consul -v 查看版本

启动Consul服务端

开发模式启动单节点

  1. ./consul agent -dev -ui -client 0.0.0.0 启动命令,添加红色部分才能被外网访问,并有web页面

  2. http://192.168.78.131:8500打开管理页面

  3. curl 192.168.78.131:8500/v1/catalog/nodes查看consul节点

集群模式启动

  1. 创建4台虚拟机
  2. 启动集群,三个service和一个client
    2.1 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c1 -ui -client 0.0.0.0 -bind 192.168.1.109 -join 192.168.1.149
    2.2 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c2 -ui -client 0.0.0.0 -bind 192.168.1.151 -join 192.168.1.149
    2.3 ./consul agent -server -bootstrap-expect 3 -data-dir /tmp/consul -node=c3 -ui -client 0.0.0.0 -bind 192.168.1.152 -join 192.168.1.149
    2.4 ./consul agent -data-dir /tmp/consul -node=c4 -ui -client 0.0.0.0 -bind 192.168.1.116 -join 192.168.1.149
  3. 查看集群成员 ./consul members


    image.png
  4. 查看成员角色:./consul operator raft list-peers


    image.png

tips: 各参数含义

  1. agent:Consul的核心命令,主要作用有维护成员信息、运行状态检测、声明服务以及处理请求等
  2. -server:就是代表server模式
  3. -ui:代表开启web 控制台
  4. -bootstrap-expect:代表想要创建的集群数目,官方建议3或者5
  5. -data-dir:数据存储目录
  6. -node:代表当前node的名称
  7. -client:应该是一个客户端服务注册的地址,可以和当前server的一致也可以是其他主机地址,系统默认是127.0.0.1
  8. -bind:集群通讯地址
  9. -join:加入的集群地址

服务注册

通过HTTP API注册服务

  1. 注册一个ID为“test001”,name为“test”的服务:curl -X PUT -d '{"id": "test001","name": "test","address": "127.0.0.1","port": 8080,"tags": ["dev"]}' http://192.168.78.131:8500/v1/agent/service/register

  2. 查看服务是否注册成功
    2.1 curl http://192.168.78.131:8500/v1/catalog/service/test 查看服务信息
    2.2 curl http://192.168.78.131:8500/v1/health/service/test?passing 健康检查
    2.3 http://192.168.78.131:8500打开管理页面查看已注册的服务

通过项目注册服务

  1. 添加依赖
<dependency>

     <groupId>org.springframework.cloud</groupId>

     <artifactId>spring-cloud-starter-consul-discovery</artifactId>

</dependency>

<dependency>

     <groupId>org.springframework.boot</groupId>

     <artifactId>spring-boot-actuator-autoconfigure</artifactId>

</dependency>
  1. 配置文件
spring:
 application:
  name: consul-client
 cloud:
  consul:
   host: 192.168.78.131
   port: 8500
   discovery:
    register: true
    service-name: ${spring.application.name}
    tags: dev
    health-check-path: /actuator/health
    ip-address: 192.168.1.107
    prefer-ip-address: true
management:
 endpoints:
  web:
   exposure:
    include: "*"
  1. 启动项目

  2. http://192.168.78.131:8500打开管理页面查看已注册的服务

    image.png
  3. 防火墙需要关闭,否则service check访问不通。

  4. ip-address: 192.168.1.107 一定要有,为本机地址,否则找不到本机

  5. prefer-ip-address: true 一定要开启

参考文档

官方文档:https://www.consul.io/docs/index.html

上一篇下一篇

猜你喜欢

热点阅读