This is the 20th day of my participation in the August More Text Challenge

I. Service registration –ProviderSet up

Nacos Docker startup, version 1.3.2 Spring Boot version 2.2.1.RELEASE Spring Cloud Alibaba version 2.2.0.release

  1. pom.xml
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId>  </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</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-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>${spring-cloud-alibaba.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement>Copy the code
  1. The configuration file
Spring. The application. The name = my - the provider for server port = 8080 spring. Cloud. Nacos. Discovery. The server - addr = 192.168.226.36:8848Copy the code
  1. code
@SpringBootApplication public class NacosProviderApplication { public static void main(String[] args) { SpringApplication.run(NacosProviderApplication.class, args); } @RestController class EchoController { @GetMapping("/echo") public String echo(HttpServletRequest request) { return "echo: " + request.getParameter("name"); }}}Copy the code

After the startup, the service is normal.

You can view Nacos, service discovery, as shown:




Ii. Service discovery –ConsumerSet up

  1. pomConfiguration, asprovider
  1. The configuration file
spring.application.name=nacos-consumer
server.port=8081
spring.cloud.nacos.discovery.server-addr=localhost:8848
Copy the code
  1. code
@SpringBootApplication @EnableDiscoveryClient(autoRegister = false) // Set not to automatically register with the registry public class NacosConsumerApplication { public static void main(String[] args) { SpringApplication.run(NacosConsumerApplication.class, args); } @Bean public RestTemplate restTemplate() { return new RestTemplate(); } @RestController class HelloController { @Autowired private DiscoveryClient discoveryClient; @autoWired private RestTemplate RestTemplate; private String serviceName = "my-provider"; @getMapping ("/info") public String info() {// Use DiscoveryClient to obtain all instances of the My-Provider service. serviceInstances = discoveryClient.getInstances(serviceName); StringBuilder sb = new StringBuilder(); sb.append("All services: " + discoveryClient.getServices() + "<br/>"); sb.append("my-provider instance list: <br/>"); serviceInstances.forEach(instance -> { sb.append("[ serviceId: " + instance.getServiceId() + ", host: " + instance.getHost() + ", port: " + instance.getPort() + " ]"); sb.append("<br/>"); }); return sb.toString(); } @GetMapping("/hello") public String hello() { List<ServiceInstance> serviceInstances = discoveryClient.getInstances(serviceName); ServiceInstance serviceInstance = serviceInstances.stream() .findAny().orElseThrow(() -> new IllegalStateException("no "  + serviceName + " instance available")); return restTemplate.getForObject( "http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/echo? name=nacos", String.class); }}}Copy the code

Go to http://localhost:8081/info:

All services: [my-provider] my-provider instance list: [serviceId: my-provider, host: 192.168.226.36, port: 8080]Copy the code

Go to http://localhost:8081/hello:

echo: nacos
Copy the code




Three, configuration management –ProviderSet up

On the basis of the first service-provider construction, set up.

  1. pom.xmladd
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>
Copy the code
  1. inresourcesaddbootstrap.properties
spring.application.name=my-provider
server.port=8080
spring.cloud.nacos.config.server-addr=192.168.226.36:8848
spring.cloud.nacos.discovery.server-addr=192.168.226.36:8848
Copy the code
  1. inNacosProviderApplication.javaAdd code to
@SpringBootApplication
public class NacosProviderApplication {
​
    public static void main(String[] args) {
        SpringApplication.run(NacosProviderApplication.class, args);
    }
​
    @RestController
    class EchoController {
​
        @Autowired
        ApplicationContext applicationContext;
​
        @GetMapping("/echo")
        public String echo(HttpServletRequest request) {
            return "echo: " + request.getParameter("name");
        }
​
        // Add the following
        @GetMapping("/config")
        public String config(a) {
​
            return "env.get('book.category')=" +
                    applicationContext.getEnvironment().getProperty("book.category"."unknown"); }}}Copy the code
  1. inNacosCreate a new configuration and publish it. As shown in figure:

The service is started and running properly.

http://localhost:8080/config:

env.get('book.category')=spring cloud
Copy the code

Modify the configuration files in the Nacos, visit http://localhost:8080/config:

You can see that the configuration is dynamically updated.

env.get('book.category')=spring cloud nacos
Copy the code

The bootstrap.properties file, which configures the address of the Nacos configuration center, will have Spring Cloud start the Bootstrap phase to get the configuration from the Nacos configuration center.

Spring Cloud Bootstrap Phase concepts:

During the Bootstrap phase, the ApplicationContext is constructed, This ApplicationContext loads the configuration based on the bootstrap.properties or bootstrap.yaml file (spring.config.name is bootstrap). During file loading, Spring Cloud has a mechanism (defined by the PropertySourceLocator interface) to construct the source PropertySource, and the rest is consistent with Spring Boot.

The ApplicationContext constructed in the BootStrap phase acts as the parent of the normal phase’s ApplicationContext. If you cannot retrieve the configuration from the child ApplicationContext, It gets it from the parent ApplicationContext.

The Spring Cloud Bootstrap phase has a high priority. The Spring Cloud Bootstrap phase reads the configuration center configuration first, which will take effect the next time the normal ApplicationContext starts.

The meta-INF /spring.factories inside the spring-Cloud-context module adds a bootstrap-ApplicationListener. Listens for ApplicationEnvironmentPreparedEvent events (just create the Environment, no create ApplicationContext to trigger events), received after the incident has entered into the phase of the Bootstrap, Loads the configuration from the configuration center.