SpringCloud Consul Config Configuration Center (1)

Consul is used to store key-value pairs to realize a distributed configuration center, and it supports the ability to read updated attributes without restarting the configuration center service.

On the basis of the previous development, a slight adjustment is made, and only the log service is adjusted temporarily.

1. Add maven dependency in log service

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-cloud-starter-consul-config</artifactId>
</dependency>

2. Adjust the configuration file, remove the port number, and the last two lines cannot be less, otherwise an error will be reported

spring:
  application:
    name: logservice
  profiles:
    active: dev
  cloud:
    consul:
      host: localhost
      port: 8500
      discovery:
        service-name: logservice
      config:
        enabled: true
        format: yaml
        prefixes: config
        defaultContext: application
        profileSeparator: ','
        data-key: data
  config:
    import: optional:consul:localhost:8500

3. Add key-value pairs on the Consul management page,

Click the Key/value menu, and then click the create button, the following page pops up:

Need to fill in two places,

The first place: key or folder text box:

This place is very critical and needs to be consistent with the configuration file, written here as:

config/application,dev/data

Consistent with several places in the configuration file:

prefixes: config
defaultContext: application
profileSeparator: ','
data-key: data

The second place, the value part, because the setting format in the configuration file is yaml, add several attribute values ​​as follows:

server:
  port: 8081
log:
  test: hello

Then click the save button to save. If there is no problem, it will prompt Success! Your key has been saved.

4. Start the log service and no error is reported, indicating that the configuration is successful.

5. Access the log service, http://localhost:8081/log , the port number has been read from the configuration center to take effect.

6. Add an API interface to the log service,

@Value("${log.test}")
String hello;

@GetMapping("/data")
public String data() {
    return hello;
}

7. The browser accesses the interface, http://localhost:8081/ data, and returns hello, indicating that the reading from the configuration center is successful.

8. By adding the following annotations to the Controller class of the API interface, after the attribute configuration is updated, it will take effect without restarting the configuration service.

@RefreshScope

 

 

Guess you like

Origin blog.csdn.net/suoyx/article/details/115015926