SpringBoot e-Commerce project mall (20K + STAR) address: github.com/macrozheng/…

Abstract

Spring Cloud Alibaba is committed to providing a one-stop solution for microservice development. As one of its core components, Nacos can be used as a registry and configuration center. This article will introduce its usage in detail.

Nacos profile

Nacos is dedicated to helping you discover, configure, and manage microservices. Nacos provides an easy-to-use feature set that helps you quickly implement dynamic service discovery, service configuration, service metadata, and traffic management.

Nacos has the following features:

  • Service discovery and service health monitoring: support DNS and RPC-based service discovery, support real-time health check of services, prevent requests to unhealthy hosts or service instances;
  • Dynamically configured services: Dynamically configured services allow you to manage application and service configurations for all environments in a centralized, external, and dynamic manner.
  • Dynamic DNS service: The dynamic DNS service supports weighted routing, enabling you to implement load balancing at the middle layer, flexible routing policies, traffic control, and simple DNS resolution services on the data center Intranet.
  • Services and metadata management: Support the management of all services and metadata in the data center from the perspective of micro-service platform construction.

Use Nacos as the registry

Install and run Nacos

  • Download Nacos from nacos-server-1.1.4.zip: github.com/alibaba/nac…

  • Configure the JAVA_HOME environment variable. If it is not configured, Nacos will not run.

JAVA_HOME = D: \ developer \ env \ Java \ jdk1.8.0 _91Copy the code
  • Decompress the installation package and run startup. CMD in the bin directory.

  • After the success of the operation, visit http://localhost:8848/nacos to view Nacos home page, the default password is Nacos.

Create an application to register with Nacos

We demonstrate service registration and discovery by adapting Consul user-Service and Consul ribbon service to apply Nacos registry support instead of consul registry support.

  • Create nacOS-user-Service module and nacOS-ribbon service module;

  • To use Spring Cloud Alibaba components, add the following configuration to POM.xml;

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2.1.0. RELEASE</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code
  • }}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}}
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
  • Modify the profile application.yml to change Consul’s registration discovery configuration to Nacos’s:
server:
  port: 8206
spring:
  application:
    name: nacos-user-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 Configure the Nacos address
management:
  endpoints:
    web:
      exposure:
        include: The '*'
Copy the code
  • Run two nacos-user-services and one nacos-ribbon-service. You can see the following information on the NACOS page:

Load balancing function

Since we run two nacos-user-Services and nacos-ribbon service calls its interface by default, we call the interface of nacos-ribbon Service to demonstrate load balancing.

Many times call interface: http://localhost:8308/user/1, you can find two nacos – user – service console alternate print the following information.

The 2019-11-06 14:28:06. 12092-458 the INFO [nio - 8207 - exec - 2] c. acro. Cloud. Controller. UserController: Get user information based on id. The user name is macroCopy the code

Use Nacos as the configuration center

We demonstrate configuration management by creating the nacos-config-client module and adding configuration information to the NACOS page.

Create the nacos-config-client module

  • Add dependencies to pom.xml:
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code
  • Add the configuration file application.yml to enable the dev environment configuration:
spring:
  profiles:
    active: dev
Copy the code
  • Add the configuration file bootstrap.yml, which mainly configures the function of Nacos as the configuration center:
server:
  port: 9101
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 # Nacos address
      config:
        server-addr: localhost:8848 # Nacos address
        file-extension: yaml Here we get the configuration in YAML format
Copy the code
  • Create the ConfigClientController and get the configuration information from the Nacos configuration center:
/** * Created by macro on 2019/9/11. */
@RestController
@RefreshScope
public class ConfigClientController {

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

    @GetMapping("/configInfo")
    public String getConfigInfo(a) {
        returnconfigInfo; }}Copy the code

Add the configuration in Nacos

  • Let’s first talk about the composition format of datAID in Nacos and the corresponding relationship with the properties in SpringBoot configuration file:
${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
Copy the code
  • Let’s say we now want to get the application namenacos-config-clientThe application of thedevUnder the environment ofyamlConfigure datAID as follows:
nacos-config-client-dev.yaml
Copy the code
  • Add the following configuration according to the above datAID:
config:
  info: "config info for dev"
Copy the code
  • Fill in the configuration diagram:

  • Start nacos – config – client, call interface to view configuration information: http://localhost:9101/configInfo
config info for dev
Copy the code

Dynamic refresh configuration of Nacos

We only need to modify the configuration information in Nacos and call the interface to view the configuration again to find that the configuration has been refreshed. Nacos supports dynamic configuration refresh like Consul. When we change the configuration on the Nacos page and publish it, the application refreshes the configuration and prints the following information

2019-11-06 14:50:49.460  INFO 12372 --- [-localhost_8848] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$ec395f8e] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible forAuto - proxying) 14:50:49 2019-11-06. 12372-608 the INFO / - localhost_8848 C.A.C.N.C.N acosPropertySourceBuilder: Loading nacos data, dataId:'nacos-config-client-dev.yaml', group: 'DEFAULT_GROUP'The 2019-11-06 14:50:49. 12372-609 the INFO / - localhost_8848 B.C.P ropertySourceBootstrapConfiguration: Located propertysource: CompositePropertySource {name='NACOS', propertySources=[NacosPropertySource {name='nacos-config-client-dev.yaml'}, NacosPropertySource {name='nacos-config-client.yaml'}}] 14:50:49 2019-11-06. 12372-610 the INFO / - localhost_8848 O.S.B oot. SpringApplication: The following profiles are active: Dev 14:50:49 2019-11-06. 12372-620 the INFO / - localhost_8848 O.S.B oot. SpringApplication: Started applicationin0.328 seconds (JVM is runningfor172.085) the 2019-11-06 14:50:49. 12372-638 the INFO / - localhost_8848 O.S.C.E.E vent. RefreshEventListener: Refresh keys changed: [config.info]Copy the code

The resources

Spring Cloud Alibaba official documentation: github.com/alibaba/spr…

The module used

Springcloud - learning ├ ─ ─ nacos -config-client The NACOS client used to demonstrate NACOS as a configuration hub├ ─ ─ nacos - user - serviceA service registered with NACOS that provides the CRUD interface to the User object└ ─ ─ nacos - ribbon - serviceRegister with nacOS's Ribbon service to invoke the test service
Copy the code

Project source code address

Github.com/macrozheng/…

The public,

Mall project full set of learning tutorials serialized, attention to the public number the first time access.