• 服务注册发现consul之二:在Spring Cloud中使用Consul实现服务的注册和发现


    首先安装consul环境,参照之前的文章:《服务注册发现consul之一:consul介绍及安装》中的第一节介绍。

    Spring Cloud使用Consul的服务与发现

    1、导入依赖pring-cloud-starter-consul-discovery。

    2、在其入口文件Application加入注解@EnableDiscoveryClient,开启服务发现(在consul中注册自己)。

    3、配置中标明consul信息及自己注册到注册中心的SERVICES和instance-id

    spring.cloud.consul.host=localhost
    spring.cloud.consul.port=8500
    spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
    spring.cloud.consul.discovery.healthCheckInterval=15s
    spring.cloud.consul.discovery.instance-id=consul-client1
    spring.application.name=consul-client1

    源码:

    spring-cloud-starter-consul-discovery-1.3.3.RELEASE里的pom.xml中引入了spring-cloud-starter-consul,查看spring-cloud-starter-consul-1.3.3.RELEASE.jar中的pom.xml文件中引入了spring-cloud-consul-core和consul-api

    再看spring-cloud-consul-core-1.3.3.RELEASE.jar的源代码:

    几个配置有:ConsulProperties.java

    @ConfigurationProperties("spring.cloud.consul")
    @Data
    @Validated
    public class ConsulProperties {
        /** Consul agent hostname. Defaults to 'localhost'. */
        @NotNull
        private String host = "localhost";
    
        /** Consul agent port. Defaults to '8500'. */
        @NotNull
        private int port = 8500;
    
        /** Is spring cloud consul enabled */
        private boolean enabled = true;
    }

    RetryProperties.java

    @ConfigurationProperties("spring.cloud.consul.retry")
    @Data
    public class RetryProperties {
    
        /** Initial retry interval in milliseconds. */
        private long initialInterval = 1000;
    
        /** Multiplier for next interval. */
        private double multiplier = 1.1;
    
        /** Maximum interval for backoff. */
        private long maxInterval = 2000;
    
        /** Maximum number of attempts. */
        private int maxAttempts = 6;
    }

    为了演示consul的注册与发现,下面会创建2个服务和1个client端:

    一:服务端1:

    1、pom.xml

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.dxz</groupId>
        <artifactId>cloud-server1</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>cloud-client</name>
        <url>http://maven.apache.org</url>
    
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.5.2.RELEASE</version>
            <relativePath/> <!-- lookup parent from repository -->
        </parent>
    
    
        <dependencies>
            <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>
    
        <dependencyManagement>
            <dependencies>
                <dependency>
                    <groupId>org.springframework.cloud</groupId>
                    <artifactId>spring-cloud-dependencies</artifactId>
                    <version>Dalston.RELEASE</version>
                    <type>pom</type>
                    <scope>import</scope>
                </dependency>
            </dependencies>
        </dependencyManagement>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>
    
    </project>

    server的启动类:ConsulApp.java

    package com.dxz.cloud_server;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication  
    @EnableDiscoveryClient  
    @RestController  
    public class ConsulApp {  
          
        @RequestMapping("/home")  
        public Object home() {  
            System.out.println("cloud-server1");  
            return "cloud-server1";  
        }  
          
        public static void main( String[] args ) {  
            SpringApplication.run(ConsulApp.class, args);  
        }  
    }  

    配置文件application.properties

    spring.cloud.consul.host=localhost
    spring.cloud.consul.port=8500
    spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
    spring.cloud.consul.discovery.healthCheckInterval=15s
    spring.cloud.consul.discovery.instance-id=consul-server1
    spring.application.name=consul-server
    server.port=8503

    由于我们增加了@EnableDiscoveryClient注解,所以,系统启动的时候,就会向consul注册一个服务,服务的名字为consul-server, ID为consul-server1

    启动后,访问:http://localhost:8500/ui/#/dc1/services/consul-server,输出如下页面:

    访问consul的HTTP API:http://localhost:8500/v1/catalog/service/consul-server 输出如下:

    [
        {
            "ID": "ae2b2853-18fa-7042-a157-25da30fcc744",
            "Node": "DESKTOP-PPSFCNC",
            "Address": "127.0.0.1",
            "Datacenter": "dc1",
            "TaggedAddresses": {
                "lan": "127.0.0.1",
                "wan": "127.0.0.1"
            },
            "NodeMeta": {},
            "ServiceID": "consul-server1",
            "ServiceName": "consul-server",
            "ServiceTags": [],
            "ServiceAddress": "DESKTOP-PPSFCNC",
            "ServicePort": 8503,
            "ServiceEnableTagOverride": false,
            "CreateIndex": 316,
            "ModifyIndex": 719
        },
        {
            "ID": "ae2b2853-18fa-7042-a157-25da30fcc744",
            "Node": "DESKTOP-PPSFCNC",
            "Address": "127.0.0.1",
            "Datacenter": "dc1",
            "TaggedAddresses": {
                "lan": "127.0.0.1",
                "wan": "127.0.0.1"
            },
            "NodeMeta": {},
            "ServiceID": "consul-server2",
            "ServiceName": "consul-server",
            "ServiceTags": [],
            "ServiceAddress": "DESKTOP-PPSFCNC",
            "ServicePort": 8504,
            "ServiceEnableTagOverride": false,
            "CreateIndex": 585,
            "ModifyIndex": 721
        }
    ]

    二:服务端2

    1、pom.xml同上

     2、启动类:

    package com.dxz.cloud_server;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication  
    @EnableDiscoveryClient  
    @RestController  
    public class ConsulApp {  
          
        @RequestMapping("/home")  
        public Object home() {  
            System.out.println("cloud-server2");  
            return "cloud-server2";  
        }  
          
        public static void main( String[] args ) {  
            SpringApplication.run(ConsulApp.class, args);  
        }  
    }  

    application.properties 配置内容:(端口、instance-id不同)

    spring.cloud.consul.host=localhost
    spring.cloud.consul.port=8500
    spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
    spring.cloud.consul.discovery.healthCheckInterval=15s
    spring.cloud.consul.discovery.instance-id=consul-server2
    spring.application.name=consul-server
    server.port=8504

    启动后:

    三:客户端

    项目依赖,只需要spring-cloud-starter-consul-discovery(我的pom同上)

    application.properties 配置内容:

    spring.cloud.consul.host=localhost
    spring.cloud.consul.port=8500
    spring.cloud.consul.discovery.healthCheckPath=${management.contextPath}/health
    spring.cloud.consul.discovery.healthCheckInterval=15s
    spring.cloud.consul.discovery.instance-id=consul-client1
    spring.application.name=consul-client1
    server.port=8501

     主类:

    package com.dxz.cloud_client;
    
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    @RestController
    public class ConsulClientApplication {
    
        @RequestMapping("/home")
        public String home() {
            return "hi ,i'm consul client";
        }
    
        public static void main(String[] args) {
            new SpringApplicationBuilder(ConsulClientApplication.class).web(true).run(args);
        }
    }

    主类:ConsulClientApplication.java

    package com.dxz.cloud_client;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.boot.builder.SpringApplicationBuilder;
    import org.springframework.cloud.client.discovery.DiscoveryClient;
    import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
    import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @SpringBootApplication
    @EnableDiscoveryClient
    @RestController
    public class ConsulClientApplication {
    
        @RequestMapping("/home")
        public String home() {
            return "hi ,i'm consul client";
        }
        
        @Autowired  
        private LoadBalancerClient loadBalancer;  
          
        @Autowired  
        private DiscoveryClient discoveryClient;  
          
        /** 
         * 从所有服务中选择一个服务(轮询) 
         */  
        @RequestMapping("/discover")  
        public Object discover() {  
            return loadBalancer.choose("consul-server").getUri().toString();  
        }  
          
        /** 
         * 获取所有服务  
         */  
        @RequestMapping("/services")  
        public Object services() {  
            return discoveryClient.getInstances("consul-server");  
        }  
    
        public static void main(String[] args) {
            new SpringApplicationBuilder(ConsulClientApplication.class).web(true).run(args);
        }
    }

    启动之后,观看consul如下:

    访问http://localhost:8501/services返回如下:

    [{"serviceId":"consul-server","host":"DESKTOP-PPSFCNC","port":8503,"secure":false,"metadata":{},"uri":"http://DESKTOP-PPSFCNC:8503"},{"serviceId":"consul-server","host":"DESKTOP-PPSFCNC","port":8504,"secure":false,"metadata":{},"uri":"http://DESKTOP-PPSFCNC:8504"}]

    访问:http://localhost:8501/discover

    Spring Cloud Consul 配置

    核心参数
    配置项默认值
    spring.cloud.consul.enabled true
    spring.cloud.consul.host localhost
    spring.cloud.consul.port 8500
    服务发现参数
    配置项默认值
    spring.cloud.consul.discovery.acl-token  
    spring.cloud.consul.discovery.catalog-services-watch-delay 10
    spring.cloud.consul.discovery.catalog-services-watch-timeout 2
    spring.cloud.consul.discovery.datacenters  
    spring.cloud.consul.discovery.default-query-tag  
    spring.cloud.consul.discovery.default-zone-metadata-name zone
    spring.cloud.consul.discovery.deregister true
    spring.cloud.consul.discovery.enabled true
    spring.cloud.consul.discovery.fail-fast true
    spring.cloud.consul.discovery.health-check-critical-timeout  
    spring.cloud.consul.discovery.health-check-interval 10s
    spring.cloud.consul.discovery.health-check-path /actuator/health
    spring.cloud.consul.discovery.health-check-timeout  
    spring.cloud.consul.discovery.health-check-tls-skip-verify  
    spring.cloud.consul.discovery.health-check-url  
    spring.cloud.consul.discovery.heartbeat.enabled false
    spring.cloud.consul.discovery.heartbeat.interval-ratio  
    spring.cloud.consul.discovery.heartbeat.ttl-unit s
    spring.cloud.consul.discovery.heartbeat.ttl-value 30
    spring.cloud.consul.discovery.hostname  
    spring.cloud.consul.discovery.instance-group  
    spring.cloud.consul.discovery.instance-id 默认为服务名+环境+端口号
    spring.cloud.consul.discovery.instance-zone  
    spring.cloud.consul.discovery.ip-address  
    spring.cloud.consul.discovery.lifecycle.enabled true
    spring.cloud.consul.discovery.management-port  
    spring.cloud.consul.discovery.management-suffix management
    spring.cloud.consul.discovery.management-tags  
    spring.cloud.consul.discovery.port  
    spring.cloud.consul.discovery.prefer-agent-address false
    spring.cloud.consul.discovery.prefer-ip-address false
    spring.cloud.consul.discovery.query-passing false
    spring.cloud.consul.discovery.register true
    spring.cloud.consul.discovery.register-health-check true
    spring.cloud.consul.discovery.scheme http
    spring.cloud.consul.discovery.server-list-query-tags  
    spring.cloud.consul.discovery.service-name  
    spring.cloud.consul.discovery.tags  
    配置服务参数
    配置项默认值
    spring.cloud.consul.config.enabled true
    spring.cloud.consul.config.prefix config
    spring.cloud.consul.config.default-context application
    spring.cloud.consul.config.profile-separator ,
    spring.cloud.consul.config.data-key data
    spring.cloud.consul.config.format KEY_VALUE, PROPERTIES, YAML, FILES
    spring.cloud.consul.config.name ${spring.application.name}
    spring.cloud.consul.config.acl-token  
    spring.cloud.consul.config.fail-fast false
    spring.cloud.consul.config.watch.enabled true
    spring.cloud.consul.config.watch.wait-time 55
    spring.cloud.consul.config.watch.delay 1000
  • 相关阅读:
    基本运算符和if判断
    数据类型
    Day 5内存管理,定义变量
    Day 4 变量常量
    编辑语言的分类
    硬盘工作原理
    计算机组成原理
    hdu5293 lca+dp+树状数组+时间戳
    hdu5290树形dp
    hdu5294 网络流+dijskstr
  • 原文地址:https://www.cnblogs.com/duanxz/p/7049350.html
Copyright © 2020-2023  润新知