【SpringCloud】整合Consul实现服务注册与发现

不念不忘少年蓝@ 2024-03-26 14:34 130阅读 0赞

一、Consul简介

什么是Consul

Consul是HashiCorp公司推出的开源软件,使用GO语言编写,提供了分布式系统的

  • 服务注册和发现、配置等功能,

  • 这些功能中的每一个都可以根据需要单独使用,也可以一起使用以构建全方位的服务网格。

  • Consul不仅具有服务治理的功能,而且使用分布式一致协议RAFT算法实现,有多数据中心的高可用方案,并且很容易和Spring Cloud等微服务框架集成,

  • 使用起来非常的简单,具有简单、易用、可插排等特点。使用简而言之,Consul提供了一种完整的服务网格解决方案 。

二、Consul 服务注册发现流程

c26b18b776bdff9ab2134ec164b799f0.png

在上面的流程图上有三个角色,分别为服务注册中心、服务提供者、服务消费者。

  • 服务提供者Provider启动的时候,会向Consul发送一个请求,

  • 将自己的host、ip、应用名、健康检查等元数据信息发送给Consul

  • Consul 接收到 Provider 的注册后,定期向 Provider 发送健康检查的请求,检验Provider是否健康

  • 服务消费者Consumer会从注册中心Consul中获取服务注册列表,当服务消费者消费服务时,根据应用名从服务注册列表获取到具体服务的实例(1个或者多个),从而完成服务的调用。

三、项目实战代码

  1. Consul启动

Consul采用Go语言编写,支持Linux、Mac、Windows等各大操作系统,本文使用windows操作系统,下载地址:https://www.consul.io/downloads.html,下完成后解压到计算机目录下,解压成功后,只有一个可执行的consul.exe可执行文件。打开cmd终端,切换到目录,执行以下命令:

  1. consul agent -dev -client 0.0.0.0 -ui
  1. 新建Java项目

新建maven项目,项目名为consul-test,同时添加两个子模块:consul-consumer、consul-provider

d1ef6333bbb3de43029b395c42c14a60.png

新建完成后,项目结构如上图

  1. 根目录pom.xml

    <?xml version=”1.0” encoding=”UTF-8”?>


    4.0.0

    org.example
    consul-test
    pom
    1.0-SNAPSHOT

    consul-provider
    consul-consumer



    org.springframework.boot
    spring-boot-starter-parent
    2.1.4.RELEASE






    org.springframework.cloud
    spring-cloud-dependencies
    Greenwich.RELEASE
    pom
    import





    8
    8




    org.springframework.cloud
    spring-cloud-starter-consul-discovery




    org.springframework.boot
    spring-boot-starter-actuator



    org.springframework.boot
    spring-boot-starter-web



    org.springframework.cloud
    spring-cloud-starter-openfeign




  2. 服务提供者代码

  3. consul-provider下pom.xml代码

    <?xml version=”1.0” encoding=”UTF-8”?>



    consul-test
    org.example
    1.0-SNAPSHOT
    ../pom.xml

    4.0.0

    consul-provider


    8
    8


  4. consul-provider/src/main/resources

application.yml

  1. spring:
  2. application:
  3. name: consul-provider
  4. profiles:
  5. active: dev
  6. cloud:
  7. consul:
  8. # 服务发现配置
  9. discovery:
  10. # 启用服务发现
  11. enabled: true
  12. # 启用服务注册
  13. register: true
  14. # 服务停止时取消注册
  15. deregister: true
  16. # 表示注册时使用IP而不是hostname
  17. prefer-ip-address: true
  18. # 执行监控检查的频率
  19. health-check-interval: 30s
  20. # 设置健康检查失败多长时间后,取消注册
  21. health-check-critical-timeout: 30s
  22. # 健康检查的路径
  23. health-check-path: /actuator/info
  24. # 服务注册标识,格式为:应用名称+服务器IP+端口
  25. instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
  26. server:
  27. port: 8764

bootstrap.yml

  1. # bootstrap.yml
  2. # consul 使用动态配置,必须在bootstrap.yml中配置好动态配置项目的配置
  3. spring:
  4. cloud:
  5. consul:
  6. host: localhost
  7. port: 8500
  8. #enabled将此值设置为“false”禁用Consul配置
  9. config:
  10. enabled: true #默认是true --
  11. format: YAML # 表示consul上面文件的格式 有四种 YAML PROPERTIES KEY-VALUE FILES
  12. data-key: data #表示consul上面的KEY值(或者说文件的名字) 默认是data
  13. # watch选项为配置监视功能,主要监视配置的改变
  14. watch:
  15. enabled: true
  16. delay: 10000
  17. wait-time: 30
  1. consul-provider/src/main/java/com/example/controller/HiController.java

    package com.example.controller;

  1. import org.springframework.beans.factory.annotation.Value;
  2. import org.springframework.web.bind.annotation.GetMapping;
  3. import org.springframework.web.bind.annotation.RequestParam;
  4. import org.springframework.web.bind.annotation.RestController;
  5. @RestController
  6. public class HiController {
  7. @Value("${server.port}")
  8. String port;
  9. @GetMapping("/hi")
  10. public String home(@RequestParam String name) {
  11. return "hi "+name+",i am from port:" +port;
  12. }
  13. }
  1. consul-provider/src/main/java/com/example/ConsulProviderApplication.java

    package com.example;

    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

    @SpringBootApplication
    @EnableDiscoveryClient
    public class ConsulProviderApplication {

    1. public static void main(String[] args) {
    2. SpringApplication.run(ConsulProviderApplication.class, args);
    3. System.out.println(".....................................");
    4. System.out.println("....Provider Application started.....");
    5. System.out.println(".....................................");
    6. }

    }

  2. 服务消费者代码

1. consul-consumer/pom.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <project xmlns="http://maven.apache.org/POM/4.0.0"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5. <parent>
  6. <artifactId>consul-test</artifactId>
  7. <groupId>org.example</groupId>
  8. <version>1.0-SNAPSHOT</version>
  9. <relativePath>../pom.xml</relativePath>
  10. </parent>
  11. <modelVersion>4.0.0</modelVersion>
  12. <artifactId>consul-consumer</artifactId>
  13. <properties>
  14. <maven.compiler.source>8</maven.compiler.source>
  15. <maven.compiler.target>8</maven.compiler.target>
  16. </properties>
  17. </project>

2. consul-consumer/src/main/resources

application.yml

  1. spring:
  2. application:
  3. name: consul-consumer
  4. profiles:
  5. active: dev
  6. cloud:
  7. consul:
  8. # 服务发现配置
  9. discovery:
  10. # 启用服务发现
  11. enabled: true
  12. # 启用服务注册
  13. register: true
  14. # 服务停止时取消注册
  15. deregister: true
  16. # 表示注册时使用IP而不是hostname
  17. prefer-ip-address: true
  18. # 执行监控检查的频率
  19. health-check-interval: 30s
  20. # 设置健康检查失败多长时间后,取消注册
  21. health-check-critical-timeout: 30s
  22. # 健康检查的路径
  23. health-check-path: /actuator/info
  24. # 服务注册标识,格式为:应用名称+服务器IP+端口
  25. instance-id: ${spring.application.name}:${spring.cloud.client.ip-address}:${server.port}
  26. server:
  27. port: 8766

bootstrap.yml

  1. # bootstrap.yml
  2. # consul 使用动态配置,必须在bootstrap.yml中配置好动态配置项目的配置
  3. spring:
  4. cloud:
  5. consul:
  6. host: localhost
  7. port: 8500
  8. #enabled将此值设置为“false”禁用Consul配置
  9. config:
  10. enabled: true #默认是true --
  11. format: YAML # 表示consul上面文件的格式 有四种 YAML PROPERTIES KEY-VALUE FILES
  12. data-key: data #表示consul上面的KEY值(或者说文件的名字) 默认是data
  13. # watch选项为配置监视功能,主要监视配置的改变
  14. watch:
  15. enabled: true
  16. delay: 10000
  17. wait-time: 30

3. consul-consumer/src/main/java/com/example/feign/EurekaClientFeign.java

  1. package com.example.feign;
  2. import org.springframework.cloud.openfeign.FeignClient;
  3. import org.springframework.web.bind.annotation.GetMapping;
  4. import org.springframework.web.bind.annotation.RequestParam;
  5. @FeignClient(value = "consul-provider")
  6. public interface EurekaClientFeign {
  7. @GetMapping(value = "/hi")
  8. String sayHiFromClientEureka(@RequestParam(value = "name") String name);
  9. }

4. consul-consumer/src/main/java/com/example/service/HiService.java

  1. package com.example.service;
  2. import com.example.feign.EurekaClientFeign;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class HiService {
  7. @Autowired
  8. EurekaClientFeign eurekaClientFeign;
  9. public String sayHi(String name){
  10. return eurekaClientFeign.sayHiFromClientEureka(name);
  11. }
  12. }

5. consul-consumer/src/main/java/com/example/ConsulConsumerApplication.java

  1. package com.example;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
  5. import org.springframework.cloud.openfeign.EnableFeignClients;
  6. @SpringBootApplication
  7. @EnableDiscoveryClient
  8. @EnableFeignClients
  9. public class ConsulConsumerApplication {
  10. public static void main(String[] args) {
  11. SpringApplication.run(ConsulConsumerApplication.class, args);
  12. System.out.println(".....................................");
  13. System.out.println("....Consumer Application started.....");
  14. System.out.println(".....................................");
  15. }
  16. }
  1. 启动和测试

分别启动 provider 和 consumer Application

访问consul -sevices如下图:

bb6b1e5d9847916d6ffe0e229ca95c3d.png

单独访问 提供者

http://127.0.0.1:8764/hi?name=aaa

779a79df9dd095b07680f504aa51fd42.png

单独访问消费者

返回的是 提供者的端口,说明微服务调用成功

590e13f26788ac7cf825c779d1f9b984.png

发表评论

表情:
评论列表 (有 0 条评论,130人围观)

还没有评论,来说两句吧...

相关阅读