转载Spring Cloud Consul实现服务的注册和发现

第一篇:SpringCloud 构建微服务系统之服务注册和发现(consul) - kldx5092 - 博客园

1. consul 官网 (https://www.consul.io)

2. consul 简介
consul是google开源的一个使用go语言开发的服务发现、配置管理中心服务。内置了服务注册与发现框 架、分布一致性协议实现、健康检查、Key/Value存储、多数据中心方案,不再需要依赖其他工具(比如ZooKeeper等)。服务部署简单,只有一个可运行的二进制的包。每个节点都需要运行agent,他有两种运行模式server和client。每个数据中心官方建议需要3或5个server节点以保证数据安全,同时保证server-leader的选举能够正确的进行。

3.consul基本概念

  • client

CLIENT表示consul的client模式,就是客户端模式。是consul节点的一种模式,这种模式下,所有注册到当前节点的服务会被转发到SERVER,本身是不持久化这些信息。

  • server

SERVER表示consul的server模式,表明这个consul是个server,这种模式下,功能和CLIENT都一样,唯一不同的是,它会把所有的信息持久化的本地,这样遇到故障,信息是可以被保留的。

  • server-leader

中间那个SERVER下面有LEADER的字眼,表明这个SERVER是它们的老大,它和其它SERVER不一样的一点是,它需要负责同步注册的信息给其它的SERVER,同时也要负责各个节点的健康监测。

  • raft

server节点之间的数据一致性保证,一致性协议使用的是raft,而zookeeper用的paxos,etcd采用的也是taft。

  • 服务发现协议

consul采用http和dns协议,etcd只支持http

  • 服务注册

consul支持两种方式实现服务注册,一种是通过consul的服务注册http API,由服务自己调用API实现注册,另一种方式是通过json个是的配置文件实现注册,将需要注册的服务以json格式的配置文件给出。consul官方建议使用第二种方式。

  • 服务发现

consul支持两种方式实现服务发现,一种是通过http API来查询有哪些服务,另外一种是通过consul agent 自带的DNS(8600端口),域名是以NAME.service.consul的形式给出,NAME即在定义的服务配置文件中,服务的名称。DNS方式可以通过check的方式检查服务。

  • 服务间的通信协议

Consul使用gossip协议管理成员关系、广播消息到整个集群,他有两个gossip pool(LAN pool和WAN pool),LAN pool是同一个数据中心内部通信的,WAN pool是多个数据中心通信的,LAN pool有多个,WAN pool只有一个。

4.consul架构图


5.Consul常用命令
5.1 agent 运行一个consul agent
consul agent -dev

5.2 join 将agent加入到consul集群
consul join IP

5.3 members 列出consul cluster的members
consul members

5.4 leave 将节点移除所在集群
consul leave

6.consul安装和启动

点击“download”下载:使用命令启动

1

consul agent -dev

启动成功之后在地址:http://localhost:8500

7.consul服务的发现与注册
7.1 注册服务
使用HTTP API 注册个服务,使用[接口API](https://www.consul.io/api/agent/service.html API)调用

调用 http://localhost:8500/v1/agent/service/register PUT 注册一个服务。request body:

{
  "ID": "userServiceId", //服务id
  "Name": "userService", //服务名
  "Tags": [              //服务的tag,自定义,可以根据这个tag来区分同一个服务名的服务
    "primary",
    "v1"
  ],
  "Address": "127.0.0.1",//服务注册到consul的IP,服务发现,发现的就是这个IP
  "Port": 9000,          //服务注册consul的PORT,发现的就是这个PORT
  "EnableTagOverride": false,
  "Check": {             //健康检查部分
    "DeregisterCriticalServiceAfter": "90m",
    "HTTP": "http://www.baidu.com", //指定健康检查的URL,调用后只要返回20X,consul都认为是健康的
    "Interval": "10s"   //健康检查间隔时间,每隔10s,调用一次上面的URL
  }
}

使用curl调用

curl http://127.0.0.1:8500/v1/agent/service/register -X PUT -i -H "Content-Type:application/json" -d '{
  "ID": "userServiceId",  
  "Name": "userService",
  "Tags": [
    "primary",
    "v1"
  ],
  "Address": "127.0.0.1",
  "Port": 8000,
  "EnableTagOverride": false,
  "Check": {
    "DeregisterCriticalServiceAfter": "90m",
    "HTTP": "http://www.baidu.com",
    "Interval": "10s"
  }
}'

结果

1

2

3

4

5

6

  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current

                                 Dload  Upload   Total   Spent    Left  Speed

100   288    0     0  100   288      0  18000 --:--:-- --:--:-- --:--:-- 18000HTTP/1.1 200 OK

Vary: Accept-Encoding

Date: Wed, 26 Dec 2018 05:11:32 GMT

Content-Length: 0

7.2 发现个服务
刚刚注册了名为userService的服务,我们现在发现(查询)下这个服务

1

curl http://127.0.0.1:8500/v1/catalog/service/userService

返回的响应:

curl http://127.0.0.1:8500/v1/catalog/service/userService
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   891  100   891    0     0  28741      0 --:--:-- --:--:-- --:--:-- 28741[
    {
        "ID": "9b831a00-ae68-d575-5e51-df193897b834",
        "Node": "vip-PC",
        "Address": "127.0.0.1",
        "Datacenter": "dc1",
        "TaggedAddresses": {
            "lan": "127.0.0.1",
            "wan": "127.0.0.1"
        },
        "NodeMeta": {
            "consul-network-segment": ""
        },
        "ServiceKind": "",
        "ServiceID": "userServiceId",
        "ServiceName": "userService",
        "ServiceTags": [
            "primary",
            "v1"
        ],
        "ServiceAddress": "127.0.0.1",
        "ServiceWeights": {
            "Passing": 1,
            "Warning": 1
        },
        "ServiceMeta": {},
        "ServicePort": 8000,
        "ServiceEnableTagOverride": false,
        "ServiceProxyDestination": "",
        "ServiceProxy": {},
        "ServiceConnect": {},
        "CreateIndex": 88,
        "ModifyIndex": 88
    }
]

基本的服务发现和注册我们已经弄清楚了。接下来我来看看Spring Cloud 整合consul的使用。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SpringCloud提供了基于服务注册中心的解决方案,其中最常用的是Eureka和Consul。下面以Eureka为例,介绍一下SpringCloud如何实现服务注册发现。 1. 添加Eureka依赖 ```xml <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency> ``` 2. 配置Eureka Server 在Spring Boot应用程序中,可以通过增加@EnableEurekaServer注释来启用Eureka Server。 ```java @EnableEurekaServer @SpringBootApplication public class EurekaServerApplication { public static void main(String[] args) { SpringApplication.run(EurekaServerApplication.class, args); } } ``` 配置文件application.yml: ```yaml server: port: 8761 # Eureka Server默认端口 eureka: instance: hostname: localhost # Eureka Server主机名 client: register-with-eureka: false fetch-registry: false ``` 3. 配置Eureka Client 在Spring Boot应用程序中,可以将@EnableDiscoveryClient添加到主类中以启用服务发现客户端。 ```java @EnableDiscoveryClient @SpringBootApplication public class EurekaClientApplication { public static void main(String[] args) { SpringApplication.run(EurekaClientApplication.class, args); } } ``` 配置文件application.yml: ```yaml server: port: 8080 # 应用程序端口 spring: application: name: eureka-client # 应用程序名称 eureka: client: service-url: defaultZone: http://localhost:8761/eureka/ # Eureka Server的URL ``` 4. 运行应用程序 首先启动Eureka Server,然后启动多个Eureka Client,它们将向Eureka Server注册并进行服务发现。在Eureka Server的管理页面上可以查看已注册服务。 5. 使用服务 Eureka Client可以通过使用Spring Cloud的@LoadBalanced注释来负载均衡调用其他服务: ```java @RestController public class MyController { @Autowired private RestTemplate restTemplate; @GetMapping("/hello") public String hello() { String url = "http://eureka-client/hello"; // 调用eureka-client服务 return restTemplate.getForObject(url, String.class); } @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } } ``` 以上就是SpringCloud实现服务注册发现的基本流程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值