美文网首页
spring cloud实战:4- 服务注册与发现Consul

spring cloud实战:4- 服务注册与发现Consul

作者: jyjack | 来源:发表于2019-07-30 16:12 被阅读0次

    如果您认为对你有帮助,请点个赞!

    概述

    本篇主要讲述如下两种集群的搭建

    • Consul集群
    • 服务提供方集群

    准备工作

    请先参考 spring cloud实战:2- 服务注册与发现Consul 完成准备工作。

    Consul集群

    (待补充)
    搭建Consul集群
    生产者及消费者如何注册到Consul集群

    服务提供方集群

    提供方项目模块为 consul_provider,我们将通过使用多配置文件的方式,配置两个节点

    • 创建多环境配置文件

    将consul_provider模块下的 application.properties 配置文件复制为application-profile1.properties,保持端口不变

    server.port=8501
    

    将consul_provider模块下的 application.properties 配置文件复制为application-profile2.properties,然后修改端口避免冲突

    server.port=8505
    

    这样我们就创建了两个配置文件。

    同时运行两个配置文件对应的服务,就可以实现集群服务。

    • 以指定的配置文件启动服务

    Run... 编辑配置 添加Application运行配置 设置运行参数

    上图中,通过如下参数指定配置文件

    --spring.profiles.active=profile1
    

    通过"Run...",选择则创建的配置 "provide-profile1" ,即可profile1对应的服务

    image.png profile1启动成功

    以同样的方式,启动profile2:


    profile2启动成功
    • 查看集群状态

    进入consul的WEB管理界面:


    image.png

    可看到该服务包括两个集群节点:


    image.png
    • 测试

    通过consumer访问该服务时,consul会进行负载均衡。
    为了验证,需要对provider应用进行改造,以显示当前提供服务的节点的信息。
    修改consul_provider模块下的SayHelloController.java程序,以添加输出当前端口的功能,代码如下:

    package com.example.consul.provider;
    
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController   //REST服务
    public class SayHelloController {
    
        @Value("${server.port}")
        private String port;       //获取当前的端口
    
    
        @RequestMapping("/sayhello")
        public String sayHello(@RequestParam String name) {
            return "Hello  " + name + " !       (by " + port + ")";   //增加显示端口
        }
    }
    

    重新启动集群的两个节点。
    通过浏览器访问comsumer的URL:多次访问,会看到端口在发生变化,说明consul的负载均衡发生了作用:


    image.png image.png

    如果停掉一个节点,则所有的请求会转到剩余的一个节点。
    当异常节点恢复后,又会进行负载均衡。


    相关文章

      网友评论

          本文标题:spring cloud实战:4- 服务注册与发现Consul

          本文链接:https://www.haomeiwen.com/subject/beqnrctx.html