Spring Cloud Hoxton version Consul discovery and configuration service registration center (Hoxton version)

Spring Cloud Hoxton version Consul discovery and configuration service registration center (Hoxton version)


Summary

Prior to the share: the Spring Cloud Services project to build a micro version of Hoxton eureka registry , to share with you today: Spring Cloud Hoxton version Consul discovery and configuration service registration center (Hoxton version)!

Spring Cloud Consul Consul provides support for SpringBoot application, Consul may be used as a registration center, you can also use as a distribution center, the paper will detail its usage.

Bloggers can go to see the article Portal: the Spring Cloud Consul Chinese reference manual!


Consul Introduction

Consul is HashiCorp launched open-source software, provides a service management system of micro-services, distribution center, bus and other control functions. Each of these functions can be used individually as needed, it can also be used together to build a grid full range of services, in short, Consul provides a complete service grid solution.

Spring Cloud Consul has the following characteristics:

  • Support Services Governance : Consul as the registry, the application of micro service can register itself with the Consul, and other application information can be obtained from the Consul;
  • Supports client-side load balancing : Includes Ribbon and Spring Cloud LoadBalancer;
  • Support Zuul : When Zuul as a gateway, you can register and find applications from the Consul;
  • Support for distributed configuration management : Consul as a distribution center, using a key to store configuration information;
  • Support control bus : event messages can be distributed through the entire micro-Control Bus service system.

Consul use as a registration center

First of all

Official website to download Consul (self-select the appropriate version), Address: https://www.consul.io/downloads.html

Here Insert Picture Description
After the download is complete only one exe file, double-click operation;

Please refer to bloggers history article for installation: installation configuration Consul in Windows10 environment!

Enter the following command in the command line you can see the version number:

consul --version

Here Insert Picture Description
Use development mode is activated:

consul agent -dev 

Here Insert Picture Description

Consul can be accessed through the following address Home : HTTP: // localhost: 8500

Here Insert Picture Description


Create an application to register Consul

Let's demonstrate the features found under the service registration through the transformation of user-service and ribbon-service, mainly to the application of the original Eureka registry support instead Consul registry support.

Create a consul-user-service module and the consul-ribbon-service module;

Modify its dependencies, the original Eureka registered dependency discovery changed Consul, and add the dependent SpringBoot Actuator:

		 <!-- 健康检查 -->
        <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>

        <!-- Spring Cloud Consul 依赖引入 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

        <!-- Admin 2.2.1 版本客户端引入依赖 -->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.2.1</version>
        </dependency>

Yml configuration file as follows:

server:
  #项目端口号
  port: 8889
  tomcat:
    max-connections: 200
    max-threads: 300
    min-spare-threads: 0
    uri-encoding: UTF-8

logging:
  pattern:
    console: "%d - %msg%n"
  #path: D:\Logback-Test\             #日志输出到指定文件夹下默认名为spring.log
  file: D:\Logback-Test\wordimg.log  #日志输出到指定文件
  #level: debug   #指定级别
  level:         #指定输出某个类的日志
    com.cnooc.wordimg.LoggerTest2: debug

spring:
  application:
    name: consul-server
  # 注册到Admin管理中心
  boot:
    admin:
      client:
        url: http://localhost:6010
  cloud:
    consul:
      # 将服务注册到consul
      host: localhost
      port: 8500
      discovery:
        service-name: ${spring.application.name}

# Admin 管理配置
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

Start categories:

package com.cyj.consulcenter;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author ChenYongJia
 * @Description: ConsulCenterApplication 服务注册中心和配置中心项目
 * @ClassName: SpringCloudApplication.java
 * @Date 2019年12月29日 晚上22:54
 * @Email [email protected]
 */
@Slf4j
@EnableDiscoveryClient
@SpringBootApplication
public class ConsulCenterApplication {

    public static void main(String[] args) {
        log.info("启动 consul-center 服务注册中心和配置中心项目...");
        SpringApplication.run(ConsulCenterApplication.class, args);
        log.info("启动 consul-center 服务注册中心和配置中心项目成功...");
    }

}

Run the project, on the Consul page you can see the following information:

Here Insert Picture Description


Load balancing

Since we run a service, and the service will default to call another call of its interface, the default load balancing.


Consul use as a distribution center

We create consul-config-client module and add the configuration information to demonstrate Consul in under configuration management functions.


Create a consul-config-client module

Add its dependencies in pom.xml:

<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.boot</groupId>
	<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

Complete pom.xml as follows:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>com.cyj</groupId>
        <artifactId>Family</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <groupId>com.cyj</groupId>
    <artifactId>consul-config-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>consul-config-client</name>
    <description>CYJ:Spring Cloud Consul 服务注册中心和配置中心</description>

    <dependencies>

        <!-- SpringCloud Eureka 注册中心依赖 -->
        <!--<dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId>
        </dependency>-->

        <!-- 健康检查 -->
        <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>

        <!-- Spring Cloud Consul 依赖引入 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-discovery</artifactId>
        </dependency>

        <!-- 引入consul的config 依赖 -->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-consul-config</artifactId>
        </dependency>

        <!-- Admin 2.2.1 版本客户端引入依赖 -->
        <dependency>
            <groupId>de.codecentric</groupId>
            <artifactId>spring-boot-admin-starter-client</artifactId>
            <version>2.2.1</version>
        </dependency>

    </dependencies>

    <!-- SpringCloud 所有子项目 版本集中管理.MS:统一所有SpringCloud依赖项目的版本 依赖 -->
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <!-- SpringBoot 2.2.x 以上版本这样配置 -->
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <!-- SpringBoot 项目打jar包的Maven插件 -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
        <!-- SpringBoot项目打包jar名称 -->
        <finalName>consul-config-client</finalName>
    </build>

    <!-- SpringCloud 官方远程仓库.MS:部分本地仓库和镜像仓库没有SpringCloud子项目依赖。 -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

Add a profile application.yml, is configured to enable the dev environment:

spring:
  profiles:
    active: dev

Add a profile bootstrap.yml, mainly on the configuration capabilities of Consul configure:

server:
  #项目端口号
  port: 8890
  tomcat:
    max-connections: 200
    max-threads: 300
    min-spare-threads: 0
    uri-encoding: UTF-8

logging:
  pattern:
    console: "%d - %msg%n"
  #path: D:\Logback-Test\             #日志输出到指定文件夹下默认名为spring.log
  file: D:\Logback-Test\wordimg.log  #日志输出到指定文件
  #level: debug   #指定级别
  level:         #指定输出某个类的日志
    com.cnooc.wordimg.LoggerTest2: debug

spring:
  application:
    name: consul-config-client
  # 注册到Admin管理中心
  boot:
    admin:
      client:
        url: http://localhost:6010
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: consul-config-client
      config:
        # 是否启用配置中心功能
        enabled: true
        # 设置配置值的格式
        format: yaml
        # 设置配置所在目录
        prefix: config
        # 设置配置的分隔符
        profile-separator: ':'
        # 配置key的名字,由于Consul是K/V存储,配置存储在对应K的V中
        data-key: data

# Admin 管理配置
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

Creating ConfigClientController, obtain configuration information from the configuration Consul center:

package com.cyj.consulclient.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @Description: 创建ConfigClientController,从Consul配置中心中获取配置信息
 * @BelongsProject: Family
 * @BelongsPackage: com.cyj.consulclient.controller
 * @Author: ChenYongJia
 * @CreateTime: 2020-01-07 15:36
 * @Email: [email protected]
 * @Version: 1.0
 */
@Slf4j
@Configuration
@RefreshScope // 用于刷新配置
@RestController
public class ConfigClientController {

    @Resource
    @Value("${config.info}")
    private String configInfo;

    /**
     * http://localhost:8890/configInfo
     * @return
     */
    @GetMapping("/configInfo")
    public String getConfigInfo() {
        log.info("configInfo=================>"+configInfo);
        return configInfo;
    }

}

Add a profile in the Consul

Add the configuration stored in the key for the consul:

config/consul-config-client:dev/data

Here Insert Picture Description

Here Insert Picture Description

Start consul-config-client, call interface to check the configuration: HTTP: // localhost: 8890 / ConfigInfo

config info for dev

Here Insert Picture Description

Here Insert Picture Description


Consul dynamic refresh configuration

As long as we modify configuration information Consul in the call again to check the configuration of the interface, you will find configuration has been refreshed. But if you use Spring Cloud Config, we need to call interface, refresh the configuration by Spring Cloud Bus talent. Consul use its own Control Bus achieve an event delivery mechanism, enabling dynamic refresh function.


At last

  • More Reference wonderful Bowen see here: "Chen Yongjia's blog"

  • Small partners like bloggers can add a concern, a point like oh, continuously updated hey!

Published 397 original articles · won praise 973 · views 90000 +

Guess you like

Origin blog.csdn.net/Mrs_chens/article/details/103874920