SpringCloud使用Consul作为注册中心和配置中心

安装consul集群

1.这里采用的是docker-compose的方式来部署consul集群,代码如下,docker的安装以及docker-compose的安装在此不做介绍。
创建docker-compose.yml文件并将其上传到服务器中,在目录下执行docker-compose up -d既可。

version: '2'
networks:
  consul:
   driver: bridge


services:
  consul1:
    image: consul
    container_name: node1
    command: agent -server -bootstrap-expect=3 -node=node1 -bind=0.0.0.0 -client=0.0.0.0 -datacenter=dc1
    networks:
      - consul

  consul2:
    image: consul
    container_name: node2
    command: agent -server -retry-join=node1 -node=node2 -bind=0.0.0.0 -client=0.0.0.0 -datacenter=dc1
    depends_on:
        - consul1
    networks:
      - consul

  consul3:
    image: consul
    container_name: node3
    command: agent -server -retry-join=node1 -node=node3 -bind=0.0.0.0 -client=0.0.0.0 -datacenter=dc1
    depends_on:
        - consul1
    networks:
      - consul

  consul4:
    image: consul
    container_name: node4
    command: agent -retry-join=node1 -node=ndoe4 -bind=0.0.0.0 -client=0.0.0.0 -datacenter=dc1 -ui 
    ports:
      - 8500:8500
    depends_on:
        - consul2
        - consul3
    networks:
      - consul

创建客户端程序

采用mvn的方式,完整的pom代码如下:
完整源代码地址:https://gitee.com/cosmosNi/consul-demo

项目目录如下:SpringCloud使用Consul作为注册中心和配置中心

<?xml version="1.0" encoding="UTF-8"?>
<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>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.cosmos</groupId>
    <artifactId>consul-demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>consul-demo</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
                <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-bus</artifactId>
        </dependency>
    </dependencies>

    <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>

    <build>
        <finalName>consul-web</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>
                                repackage
                            </goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

</project>

主要配置:

spring:
  cloud:
    consul:
      discovery:
        health-check-path: /actuator/health  ##检测实例健康
        health-check-interval: 10s   ##每隔10s检查
#        hostname: 127.0.0.1    ##配置实例地址 
        register: true  ##自动注册
        service-name: ${spring.application.name} ##实例名称
      host: 127.0.0.1 #consul地址
      port: 8500  ##consul端口
      config:  
        enabled: true  ##是否开启配置中心
        format: yaml   ##配置中心解析样式
  application:
    name: consultest

创建configuration类用于接收远程配置:代码如下

@ConfigurationProperties(prefix = "student")
@Data
@ToString
public class StudentConfig {
    private String name;
    private int age;
    private String sex;
}

创建一个feign类,用于进行远程访问以及负载均衡,这里的value的值即为上面配置的spring.application.name

@FeignClient(value = "consultest")
public interface FeignService {

    @GetMapping("/test")
    String test();
}

创建controller,用于消费以及服务提供

@RestController
public class TestController {
    @Autowired
    private FeignService feignService;
    @Autowired
    private StudentConfig studentConfig;

    @GetMapping("/test")
    public String test() {
        System.out.println("------输出----------");
        return "1232132132";
    }

    @GetMapping("/consul")
    private String testConsul() {
        return feignService.test();
    }

    @GetMapping("/config")
    private String testConfig() {
        return studentConfig.toString();
    }
}

启动类

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients
@EnableConfigurationProperties({StudentConfig.class})
public class ConsulDemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConsulDemoApplication.class, args);
    }

}

最后,根据自己需要启动多个服务,在这里笔者使用dev,test,client三个环境

创建key/value

访问consul地址:key指代的是作用的配置文件以及application.name
SpringCloud使用Consul作为注册中心和配置中心

结果展示

配置中心(当你在consul里更改配置时,客户端通过bus自动刷新,获取最新值)
SpringCloud使用Consul作为注册中心和配置中心
服务注册:请求多次
SpringCloud使用Consul作为注册中心和配置中心
负载均衡:
SpringCloud使用Consul作为注册中心和配置中心SpringCloud使用Consul作为注册中心和配置中心

结束语

在Eureka2.0闭源的时代,consul也是一个不错的选择。