More and more readers are telling me about Spring Cloud Alibaba, and I even spent half of an interview talking about it. Therefore, in line with the enthusiasm of technical research, Spring Cloud Alibaba has been studied.

I don’t want to talk or predict the future, but I just picked a few open source components from alibaba’s middleware team that can help solve real business problems.

The background,

First, the context.

Now, there is a clear trend: microservices.

The underlying driver of this trend is the spread of distributed systems, and the various features of microservices are now irresistible to enterprises large and small.

Then, using the microservices architecture style, set up a scaffolding with Spring Cloud, or Dubbo, and got to work.

Then a lot of small companies finish their big pie and find they can’t eat it. This is the acute contradiction of typical backward labor force and advanced productivity. At this point, the idea of going back to basics is out of the question; refactoring is too expensive.

Of course, where there is a problem, there is a business opportunity. After a series of packaging, major XX Cloud manufacturers came on stage with the new concept of “Cloud Native”.

Spring Cloud Alibaba is one of them.

One of the core values of this concept is: smooth up the cloud, enabling operation and maintenance. The most obvious business manifestation is to provide an Open API, or even a nice visual console, the dumb kind.

Start with NACOS

This is a dazzling pearl in the eye, quickly caught my attention.

According to the routine, there are two lectures. The first one covers the features and usage of NACOS, and the second one takes a deeper look at the code written by dachang’s siege lions.

The version used in this article is NACOS 1.0.0, because this version is the first official version of NACOS, NACOS is in the stage of rapid development, some of the content of this article may not be applicable to the later version, please distinguish yourself.

NACOS addresses two core issues: dynamic configuration management and service registry discovery.

In terms of compatibility, in addition to supporting Dubbo, Spring Cloud, Kubernetes, Istio are also compatible.

At this point, I feel a little guilty not to say Eureka.

My experience with NACOS was that it was a perfect replacement for Eureka.

It is an inevitable result that there are talented people in jiangshan generation.

Under the background of “cloud native”, NACOS successfully launched Console, which further extends its tentacles to fine management of services.

Of course, there’s no denying that Eureka is up to something.

Let’s talk about dynamic configuration.

NACOS is, of course, a better alternative to Spring Cloud Config.

Configuration items previously hosted on Git/SVN can now be centrally managed on the Console.

Read on if you want to get a sneak peek. If you want to learn more, you can skip this section and read the next section.

NACOS can be thought of as a centralized service, which is common in The Ali architecture. Therefore, the service must be started first.

There are two options: one is to clone the source code directly and package it using Maven. The second option is to download the GitHub release directly.

Recommend the latter.

Method 1: Run the following command:

git clone https://github.com/alibaba/nacos.git 
cd nacos/ 
mvn -Prelease-nacos clean install -U
Copy the code

After a while of building, we had the desired zip package in the./distribution/target directory.

Method 2: Go to github.com/alibaba/nac… Find the zip package and download it.

For demonstration purposes, let’s start in single-machine mode.

In Windows:

startup.cmd -m standalone
Copy the code

Ready, go to http://127.0.0.1:8848/nacos/index.html and login using nacos/nacos.

Next, look around.

3. Important concepts

To avoid getting lost in Console, it’s important to explain a few important concepts.

NACOS best practices indicate that the outermost namespace can be used to distinguish deployment environments, such as Test, UAT, Product, etc. At the same time, there is a commercial use value: multi-tenant. The namespace is used to allocate space for users.

The other two domain models need no further explanation. The purpose is also obvious: to be able to logically distinguish between the two target objects.

By default, namespace=public and group=DEFAULT_GROUP.

Now that you understand the data model, you can do some Console tricks, such as creating a few new namespaces:

Before moving on to the next section, it is highly recommended that you create a Spring Boot sample project without any configuration or code.

Of course, in order to make this talk more practical, I will not copy the Demo from the official website. The Demo project can also be cloned from GitHub. Please be prepared in advance, the following content will only pick the key points, not how to build the engineering.

4. Construction projects using NACOS

The project name is nacos-example, and dependency management is not mentioned in the various pom.xml files.

Now, this demo project does what it does: when placing an order, the user needs to verify the user’s status, whether the item is on the shelf, and the maximum number of purchases.

To reflect the dynamic configuration, the user status and the purchase of the maximum number of configuration items. The two configurations are different under different namespaces.

In order to reflect the call between services, the order entry is verified by the user module in order module.

Such a configuration rule is highly controversial and will not be discussed in this article.

The User module needs to be configured dynamically, so it can be considered a Config client. It is also a service provider because it receives calls from the Order module.

Similarly, the Order module is a Config client because it needs to be configured dynamically.

At this point, the reader will find some of the drawbacks of NACOS, most notably the intrusiveness of “multiple roles.” Because it is a centralized architecture, this problem is not surprising if it is not well decoupled.

In particular, in the role allocation of remote calls, NACOS strictly follows the “producer-consumer” model. In actual business scenarios, it is inevitable that some services are both producers and consumers, while Eureka does not have this distinction.

Next, look at configuration.

Most of alibaba’s open source products suggest using properties files. Due to my personal habit, I use YML to achieve the same effect.

It is worth noting that the configuration file must use bootstrap.yml because a higher priority load order is required.

The configuration file of the User module, which distinguishes the environment, also defines the group for isolation in order to increase identification. As follows:

server:
  port: 8100
spring:
  application:
    name: user
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848
        file-extension: yaml
        namespace: 7d3e5f19-a102-471a-b6e0-67bd7d1d35f3
        group: USER_GROUP
      discovery:
        server-addr: 127.0. 01.: 8848
        namespace: 7d3e5f19-a102-471a-b6e0-67bd7d1d35f3
---
spring:
  profiles: prod
  cloud:
    nacos:
      config:
        server-addr: 11.162196.16.: 8848
        namespace: c4c81555-91e1-4ef5-8b57-77c5407b3481
      discovery:
        server-addr: 11.162196.16.: 8848
        namespace: c4c81555-91e1-4ef5-8b57-77c5407b3481
---
spring:
  profiles:
    active: dev
Copy the code

The configuration file for the ORDER module is similar and will not be described here.

Custom configuration parameters are then encapsulated. If you only have a single parameter, you can not use JavaBean form, but most cases are multi-parameter configuration, this article gives the JavaBean form encapsulation.

Configuration parameters used by the user module:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Getter
@Setter
@ConfigurationProperties(prefix = "user")
public class UserConfig {

    /** * User status: enable- enable, disable- disable */
    private String status;
}
Copy the code

Configuration parameters used by the ORDER module:

import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Getter
@Setter
@ConfigurationProperties(prefix = "order")
public class OrderConfig {

    /** * Maximum purchase quantity */
    private int maxNum = Integer.MAX_VALUE;

    /** * whether to install */
    private boolean onSale = true;
}
Copy the code

The main entry is OrderController in the Order module:

@RefreshScope
@RestController
@RequestMapping
public class OrderController {

    @Autowired
    private OrderConfig config;

    @Autowired
    private UserRpcService userRpcService;

    @PostMapping(value = "/order")
    public String placeOrder(@RequestParam(name = "num", defaultValue = "1") Integer num) {
        if (!"enable".equals(userRpcService.getUserStatus())) return "The user has been disabled and cannot place orders.";
        if (num <= 0) return "Purchase quantity error";
        if(! config.isOnSale())return "Goods not on the shelves";
        if (num > config.getMaxNum()) return "Purchase quantity over limit";
        return "OK"; }}Copy the code

Some columns of order checks, the first check is to determine the user status, using a remote call based on Feign. Of course, the corresponding Controller implementation must be provided in the User module:

@RefreshScope
@RestController
@RequestMapping(value = "/user")
public class UserController {

    @Autowired
    private UserConfig config;

    @GetMapping(value = "/status")
    public String getUserStatus(a) {
        returnconfig.getStatus(); }}Copy the code

The @refreshScope annotation in the Controller is used to enable automatic configuration updates.

After the whole project is ready, before running, you need to add the configuration to the Console to test whether the dynamic configuration works.

The procedure for adding a configuration is not described here, but the Data Id filling specification needs to be paid attention to. The complete format of dataId consists of three parts:

${prefix}-${spring.profile.active}.${file-extension}
Copy the code

The prefix, the default use ${spring. Application. The name}, but can be by spring. Cloud. Nacos. Config. The prefix to configuration.

Spring.profile. active is the profile corresponding to the current environment. For details, see the Spring Boot documentation. Note: When spring.profile.active is null, the corresponding hyphen – will also not exist, and the dataId concatenation format will become ${prefix}.${file-extension}.

File – exetension for configuration of content data format, can be configured a spring. The cloud. Nacos. Config. The file – the extension to the configuration. Currently, only properties and YAML types are supported.

Other functions

NACOS keeps a history of configuration files for 30 days and offers a nice one-click rollback that triggers configuration updates.

Finally, the graceful up/down function is a highlight of NACOS. Within each service detail, there can be multiple instances, each of which can be brought on/off by Console. If it is to go live again, there will be a period of registration process, rather than clicking the “live” button and immediately accessing the instance.

6. Advanced features of NACOS

That would be far from enough if NACOS were to go into mass production. In this chapter, several advanced features will be explained to ensure that your NACOS service is safe.

1. Cluster mode

Starting only one instance of the NACOS service is too small. This section shows you how to deploy a NACOS cluster on a stand-alone deployment basis.

Find the conf/cluster.conf file, if not, create a new one. To edit the contents, simply specify the IP and port of the machine, preferably three or more. If there are not so many machine resources, you can directly deploy them on one machine by specifying the port number. As follows:

# ip:port
192.168.0.88:8848
192.168.0.88:8849
192.168.0.88:8840
Copy the code

Please note that you cannot use 127.0.0.1 or localhost in clustered mode, the current version has a bug in nic resolution.

The problem is that when Nacos gets the local IP, it doesn’t get the correct external IP, Make sure that inetaddress.getlocalhost ().gethostAddress () or hostname -i is the same as the IP configured in cluster.conf.

Find the conf/application. The properties, if not, there is a problem. Edit the contents to enable MySQL as the storage layer (currently MySQL only supported). Append to the end of the file:

Spring. The datasource. Platform = mysql db. Num = 1 db. Url. 0 = JDBC: mysql: / / 127.0.0.1:3306 / nacos? characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true db.user=root db.password=123456Copy the code

Then create a new database named nacos and run the conf/nacos-mysql.sql script file.

That’s all you need to configure to run the NACOS cluster mode.

Because on one machine to simulate multiple NACOS services, can be configured out two copies of engineering, and then in the conf/application. The properties of modified port number.

startup -m cluster
Copy the code

Use the corresponding port number to access Console. If the Console is successfully opened, the deployment is successful.

Finally, in the demo project built above, modify the value of server-addr and add other NACOS access addresses:

server:
  port: 8200
spring:
  application:
    name: order
  cloud:
    nacos:
      config:
        server-addr: 192.168. 088.: 8848192168 0.88:8849192168 0.88:8840
        file-extension: yaml
        namespace: 7d3e5f19-a102-471a-b6e0-67bd7d1d35f3
        group: ORDER_GROUP
      discovery:
        server-addr: 192.168. 088.: 8848192168 0.88:8849192168 0.88:8840
        namespace: 7d3e5f19-a102-471a-b6e0-67bd7d1d35f3
Copy the code

2. Safety measures

Unfortunately, the NACOS website does not cover security in detail. AccessKey and secretKey are the only suspected security configuration items, but they are set up to cooperate with ACM of Ali Cloud.

The configuration file encryption function that I am most concerned about has not been released yet. Here is the official quote:

Nacos plans to provide encryption capability in 1.x version. Currently, encryption is not supported. We can only rely on SDK to do encryption and save it in Nacos. The security of the NACOS Console is also poor. Passwords cannot be changed, users cannot be created, and there is no concept of roles or permissions.

NACOS service registration and discovery based on HttpURLConnection remote calls, this place is to provide the HTTPS enable switch, the JVM parameter name is: com. Alibaba. NACOS. Client. Naming. TLS. Enable.

Beyond that, security measures can only be done around the periphery of NACOS for now.

3. Some useful configurations

Nacos. home, which is the startup parameter of the Nacos service, passed in as a JVM parameter. Unfortunately, using this parameter is not very convenient, and you need to modify the startup script, which is approximately line 104 in startup.sh:

JAVA_OPT="${JAVA_OPT} -Dnacos.home=${BASE_DIR}"
Copy the code

A more radical approach is to change the BASE_DIR value (which defaults to the parent directory of the startup.sh file), around line 71 of the startup.sh file:

export BASE_DIR=`cd $(dirname $0)/.. ; pwd`Copy the code

Nacos.logging.path, logs are the most valuable add-on to a system run, and sometimes you need to customize log directories for ease of management. If you need to specify this parameter, you also need to modify the startup.sh script. Append a line after about 104:

JAVA_OPT="${JAVA_OPT} -dnacos.logging. path= specified directory"Copy the code

Log level, of course, can also be specified, respectively through the com. Alibaba. Nacos. Naming. The level and com. Alibaba. Nacos. Config. The level of these two JVM parameters specified.

However, it is important to note that not all logs are valuable, and you can delete them as required. Otherwise, the server will be unnecessarily burdened. The relevant log configuration can be modified in conf/nacos-logback.xml.

4, the endpoint

The serverAddr parameter in the above configuration file is a summary of all available NACOS services, which is obviously not reasonable in a large-scale application scenario. The endpoint is a DNS service that can proxy all NACOS services by specifying a single access domain name.

This article is a best practice for the endpoint and provides an effective means of isolating the environment.

Seven,

This article is a functional introduction to Spring Cloud Alibaba Nacos.

If the team with strong r&d ability can try this “crab” now, along with a lot of PR.

My recommendation is to wait and see for a while, probably after V1.2.0, and gradually introduce it into the company’s technology stack.

Scan the qr code below, enter the original dry goods, engage in “technology” holy land.