[Spring Cloud Alibaba reviews the past and knows the new] Alibaba Nacos

catalogue

4.1.1 basic architecture and concept of Alibaba Nacos

  • Alibaba Nacos basic architecture

    • Service, configuration service, name service
  • Interpretation of Alibaba Nacos concept

    • Service registry: it is the database of services, instances and metadata; The service registry may call the health check API of the service instance to verify that it can handle the request
    • Service metadata: includes service endpoints, service tags, service version numbers, service instance weights, routing rules, security policies and other data describing services
    • Service provider and consumer: the application that provides reusable and callable services; The application party that will initiate the call to a service
    • Configuration: in the process of system development, some parameters and variables that need to be changed are usually separated from the code for independent management and exist in the form of independent configuration files

4.1.2 Alibaba Nacos stand-alone deployment (Linux version)

4.1.2.1 downloading and running Nacos

  • Stand alone version deployment steps
    • Download the version you need (latest)
      • https://github.com/alibaba/nacos/releases/
      • tar -zxvf nacos-server-2.0.3.tar.gz
      • Stand alone mode startup (default configuration)
[root@localhost bin]# ./startup.sh -m standalone
/usr/local/java/bin/java -Djava.ext.dirs=/usr/local/java/jre/lib/ext:/usr/local/java/lib/ext  -Xms512m -Xmx512m -Xmn256m -Dnacos.standalone=true -Dnacos.member.list= -Xloggc:/opt/nacos/logs/nacos_gc.log -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=10 -XX:GCLogFileSize=100M -Dloader.path=/opt/nacos/plugins/health,/opt/nacos/plugins/cmdb -Dnacos.home=/opt/nacos -jar /opt/nacos/target/nacos-server.jar  --spring.config.additional-location=file:/opt/nacos/conf/ --logging.config=/opt/nacos/conf/nacos-logback.xml --server.max-http-header-size=524288
nacos is starting with standalone
nacos is starting,you can check the /opt/nacos/logs/start.out

Then, visit http://192.168.3.250:8848/nacos connection failed

View log / opt/nacos/logs/start.out

cksdbjni5856883071013166985.so: libstdc++.so.6: cannot open shared object file: No such file or directory

Perform installation resolution

yum install libstdc++.i686

4.1.2.2 Web presentation

visit http://192.168.3.250:8848/nacos

Initial account: nacos/nacos

Create SCA commerce namespace

4.1.3 Nacos configuring custom MySQL persistence

  • Modify the configuration and specify MySQL address, user name and port number

4.1.3.1 preparing MySQL database

  • Install docker & docker compose
  • Run docket compose
  • Log in to the container and change the root password

reference resources: https://hub.docker.com/_/mysql

It's not the special content here, so post the following steps:

# Enter mysql container
docker exec -it mysql bash 

# Log in to mysql. The first password is empty. Enter directly
mysql -uroot -p

# mysql8 change password
use mysql; 
update user set authentication_string='' where user='root';
ALTER user 'root'@'localhost' IDENTIFIED BY '123456';

# Modifying the account is not allowed to log in remotely, but only in localhost. At this time, just log in to mysql on the computer of localhost and change the "host" item in the "user" table in the "mysql" database from "localhost" to "%"
select host from user where user='root';
update user set host = '%' where user ='root';
flush privileges;

I have tried to start mysql:8 when deploying on a single machine. An error will be reported in the cluster mode. It is recommended to use MySQL 5.7

4.1.3.2 modify the Nacos configuration and specify MySQL persistence

vim /opt/nacos/conf/application.properties

#*************** Config Module Related Configurations ***************#
### If use MySQL as datasource:
spring.datasource.platform=mysql

### Count of DB:
db.num=1

### Connect URL of DB:
db.url.0=jdbc:mysql://127.0.0.1:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true&useUnicode=true&useSSL=false&serverTimezone=UTC
db.user.0=root
db.password.0=123456

4.1.3.3 running SQL statements

Nacos officials have provided us with the nacos-mysql.sql statement file

[root@localhost conf]# ll
total 88
-rw-r--r--. 1 502 games  1224 Jun 17 22:39 1.4.0-ipv6_support-update.sql
-rw-r--r--. 1 502 games  9496 Oct 27 03:11 application.properties
-rw-r--r--. 1 502 games  9506 Jul 27 02:18 application.properties.example
-rw-r--r--. 1 502 games   670 Mar 17  2021 cluster.conf.example
-rw-r--r--. 1 502 games 31156 Jul 15 07:19 nacos-logback.xml
-rw-r--r--. 1 502 games 10660 Jun 17 22:39 nacos-mysql.sql
-rw-r--r--. 1 502 games  8795 Jun 17 22:39 schema.sql

https://github.com/eddie-code/sca-commerce/blob/develop/nacos-mysql.sql

https://github.com/alibaba/nacos/blob/master/distribution/conf/nacos-mysql.sql

4.1.3.4 rerun Nacos

Start Nacos before shutting down and run Nacos again

cd /opt/nacos/bin
./shutdown.sh
./startup.sh -m standalone 

Create a new namespace and check whether it is successful

4.2.1 Alibaba Nacos cluster deployment (Linux version)

  • Steps for cluster deployment of Alibaba Nacos
    • Define the IP and port of the cluster deployment, that is, the cluster.conf file
    • The cluster must use data sources that can be accessed jointly (such as MySQL, PG, etc.) as the persistence method
    • Clustered startup has no additional parameters:. / startup.sh

At least three Nacos nodes are required

4.2.1.1 modify cluster.conf file

Copy example

cd /opt/nacos/conf/
cp cluster.conf.example cluster.conf

vim cluster.conf

192.168.3.250:8848
192.168.3.250:8858
192.168.3.250:8868

4.2.1.2 creating a Nacos node

Copy nacos folder

[root@localhost opt]# ll
total 314696
drwxr-xr-x. 7 root root        96 Oct 27 00:52 nacos
-rw-r--r--. 1 root root 117593603 Oct 27 00:49 nacos-server-2.0.3.tar.gz
[root@localhost opt]# 
[root@localhost opt]# cp -r nacos nacos-8848
[root@localhost opt]# cp -r nacos nacos-8858
[root@localhost opt]# cp -r nacos nacos-8868
[root@localhost opt]# ll
total 314696
drwxr-xr-x. 7 root root        96 Oct 27 00:52 nacos
drwxr-xr-x. 7 root root        96 Oct 27 04:30 nacos-8848
drwxr-xr-x. 7 root root        96 Oct 27 04:30 nacos-8858
drwxr-xr-x. 7 root root        96 Oct 27 04:30 nacos-8868
-rw-r--r--. 1 root root 117593603 Oct 27 00:49 nacos-server-2.0.3.tar.gz
[root@localhost opt]# 

Modify the port of application.properties

vim /opt/nacos-8858/conf/application.properties

server.port=8858

vim /opt/nacos-8868/conf/application.properties

server.port=8868

4.2.1.3 execute the startup script of three Nacos nodes

vim nacos-cluster-startup.sh

sh /opt/nacos-8848/bin/startup.sh
sh /opt/nacos-8858/bin/startup.sh
sh /opt/nacos-8868/bin/startup.sh

chmod 777 nacos-cluster-startup.sh

The same is true for closing scripts

Enter the Web to view: http://192.168.3.250:8848/nacos

4.3.1 Alibaba Nacos Client service registration and discovery

4.3.1.1 service registration

Create a Nacos Client subproject

Project Name: SCA commerce Alibaba Nacos client

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>sca-commerce</artifactId>
        <groupId>com.edcode.commerce</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>sca-commerce-alibaba-nacos-client</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <!-- Module name and description information -->
    <name>sca-commerce-alibaba-nacos-client</name>
    <description>Nacos Client</description>

    <dependencies>
        <!-- spring cloud alibaba nacos discovery rely on -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.2.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>com.edcode.commerce</groupId>
            <artifactId>sca-commerce-mvc-config</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <!--
        SpringBoot of Maven plug-in unit, Able to Maven Provide for the application SpringBoot With your support, you can
        SpringBoot The application is packaged as executable jar or war file, Then run in the usual way SpringBoot application
     -->
    <build>
        <finalName>${artifactId}</finalName>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <!-- Configure remote warehouse -->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

</project>

NacosClientApplication startup class

package com.edcode.commerce;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description Nacos Client Project start-up entrance
 */
@EnableDiscoveryClient
@SpringBootApplication
public class NacosClientApplication {

    public static void main(String[] args) {
        SpringApplication.run(NacosClientApplication.class, args);
    }

}

bootstrap.yml

server:
  port: 8000
  servlet:
    context-path: /scacommerce-nacos-client

spring:
  application:
    name: sca-commerce-nacos-client # The application name is also part of the Nacos configuration management dataId field (when config.prefix is empty)
  cloud:
    nacos:
      # Service registration discovery
      discovery:
        enabled: true # If you do not want to use Nacos for service registration and discovery, set it to false
        #server-addr: ${NACOS_ADDR:127.0.0.1}:8848
        server-addr: ${NACOS_ADDR:127.0.0.1}:8848,${NACOS_ADDR:127.0.0.1}:8849,${NACOS_ADDR:127.0.0.1}:8850 # Nacos server address
        namespace: ${NAMESPACE_ID:1adcfdd8-5763-4768-9a15-9c7157988950}

# Exposure endpoint
management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

Start the project and view the Nacos Web

4.3.1.2 service discovery

NacosClientService

package com.edcode.commerce.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description
 */
@Slf4j
@Service
public class NacosClientService {

    private final DiscoveryClient discoveryClient;

    public NacosClientService(DiscoveryClient discoveryClient) {
        this.discoveryClient = discoveryClient;
    }

    /**
     * Print Nacos Client information to log
     * @param serviceId
     * @return
     */
    public List<ServiceInstance> getNacosClientInfo(String serviceId) {
        log.info("request nacos client to get service instance info: [{}]", serviceId);
        return discoveryClient.getInstances(serviceId);
    }

}

NacosClientController

package com.edcode.commerce.controller;

import com.edcode.commerce.service.NacosClientService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author eddie.lee
 * @blog blog.eddilee.cn
 * @description
 */
@Slf4j
@RestController
@RequestMapping("/nacos-client")
@RequiredArgsConstructor
public class NacosClientController {

    private final NacosClientService nacosClientService;

    /**
     * Obtain all instance information of the service according to the service id
     */
    @GetMapping("/service-instance")
    public List<ServiceInstance> logNacosClientInfo(@RequestParam(defaultValue = "sca-commerce-nacos-client") String serviceId) {
        log.info("coming in log nacos client info: [{}]", serviceId);
        return nacosClientService.getNacosClientInfo(serviceId);
    }

}

Use IDEA or PostMan request API


Keywords: Java Back-end Spring Cloud

Added by johnthedeveloper on Thu, 28 Oct 2021 19:30:27 +0300