当前位置: 移动技术网 > IT编程>开发语言>Java > 服务注册和发现(Consul)

服务注册和发现(Consul)

2019年04月08日  | 移动技术网IT编程  | 我要评论

使用consul提供注册和发现服务

什么是 consul

consul 是 hashicorp 公司推出的开源工具,用于实现分布式系统的服务发现与配置。与其它分布式服务注册与发现的方案,consul 的方案更“一站式”,内置了服务注册与发现框架、分布一致性协议实现、健康检查、key/value 存储、多数据中心方案,不再需要依赖其它工具(比如 zookeeper 等)。使用起来也较为简单。consul 使用 go 语言编写,因此具有天然可移植性(支持linux、windows和mac os x);安装包仅包含一个可执行文件,方便部署,与 docker 等轻量级容器可无缝配合。

consul 安装

访问 consul 官网 ,根据操作系统类型,选择下载 consul 的最新版本。我这里选择windows版本。

下载下来是一个zip压缩包,解压之后,是一个exe可执行文件。

 打开cmd终端,进入consul.exe所在目录,执行如下命令启动consul服务。

cd c:\consul_1.3.0_windows_amd64  # 进入consul.exe所在目录
consul agent -dev # 启动服务, -dev 表示开发模式运行,另外还有 -server 表示服务模式运行

启动过程信息如下图所示。

启动成功之后,访问 http://www.lhsxpumps.com/_localhost:8500 , 可以查看 consul 管理界面。

 

consul 服务提供者

服务注册发现中心有了,现在我们来开发服务提供者。

新建项目 spring-cloud-consul-producer,添加以下依赖。

pom.xml

复制代码
<dependencies>
    <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.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>
</dependencies>
复制代码

说明:

spring-boot-starter-actuator 健康检查依赖于此包。

spring-cloud-starter-consul-discovery spring cloud consul 的支持。

注意添加spring cloud的依赖配置,完整内容参见源码pom文件。

复制代码
  <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>
复制代码

添加配置

在配置文件添加内容如下。

application.yml

复制代码
server:
  port: 8511
spring:
  application:
    name: spring-cloud-consul-producer
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        servicename: service-producer    # 注册到consul的服务名称
复制代码

consul 的地址和端口号默认是 localhost:8500 ,如果不是这个地址可以自行配置,consul服务会占用8502接口,所以不要用8501、8502。
spring.cloud.consul.discovery.servicename 是指注册到 consul 的服务名称,后期客户端会根据这个名称来进行服务调用。

修改启动类

 修改启动器类,添加 @enablediscoveryclient 注解,开启服务发现支持。

复制代码
package com.louis.spring.cloud.consul.producer;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.cloud.client.discovery.enablediscoveryclient;

@enablediscoveryclient
@springbootapplication
public class consuleproducerapplication {

    public static void main(string[] args) {
        springapplication.run(consuleproducerapplication.class, args);
    }
}
复制代码

添加服务

新建 hellocontroller,提供 hello 接口, 返回 hello consul 字符串。

复制代码
package com.louis.spring.cloud.consul.producer.controller;

import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
public class hellocontroller {

    @requestmapping("/hello")
    public string hello() {
        return "hello consul.";
    }
}
复制代码

为了模拟注册均衡负载,复制一份上面的项目,重命名为 spring-cloud-consul-producer2 ,修改对应的端口为 8512,修改 hello 方法的返回值为:"helle consul two",修改完成后依次启动两个项目,启动成功之后刷新consul管理界面,发现我们注册的service-producer服务,并有2个节点实例。

点击进入节点详情页面,可以看到我们注册的8511和8512两个服务提供者节点实例。

consul 消费者

服务注册发现中心有了,服务提供者也有了,现在我们来开发服务消费者。

新建项目 spring-cloud-consul-comsumer,依赖同提供者。

添加配置

修改配置文件如下。

application.yml

复制代码
server:
  port: 8521
spring:
  application:
    name: spring-cloud-consul-consumer
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        register: false    #设置不需要注册到 consul 中
复制代码

客户端可以设置是否注册到 consul 中,具体需要根据我们的业务来选择,一般在需要对外提供服务时进行注册。

启动器类

consuleconsumerapplication.java

复制代码
package com.louis.spring.cloud.consul.producer;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;

@springbootapplication
public class consuleconsumerapplication {

    public static void main(string[] args) {
        springapplication.run(consuleconsumerapplication.class, args);
    }
}
复制代码

服务消费者

添加消费服务测试类,添加两个接口,一个查询所有我们注册的服务,另一个从我们注册的服务中选取一个服务,采用轮询的方式。

servicecontroller.java

复制代码
package com.louis.spring.cloud.consul.producer.controller;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.cloud.client.discovery.discoveryclient;
import org.springframework.cloud.client.loadbalancer.loadbalancerclient;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;

@restcontroller
public class servicecontroller {

    @autowired
    private loadbalancerclient loadbalancerclient;
    @autowired
    private discoveryclient discoveryclient;

   /**
     * 获取所有服务
     */
    @requestmapping("/services")
    public object services() {
        return discoveryclient.getinstances("service-producer");
    }

    /**
     * 从所有服务中选择一个服务(轮询)
     */
    @requestmapping("/discover")
    public object discover() {
        return loadbalancerclient.choose("service-producer").geturi().tostring();
    }
}
复制代码

添加完成之后,启动项目, 访问 http://www.lhsxpumps.com/_localhost:8521/services,返回两个服务,分别是我们注册的8511和8512。

复制代码
[{
    "serviceid": "service-producer",
    "host": "gg20j1g2e.logon.ds.ge.com",
    "port": 8511,
    "secure": false,
    "metadata": {
        "secure": "false"
    },
    "uri": "http://gg20j1g2e.logon.ds.ge.com:8511",
    "scheme": null
}, {
    "serviceid": "service-producer",
    "host": "gg20j1g2e.logon.ds.ge.com",
    "port": 8512,
    "secure": false,
    "metadata": {
        "secure": "false"
    },
    "uri": "http://gg20j1g2e.logon.ds.ge.com:8512",
    "scheme": null
}]
复制代码

反复访问 http://localhost:8521/discover,结果交替返回服务8511和8512,因为默认的负载均衡器是采用轮询的方式。

http://gg20j1g2e.logon.ds.ge.com:8511
http://gg20j1g2e.logon.ds.ge.com:8512
...

8511 和 8512 两个服务会交替出现,从而实现了获取服务端地址的均衡负载。

大多数情况下我们希望使用均衡负载的形式去获取服务端提供的服务,因此使用第二种方法来模拟调用服务端提供的 hello 方法。

创建 callhellocontroller.java

复制代码
package com.louis.spring.cloud.consul.producer.controller;

import org.springframework.beans.factory.annotation.autowired;
import org.springframework.cloud.client.serviceinstance;
import org.springframework.cloud.client.loadbalancer.loadbalancerclient;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.client.resttemplate;

@restcontroller
public class callhellocontroller {

    @autowired
    private loadbalancerclient loadbalancer;

    @requestmapping("/call")
    public string call() {
        serviceinstance serviceinstance = loadbalancer.choose("service-producer");
        system.out.println("服务地址:" + serviceinstance.geturi());
        system.out.println("服务名称:" + serviceinstance.getserviceid());

        string callserviceresult = new resttemplate().getforobject(serviceinstance.geturi().tostring() + "/hello", string.class);
        system.out.println(callserviceresult);
        return callserviceresult;
    }

}
复制代码

使用 resttemplate 进行远程调用。添加完之后重启 spring-cloud-consul-consumer 项目。

在浏览器中访问地址:http://localhost:8521/call,依次返回结果如下:

helle consul
helle consul two
...

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网