之前有几篇博客介绍了consul和springboot1.x,对于consul的下载,安装配置不懂的可以看看

地址:

Consul1-window安装consul

Consul2-使用consul作为服务注册和发现中心

Consul3-使用consul作为配置中心

Consul4-linux安装consul以及集群搭建

 

由于consul已经发行了行的版本,springboot2的改动也比较大,所以本篇介绍springboot2使用consul做为配置中心的使用。

一,下载安装consul

      下载地址:https://www.consul.io/downloads.html

 

二,启动consul

写一个bat脚本用来启动consul

建立一个bat文件,consul_start.bat

内如如下:

title consul
echo start..............................
d:
cd D:\consul_1.6.0_windows_amd64
consul agent -dev
echo end.......................
pause

 

上面是已开发者模式启动的,只是为了测试使用,填好文件的内容以后,保存,双击启动,打开浏览器输入:http://localhost:8500,出现如下图,则表示启动成功

刚启动你的可能没有上面那么多节点的,只有一个consul默认的

创建一个数据节点,后面会用到,数据内容如下:

student:
  name: jack3
  age: 20
name: tom

数据节点是:jack/consul4/data

 

 

三,创建一个springboot项目

1,pom.xml如下

<?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>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.6.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.jack</groupId>
	<artifactId>consul4</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>consul4</name>
	<description>Demo project for Spring Boot</description>

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

	<dependencies>
		<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.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-actuator</artifactId>
		</dependency>



		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.45</version>
		</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>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

 

2,主类代码如下

package com.jack.consul4;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients

public class Consul4Application implements CommandLineRunner {

	@Value("${name}")
	private String name;

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

	@Override
	public void run(String... args) throws Exception {
		System.out.println("Consul4Application.....启动成功"+name);
	}
}

 

3,在resource目录下创建bootstrap.yml文件

内容如下:

server:
  port: 8081
spring:
  application:
    name: consul4
  cloud:
    consul:
    #配置consul服务器的host
      host: localhost
      #配置端口
      port: 8500
      config:
      #配置默认文件名
        default-context: ${spring.application.name}
        #是否启用consul配置
        enabled: true
        #配置文件格式
        format: YAML
        #配置基本文件,默认值config
        prefix: jack
        #配置文件名,默认data
        data-key: data
      discovery:
      #是否启用服务发现
        enabled: true
        #配置健康检查路径
        health-check-path: /actuator/health
        #配置健康检查时间间隔
        health-check-interval: 15s
        #配置实例id
        instance-id: ${spring.application.name}:${vcap.application.instance_id:${spring.application.instance_id:${random.value}}}
        #配置服务注册
        register: true
        #服务停止时取消注册,http://www.imooc.com/article/286883?block_id=tuijian_wz
        deregister: true
        #表示注册时使用ip而不是hostname
        prefer-ip-address: true
        #健康检查失败多长时间取消注册
        health-check-critical-timeout: 30s
  profiles:
    active: dev

顺便创建application.yml和application-dev.yml文件,内如为空就行,在实际项目中可以存放其他的配置内容

 

4,创建一个学生配置类

用于读取consul中的配置,eg:

package com.jack.consul4.config;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * create by jack 2019/9/3
 *
 * @author jack
 * @date: 2019/9/3 20:15
 * @Description:
 */
@Component
@ConfigurationProperties(prefix = "student")
@Data
public class StudentConfig {
    private String name;
    private Integer age;
}

 

5,创建一个测试的controller

代码如下:

package com.jack.consul4.controller;

import com.alibaba.fastjson.JSONObject;
import com.jack.consul4.config.StudentConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * create by jack 2019/9/3
 *
 * @author jack
 * @date: 2019/9/3 20:17
 * @Description:
 */
@RestController
@RequestMapping("test")
public class TestController {
    @Autowired
    private StudentConfig studentConfig;
    @RequestMapping("test1")
    public String test1(){
        return JSONObject.toJSONString(studentConfig);
    }
}

 

6,启动测试

1)启动应用程序

启动应用程序输出如下内容:

2019-09-03 21:18:38.282  INFO 4496 --- [           main] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='consul', propertySources=[ConsulPropertySource {name='jack/consul4,dev/'}, ConsulPropertySource {name='jack/consul4/'}]}
2019-09-03 21:18:38.286  INFO 4496 --- [           main] com.jack.consul4.Consul4Application      : The following profiles are active: dev
2019-09-03 21:18:38.886  WARN 4496 --- [           main] o.s.boot.actuate.endpoint.EndpointId     : Endpoint ID 'service-registry' contains invalid characters, please migrate to a valid format.
2019-09-03 21:18:39.063  INFO 4496 --- [           main] o.s.cloud.context.scope.GenericScope     : BeanFactory id=d2cdbbf5-0779-3407-8675-8c291c9397fa
2019-09-03 21:18:39.130  INFO 4496 --- [           main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$5a06c53f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-03 21:18:39.415  INFO 4496 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat initialized with port(s): 8081 (http)
2019-09-03 21:18:39.435  INFO 4496 --- [           main] o.apache.catalina.core.StandardService   : Starting service [Tomcat]
2019-09-03 21:18:39.435  INFO 4496 --- [           main] org.apache.catalina.core.StandardEngine  : Starting Servlet engine: [Apache Tomcat/9.0.21]
2019-09-03 21:18:39.609  INFO 4496 --- [           main] o.a.c.c.C.[Tomcat].[localhost].[/]       : Initializing Spring embedded WebApplicationContext
2019-09-03 21:18:39.609  INFO 4496 --- [           main] o.s.web.context.ContextLoader            : Root WebApplicationContext: initialization completed in 1312 ms
2019-09-03 21:18:39.747  WARN 4496 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-09-03 21:18:39.747  INFO 4496 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-09-03 21:18:39.760  INFO 4496 --- [           main] c.netflix.config.DynamicPropertyFactory  : DynamicPropertyFactory is initialized with configuration sources: com.netflix.config.ConcurrentCompositeConfiguration@7cdbaa50
2019-09-03 21:18:40.400  WARN 4496 --- [           main] c.n.c.sources.URLConfigurationSource     : No URLs will be polled as dynamic configuration sources.
2019-09-03 21:18:40.400  INFO 4496 --- [           main] c.n.c.sources.URLConfigurationSource     : To enable URLs as dynamic configuration sources, define System property archaius.configurationSource.additionalUrls or make config.properties available on classpath.
2019-09-03 21:18:40.529  INFO 4496 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Initializing ExecutorService 'applicationTaskExecutor'
2019-09-03 21:18:40.799  INFO 4496 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'catalogWatchTaskScheduler'
2019-09-03 21:18:41.164  INFO 4496 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Initializing ExecutorService 'configWatchTaskScheduler'
2019-09-03 21:18:41.196  INFO 4496 --- [           main] o.s.b.a.e.web.EndpointLinksResolver      : Exposing 2 endpoint(s) beneath base path '/actuator'
2019-09-03 21:18:41.369  INFO 4496 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8081 (http) with context path ''
2019-09-03 21:18:41.392  INFO 4496 --- [           main] o.s.c.c.s.ConsulServiceRegistry          : Registering service with consul: NewService{id='consul4-e404464d40367813c64555df0869980f', name='consul4', tags=[secure=false], address='192.168.0.102', meta=null, port=8081, enableTagOverride=null, check=Check{script='null', interval='15s', ttl='null', http='http://192.168.0.102:8081/actuator/health', method='null', header={}, tcp='null', timeout='null', deregisterCriticalServiceAfter='30s', tlsSkipVerify=null, status='null'}, checks=null}
2019-09-03 21:18:41.410  INFO 4496 --- [           main] com.jack.consul4.Consul4Application      : Started Consul4Application in 5.447 seconds (JVM running for 6.358)
Consul4Application.....启动成功tom

 

上面主要输出了读取consul哪些配置文件的信息以及输出了一个配置的字段name

 

2)测试

1,使用postman或者浏览器,输入http://localhost:8081/test/test1,返回如下内如:

{"age":20,"name":"jack3"}

 

2,在consul上修改学生配置的内容,然后保存,修改后的内容如下

student:
  name: jack4
  age: 21
name: tom

保存的时候,控制台日志输出了如下内如:

2019-09-03 21:22:40.640  INFO 4496 --- [TaskScheduler-1] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$5a06c53f] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2019-09-03 21:22:40.931  INFO 4496 --- [TaskScheduler-1] b.c.PropertySourceBootstrapConfiguration : Located property source: CompositePropertySource {name='consul', propertySources=[ConsulPropertySource {name='jack/consul4,dev/'}, ConsulPropertySource {name='jack/consul4/'}]}
2019-09-03 21:22:40.932  INFO 4496 --- [TaskScheduler-1] o.s.boot.SpringApplication               : The following profiles are active: dev
2019-09-03 21:22:40.939  INFO 4496 --- [TaskScheduler-1] o.s.boot.SpringApplication               : Started application in 0.631 seconds (JVM running for 245.888)
2019-09-03 21:22:41.021  INFO 4496 --- [TaskScheduler-1] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [student.name, student.age]

在次使用http://localhost:8081/test/test1请求,返回如下内如:

{"age":21,"name":"jack4"}

 

  可见,我们没有启动应用程序,通过在consul上修改配置,应用程序的内容就发生变更了

 

总结:

     1,在bootstrap.yml文件中应用程序名配置错误了,导致和consul上配置的不一致,consul上设置的值读取不到

     2,要使consul配置的内容能更新到应用程序,需要封装一个类,使用下面的注解

          @Component
         @ConfigurationProperties(prefix = "student")

         或者去掉上面的@Component,在主类上使用

@EnableConfigurationProperties({StudentConfig.class})//指定配置类

欢迎加群学习交流:331227121

源码:源码

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Logo

更多推荐