Moment For Technology

Spring Cloud Alibaba's service registration and configuration center Nacos

Posted on June 26, 2022, 10:40 p.m. by Ivana Saha
Category: The back-end Tag: The back-end

An overview,

  • Nacos, the first two letters of Naming and Configuration, and the last s of Service.
  • Nacos does service registration and configuration. Configuration changes can also be notified dynamically to clients. Therefore Nacos = Eureka + Config + Bus.
  • Github, official docs, official docs

Second, the installation

  • Nacos is the Java code at the bottom, and the server is already wrapped up and can be downloaded directly to run, download the address
  • After downloading, you can directly go to the bin directory and run the script. (Bat script for Windows, shell script for Linux)
  • Execute standalone versionstartup.cmd -m standalone
  • After the operation is successful, you can open the page for monitoring web pages.http://localhost:8848/nacos

Nacos as a service registry

1. The package

  • First, you can import the Spring Cloud Alibaba package into the parent POM, which contains all the packages for the Spring Cloud Alibaba ecosystem
dependency
    groupIdcom.alibaba.cloud/groupId
    artifactIdspring-cloud-alibaba-dependencies/artifactId
    version2.1.0. RELEASE/version
    typepom/type
    scopeimport/scope
/dependency
Copy the code
  • Import the registered package. The service invocation and the package provided by the service are the same.
dependencies
    ! --nacos-discovery--
    dependency
        groupIdcom.alibaba.cloud/groupId
        artifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactId
    /dependency
    ! --web + actuator--
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-web/artifactId
    /dependency
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-actuator/artifactId
    /dependency
    ! -- Basic configuration --
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-devtools/artifactId
        scoperuntime/scope
        optionaltrue/optional
    /dependency
    dependency
        groupIdorg.projectlombok/groupId
        artifactIdlombok/artifactId
        optionaltrue/optional
    /dependency
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-test/artifactId
        scopetest/scope
    /dependency
/dependencies
Copy the code

2. Configuration file provided by the service

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 Configure the Nacos address

management:
  endpoints:
    web:
      exposure:
        include: The '*'
Copy the code

3. The main startup class provided by the service

  • @EnableDiscoveryClientOpen registration
@EnableDiscoveryClient
@SpringBootApplication
public class PaymentMain9001 {
    public static void main(String[] args) { SpringApplication.run(PaymentMain9001.class, args); }}Copy the code

4. Business classes provided by the service

@RestController
@Slf4j
public class PaymentController {
  @Value("${server.port}")
  private String serverPort;

  @GetMapping(value = "/payment/nacos/{id}")
  public String getPayment(@PathVariable("id") Integer id) {
    String result = "nacos registry, serverPort: " + serverPort + "\t id" + id;
    log.info(result);
    returnresult; }}Copy the code

5. Configuration file for service invocation

  • This is basically the same as the service provider's configuration file. The bottom configuration is a self-defined call URL that uses the service you want to call as the URL
server:
  port: 83


spring:
  application:
    name: nacos-order-consumer
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848


The name of the microservice that the consumer is going to access (the microservice provider that successfully registered with NACOS)
service-url:
  nacos-user-service: http://nacos-payment-provider 
Copy the code

6. Main startup class for service invocation

@EnableDiscoveryClient
@SpringBootApplication
public class OrderNacosMain83
{
    public static void main(String[] args)
    { SpringApplication.run(OrderNacosMain83.class,args); }}Copy the code

7. Business class for service invocation

  • It's worth noting that the NacOS package includes the Ribbon, so the service can be invoked in the same way as before.
@Configuration
public class Config {
  @Bean
  @LoadBalanced
  public RestTemplate getRestTemplate(a) {
    return newRestTemplate(); }}Copy the code
@RestController
@Slf4j
public class OrderNacosController {
  @Autowired
  private RestTemplate restTemplate;
  @Value("${service-url.nacos-user-service}")
  private String serverURL;

  @GetMapping("/consumer/payment/nacos/{id}")
  public String paymentInfo(@PathVariable("id") Long id) {
    return restTemplate.getForObject(serverURL + "/payment/nacos/"+ id, String.class); }}Copy the code

Test 8.

  • The service caller will call the service provider as usual.
  • Service providers can be replicated to test load balancing. Tests show that the polling load balancing policy is used by default.
  • You can also see the registered service in the monitoring screen.

9. Comparison of various registries

  • In fact, Nacos supports switching between AP and CP.
  • If no storage service level information is required and the service instance is registered with nacOS-Client and can maintain heartbeat reporting, the AP mode can be selected. Current mainstream services, such as Spring Cloud and Dubbo services, are applicable to AP mode. AP mode reduces consistency for the possibility of service, so only temporary instances can be registered in AP mode.
  • If you need to edit or store configuration information at the service level, CP is required, and THE K8S service and DNS service are suitable for CP mode. In CP mode, persistent instances can be registered and Raft protocol is used as the cluster mode. In this mode, services must be registered before instances are registered. If the service does not exist, an error is returned.
  • Switch commandcurl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches? entry=serverModevalue=CP'

4. Nacos serves as the service configuration center

1. The package

  • Import the nacos-config package and also import the service discovery package.
dependencies
    ! --nacos-config--
    dependency
        groupIdcom.alibaba.cloud/groupId
        artifactIdspring-cloud-starter-alibaba-nacos-config/artifactId
    /dependency
    ! --nacos-discovery--
    dependency
        groupIdcom.alibaba.cloud/groupId
        artifactIdspring-cloud-starter-alibaba-nacos-discovery/artifactId
    /dependency
    ! --web + actuator--
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-web/artifactId
    /dependency
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-actuator/artifactId
    /dependency
    ! -- Basic configuration --
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-devtools/artifactId
        scoperuntime/scope
        optionaltrue/optional
    /dependency
    dependency
        groupIdorg.projectlombok/groupId
        artifactIdlombok/artifactId
        optionaltrue/optional
    /dependency
    dependency
        groupIdorg.springframework.boot/groupId
        artifactIdspring-boot-starter-test/artifactId
        scopetest/scope
    /dependency
/dependencies
Copy the code

2. Configuration file

  • As stated in Spring Cloud Config,bootstrap.ymlIs of higher priority thanapplication.ymlTherefore, the configuration content imported from the configuration center is generally stored in thebootstrap.ymlFile.
# nacos configuration
server:
  port: 3377

spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos service registry address
      config:
        server-addr: localhost:8848 #Nacos as the configuration center address
        file-extension: yaml # specify yamL configuration

This is the naming convention for DataId, which maps to the contents of the configuration file to select the actual configuration file in the configuration center.
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
Copy the code
  • inapplication.yml, select the development environment.
spring:
  profiles:
    active: dev # indicates the development environment
Copy the code

3. Main startup class

@EnableDiscoveryClient
@SpringBootApplication
public class NacosConfigClientMain3377 {
    public static void main(String[] args) { SpringApplication.run(NacosConfigClientMain3377.class, args); }}Copy the code

4. Business class

  • As you can see, there is no difference from the previous Spring Cloud Config call. I need to put one on top of the class@RefreshScopeAnnotations to indicate that the current configuration can be refreshed dynamically.
@RestController
@RefreshScope // Add the @refreshScope annotation to the controller class to enable Nacos dynamic refresh in the configuration of the current class.
public class ConfigClientController {
    @Value("${config.info}")
    private String configInfo;

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

5. Configure the center

  • The configuration center stores configuration information, provides modification function, and after modification, can voluntarily provide all clients. Very convenient, solve the need for message bus, Git repository problems, direct one-stop solution. website
  • Select Config Add on the web page

  • You can then write the contents of the configuration file on it. Multiple formats are allowed.

  • It is worth mentioning that DataID is named carefully. The general format is${spring.application.name}-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}This corresponds to the local configuration file.

  • The Nacos Configuration center also has a rollback function that allows you to scroll through the history of configuration files in the last 30 days and roll back with one click. (But I have tested, there seems to be a small bug, not recommended to use)

6. Configure the center category

  • Configuration files can be distinguished by Namespace, Group, and DataID.

  • You can specify a Group when defining a configuration file using the following method. In a YAML file, you can use this Group by specifying it.

  • You can group by namespace in the following way.

5. Persistent configuration

  • website
  • The official built-in persistent database, using the embedded database Derby
  • We can modify it to use mysql as the persistent database.

1. Build database and table

  • First, find the mysql script in the conf foldernacos-mysql.sqlAnd run on the database. (It's worth noting that the script doesn't have a library command, so it's best to add one yourself.)

2. Modify the configuration file

  • Find it in the conf folderapplication.propertiesFile and add configuration for database connection at the end.
spring.datasource.platform=mysql
 
db.num=1
db.url.0=JDBC: mysql: / / 127.0.0.1:3306 / nacos_config? characterEncoding=utf8connectTimeout=1000socketTimeout=3000autoReconnect=true
db.user=Root # could be db.user.0, it depends
db.password=Db.password. 0 = 123456
Copy the code

3. Start

  • When you start Nacos, you'll find that everything is gone because you're now in a new database.
  • Add the configuration file. If data is added to the database, the modification is successful.
  • If the version of the database is incorrect, an error may be reported. It is best to check the version of the database connection driver currently in use. If not, you can try to change it. Come on...

6. Cluster configuration

  • The structure is as above. Load balancing via Nginx, pointing to Nacos clusters.

1. Modify the configuration file

  • Under conf, there is onecluster.conf.exampleFile, make a copy of it and call itcluster.confAnd modify it. Put in the IP and port number of the cluster.

2. Open

  • Then you can try to turn it on.
Search
About
mo4tech.com (Moment For Technology) is a global community with thousands techies from across the global hang out!Passionate technologists, be it gadget freaks, tech enthusiasts, coders, technopreneurs, or CIOs, you would find them all here.