导入maven坐标
<dependencies>
<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>
编写代码
package com.edu.www;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ConfigurableApplicationContext;
@SpringBootApplication
@EnableDiscoveryClient
public class DemoConsulApplication {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(DemoConsulApplication.class, args);
String username = context.getEnvironment().getProperty("username");
System.out.println(username);
}
}
Consul编写配置文件
配置文件根目录
各环境配置文件夹
各环境配置文件
编写bootstrap.yml配置文件
server:
port: 6666
spring:
application:
name: consu-config-demo
cloud:
consul:
host: localhost
port: 8500
config:
enabled: true
prefix: config
default-context: orderService
profile-separator: '-'
format: yaml
data-key: orderServiceConfig
watch:
enabled: true
delay: 1000
discovery:
register: true
instance-id: ${spring.application.name}-01
service-name: ${spring.application.name}
port: ${server.port}
prefer-ip-address: true
ip-address: ${spring.cloud.client.ip-address}
编写properties文件配置类
package com.edu.www.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "mysql")
@Data
public class MysqlConfigProperties {
private String host;
}
测试代码
package com.edu.www.controller;
import com.edu.www.config.MysqlConfigProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RefreshScope
public class ConfigController {
@Autowired
MysqlConfigProperties configurationProperties;
@GetMapping("config")
public MysqlConfigProperties config() {
return configurationProperties;
}
@GetMapping("/actuator/health")
public String health() {
return "ok";
}
}