13. Spring cloud Alibaba Chapter 13, upgrade, service registration and configuration center Nacos

Keywords: Programming Spring Nginx Maven MySQL

Spring cloud Alibaba Chapter 12, upgrade, service registration and configuration center Nacos

1, Why spring cloud Alibaba

1. Why

With the micro service framework of spring cloud, why do you want to use the framework of spring cloud alibaba? The most important reason is spring 

Almost all components in the cloud use Netflix products, and then a layer of encapsulation is made on the basis of it, while some other frameworks are added. however

The service discovery component Eureka of Netflix has stopped updating, and Feign, Hystrix, Zuul, etc. have all entered the maintenance stage for upgrading or stopping.

So we need other alternative products urgently, namely spring cloud alibaba.

2. What can spring cloud Alibaba do

1,Nacos
Alibaba's open source product is a platform for dynamic service discovery, configuration management and service management that is easier to build cloud native applications.

2,Sentinel
Alibaba's open-source products take traffic as the entry point to protect the stability of services from multiple dimensions such as traffic control, fuse degradation, system load protection, etc.

3,RocketMQ
Apache RocketMQ Gamma Java based distributed message and flow computing platform with high performance and high throughput.

4,Dubbo
Apache Dubbo Gamma Is a high-performance Java RPC framework.

5,Seata
Alibaba open source product, an easy-to-use high-performance distributed transaction solution for microservices.

6,Alibaba Cloud OSS
Alibaba cloud Object Storage Service (OSS) is a massive, secure, low-cost, and highly reliable cloud storage provided by Alibaba cloud
Services. You can store and access any type of data in any application, at any time, anywhere.

7,Alibaba Cloud SchedulerX
A distributed task scheduling product developed by Alibaba middleware team supports periodic tasks and fixed point in time triggering tasks.

8,Alibaba Cloud SMS
The global SMS service, friendly, efficient and intelligent Internet communication capabilities help enterprises quickly build customer access channels.

3. Official website and information

https://github.com/alibaba/spring-cloud-alibaba

https://spring-cloud-alibaba-group.github.io/github-pages/greenwich/spring-cloud-alibaba.html

4. References

Reference in the total POM of cloud 2020 project:

<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>

2, Service registration and configuration center Nacos

Nacos: Dynamic Naming + Configuration Service

Nacos is the combination of registry and configuration center = = equivalent to Eureka+Config+Bus

Official website:

https://nacos.io/zh-cn/

https://nacos.io/zh-cn/docs/quick-start.html

1. Nacos download and install (Server)

nacos here is the registry Server

Download address:
https://github.com/alibaba/nacos/releases/tag/1.2.1

function:
start under bin directory after decompression

Browse:
http://localhost:8848/nacos/#/login
	Account: nacos password: nacos

2. Service registry case (client)

2.1 service provider-payment-9001

Here nacos, the registry client

New module, cloudalibaba-provider-payment-9001

<parent>
    <artifactId>cloud_2020</artifactId>
    <groupId>com.lee.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment-9001</artifactId>

POM

<?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>cloud_2020</artifactId>
        <groupId>com.lee.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-provider-payment-9001</artifactId>

    <dependencies>

        <!--nacos discovery Service discovery-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.lee.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--  web assembly -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

    </dependencies>

</project>

application.yml

server:
  port: 9001

spring:
  application:
    name: nacos-payment-provider #Service name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #nacos server address

management:
  endpoints:
    web:
      exposure:
        include: '*'

Main startup class

@SpringBootApplication
@EnableDiscoveryClient //Service discovery
public class PaymentMain9001 {

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

Business class PaymentController (read configuration information)

@RestController
@RequestMapping("/payment")
public class PaymentController {

    @Value("${server.port}")
    private String serverPort;

    @GetMapping(value = "/nacos/{id}")
    public String getPayment(@PathVariable("id") Integer id)
    {
        return "nacos registry, serverPort: "+ serverPort+"\t id"+id;
    }
}

Test:

1. Start nacos server and cloudalibaba-provider-payment-9001
2. Visit:
http://localhost:9001/payment/nacos/1
result:
nacos registry, serverPort: 9001 id1
3. Visit:
http://localhost:8848/nacos



2.2 service provider-payment-9002

For the convenience of later testing, create 9002 by imitating cloud alibaba-provider-payment-9001

<parent>
    <artifactId>cloud_2020</artifactId>
    <groupId>com.lee.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>cloudalibaba-provider-payment-9002</artifactId>

application.yml

server:
  port: 9002

spring:
  application:
    name: nacos-payment-provider #Service name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #nacos server address

management:
  endpoints:
    web:
      exposure:
        include: '*'

2.3 service consumer-order-83

New module, cloudalibaba-consumer-order-83

<parent>
    <artifactId>cloud_2020</artifactId>
    <groupId>com.lee.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>cloudalibaba-consumer-order-83</artifactId>

POM

<?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>cloud_2020</artifactId>
        <groupId>com.lee.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-consumer-order-83</artifactId>

    <dependencies>

        <!--  nacos Service discovery    -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.lee.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>

        <!--  web assembly      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

</project>

application.yml

server:
  port: 83


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

Main startup class

@SpringBootApplication
@EnableDiscoveryClient//Service discovery
public class OrderMain83 {

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

Configuration class

/**
 * Configuration class
 */
@Configuration
public class ApplicationContextConfig {


    //With this annotation, the RestTemplate has client load balancing capability - because the registry is used
    //This annotation must be added, otherwise java.net.UnknownHostException: NACOS-PAYMENT-PROVIDER
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }

}

Business

@RestController
@RequestMapping("/consumer")
public class OrderController {


    public static final String serverURL = "http://nacos-payment-provider";

    @Resource
    private RestTemplate restTemplate;

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

}

Test:

1. Start Nacos server, cloud provider-payment-9001, cloud provider-payment-9002
cloud-consumer-order-83

2. Visit: http://localhost:83/consumer/payment/nacos/1
result:
nacos registry, serverPort: 9001 id1
And G
nacos registry, serverPort: 9002 id1
Polling access

3. Visit http://localhost:8848/nacos

Conclusion: within nacos, Ribbon is integrated

2.4 comparison of registration centers

2.5. AP and CP mode switching of Nacos

CAP: C data consistency, A available write, P partition fault tolerance

Nacos defaults to AP mode, and switches as follows:

curl -X PUT '$NACOS_SERVER:8848/nacos/v1/ns/operator/switches?entry=serverMode&value=CP'

When to choose which mode:

AP mode:
If you do not need to store service level information, and the service instance is registered through Nacos client, and can keep heartbeat reporting, then select AP mode.
The current mainstream services, such as springcloud and dubbo, are all applicable to AP mode. AP mode weakens the consistency for service availability, so it only supports AP mode
Register a temporary instance.

CP mode:
If you need to edit or store the configuration information at the service level, then CP is necessary, and the K8S service and DNS service apply CP mode.
CP mode supports the registration of persistent instances. At this time, the raft protocol is used as the cluster operation mode. In this mode, the service must be registered before the instance is registered. If the service does not exist, an error will be returned.


3. Service configuration center case (client)

3.1 basic cases

Create cloudalibaba-provider-payment-9003

<parent>
    <artifactId>cloud_2020</artifactId>
    <groupId>com.lee.springcloud</groupId>
    <version>1.0-SNAPSHOT</version>
</parent>
<modelVersion>4.0.0</modelVersion>

<artifactId>cloudalibaba-provider-payment-9003</artifactId>

POM

<?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>cloud_2020</artifactId>
        <groupId>com.lee.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>cloudalibaba-provider-payment-9003</artifactId>

    <dependencies>
        <!--   nacos Configuration center     -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

        <!--  nacos Service discovery    -->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>com.lee.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>


        <!--  web assembly      -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>


        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


</project>

application.yml

server:
  port: 9003

spring:
  profiles:
    active: dev

bootstrap.yml

spring:
  application:
    name: nacos-payment-provider #Service name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Service registry address
      config:
        server-addr: localhost:8848 #Configuration center address
        file-extension: yaml #Specify configuration in yaml format

Main startup class

@SpringBootApplication
@EnableDiscoveryClient//Service discovery
public class PaymentMain9003 {

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

Business

@RestController
@RefreshScope //Realize automatic update of configuration
public class ConfigClientController {

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

    @GetMapping("/config/info")
    public String getConfigInfo() {
        return configInfo;
    }

}

3.2. Nacos adds corresponding configuration information

3.2.1 data id configuration rules

${prefix}-${spring.profile.active}.${file-extentsion}

prefix:
	The default value is: spring.application.name, which can also be configured through spring.cloud.nacos.config.prefix

spring.profile.active:
	When spring.profile.active does not exist, the corresponding connector will not exist.
	The corresponding data id splicing format is:
	${prefix}.${file-extension}

file-extension: 
	To configure the data format of the content, you can configure it through spring.cloud.nacos.config.file-extension.
	Currently only properties and yaml types are supported

3.2.2 practical operation

According to the configuration contents of bootstrap.yml and application.yml of cloudalibaba-provider-payment-9003, the configuration is as follows:

nacos-payment-provider-dev.yaml

Configuration content:

config: 
    info: "config info from nacos config center, nacos-payment-provider-dev.yaml,version:1"

3.3 test

1. Start Nacos server, cloudalibaba provider payment-9003

2. Browse: http://localhost:9003/config/info
result:
config info from nacos config center, nacos-payment-provider-dev.yaml,version:1

3. Modify the configuration file version to 2 in Nacos server

4. Browse http://localhost:9003/config/info
result:
config info from nacos config center, nacos-payment-provider-dev.yaml,version:2

Conclusion:
	nacos comes with dynamic refresh function

3.4 classification configuration

A large-scale distributed microservice system will have many microservice subprojects, and each microservice project will produce multiple operating environments: development environment, test environment, formal environment, etc.

So how to manage these micro service configurations?

nacos manages different development environments and microservices through namespace+groupID+dataId

namespace: divide deployment environment DEV\TEST\PROD, etc., default PUBLIC
Group: divide microservice items, such as order user cms, etc., default default group
dataID as the above naming rule

Related configuration:

spring:
  application:
    name: nacos-payment-provider #Service name
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Service registry address
      config:
        server-addr: localhost:8848 #Configuration center address
        file-extension: yaml #Specify configuration in yaml format
        namespace: 0a294291-a318-4a65-b899-17b08772bb39 #namespaceID corresponding to nacos
        group: CMS #group corresponding to nacos

namespace configuration:

group configuration:

Test:

1. Start Nacos server and cloudalibaba-provider-payment-9003

2. Visit: http://localhost:9003/config/info
result:
namespace:DEV, Group:CMS, Data ID:nacos-payment-provider-dev.yaml. version:1

Conclusion:
9003 locate the location of the configuration file through namespace + group + data ID to read the configuration file

4. Nacos cluster and persistent configuration

Here we only use one Nginx server, three Nacos, one MySQL and three Linux

4.1 Nacos cluster installation and persistent switching

1,Prepare 3 sets Linux Virtual machines, their IP 192.168.0.111 -  192.168.0.107  -  192.168.0.112

2,3 Download on servers nacos
wget   https://Download path of Nacos (found on nacos.io website)

3,stay nacos Of conf Catalog based on cluster.conf.example Fu pointed out that cluster.conf file
cp cluster.conf.example cluster.conf

4,edit cluster.conf Document content
vi cluster.conf
############The contents of the document are as follows--3 sets nacos Server address for copy Just go up--Delete the original content##########
192.168.0.111:8848
192.168.0.107:8848
192.168.0.112:8848

5,Persistence nacos,modify conf Directory application.properties File, will nacos Persistent database from embedded Derby Switch to local MySQL data base
vi application.properties
#######Add the following at the bottom of the file--192.168.0.102 It's my place windows Of IP Address, i.e MySQL It's up to me. windows local#######

spring.datasource.platform=mysql

db.num=1
db.url.0=jdbc:mysql://192.168.0.102:3306/nacos_config?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=root
db.password=admin123


6,Close linux firewall
systemctl stop firewalld
##View firewall status
systemctl status firewalld

4.2. Mysql data initialization

[my MySQL is 192.168.0.102 on the local windows. In order to allow nacos to connect with the local mysql, close the local firewall and enable the remote access of MySQL]
Find the file nacos-mysql.sql from the conf directory of the Nacos decompression package

CREATE DATABASE IF NOT EXISTS nacos_config DEFAULT CHARSET utf8 COLLATE utf8_general_ci;

use nacos_config;

Run the file content of nacos-mysql.sql to OK

##Local mysql settings can be accessed remotely
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%'IDENTIFIED BY 'admin123' WITH GRANT OPTION;
select user,host from user;

##Turn off local firewall

4.3. Nginx configuration

My nginx service is installed on 192.168.0.107 and uses upstream.

Nginx needs to integrate the nginx ﹣ upstream ﹣ check ﹣ module. For the specific installation method, see:
https://blog.csdn.net/weixin_30379625/article/details/87693818

4.4. Modify cloudalibaba-provider-payment-9003

Modify bootstrap.yml to change the original address of nacos to the service address of NGINX

spring:
  application:
    name: nacos-payment-provider #Service name
  cloud:
    nacos:
      discovery:
        #server-addr: localhost:8848 #Service registry address
        server-addr: 192.168.0.107:80 #Service address of NGINX
      config:
        #server-addr: localhost:8848 #Configuration center address
        server-addr: 192.168.0.107:80 #Service address of NGINX
        file-extension: yaml #Specify configuration in yaml format
        #namespace: 0a294291-a318-4a65-b899-17b08772bb39 #nacos Corresponding namespaceID #Temporarily closed
        #group: CMS #nacos Corresponding group #Temporarily closed

4.5 test

1. Start 3 nacos services
cd /opt/software/nacos/bin
sh startup.sh

Testing
You can view the log by / opt/software/nacos/logs/start.out
You can also access:
http://192.168.0.111:8848/nacos
http://192.168.0.107:8848/nacos
http://192.168.0.112:8848/nacos
(pay attention to turn off the firewall)

2. Start NGINX service
/usr/local/nginx-1.14.1/sbin/nginc -c /usr/local/nginx-1.14.1/conf/nginx.conf

Testing
You can access:
http://192.168.0.107:80/nacos
(pay attention to turn off the firewall)

Enter Nacos through nginx, and create the configuration file nacos-payment-provider-dev.yaml

The configuration format yaml is as follows:
config: 
    info: "this is nacos cluster,version:1"

3. Start cloudalibaba-provider-payment-9003
Visit: http://localhost:9003/config/info

result:
this is nacos cluster,version:1

Test success, nacos cluster configuration success!

(in nacos cluster management, you can see the service details of each nacos)

Posted by Liz_SA on Mon, 27 Apr 2020 20:09:31 -0700