Overview
A. Technology stack
- Development language: Java 1.8
- Database: MySQL, Redis, MongoDB, Elasticsearch
- Microservice Framework: Spring Cloud Alibaba
- Microservice Gateway: Spring Cloud Gateway
- Service registration and configuration center: Nacos
- Distributed transactions: Seata
- Link Tracking Framework: Sleuth
- Service degradation and circuit breaker: Sentinel
- ORM framework: MyBatis-Plus
- Distributed task scheduling platform: XXL-JOB
- Message middleware: RocketMQ
- Distributed lock: Redisson
- Permissions: OAuth2
- DevOps: Jenkins, Docker, K8S
B. This section achieves the goal
- Each server of the project [mall2] is registered with the Nacos service, and accesses the interface through the Nacos service name.
- Use the Nacos namespace to create a dev_id/dev_name namespace for registering development environment services.
- Use Naocs shared configuration to extract the configuration required by each service into common.yml.
- IDEA configuration Active profiles
C. Release Notes
- Nacos: 2.0.0
- spring-cloud.version: Hoxton.SR9
- spring-boot.version: 2.3.6.RELEASE
- alibaba.cloud.version: 2.2.3.RELEASE
D. Nacos address
Nacos official website document
Nacos official GitHub address
Nacos official download address
E. Nacos deployment environment
Nacos is defined as an IDC internal application component, not a product for the public network environment. It is recommended to be deployed in an internal isolated network environment, and it is strongly not recommended to be deployed in a public network environment.
H. Nacos supports three deployment modes
- Standalone mode – for testing and single-player trials.
- Cluster mode – used in production environments to ensure high availability.
- Multi-cluster mode – for multi-data center scenarios
1. Nacos installation
Can refer to:
-
Nacos Quick Start, Nacos Spring Cloud Quick Start
Visit: http://localhost:8848/nacos
after running successfully. Default account: nacos, password: nacos
login page
home page
2. Service mall-member access to Nacos
2.1 Add nacos dependency
Service mall-pom service adds naocs dependency, mall-pom.xml:
<!-- Manage the versions of all jar packages of subclasses, the purpose of which is to facilitate unified upgrade and maintenance --> <dependencyManagement> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>${alibaba.cloud.version}</version> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> <version>${alibaba.cloud.version}</version> </dependency> <!-- other omissions --> </dependencyManagement> <!-- All subprojects will automatically add the following dependencies --> <dependencies> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency> <!-- other omissions --> </dependencies>
2.2 yml configuration
Add the configuration to the application-dev.yml configuration of the mall-member service
spring: application: name: mall-member cloud: nacos: discovery: server-addr: 127.0.0.1:8848
2.3 Restart the mall-member service to view the nacos service list
mall-member service
The same is true for other servers connected to nacos.
3. Nacos namespace
3.1 How Nacos supports multiple environments
In daily use, different environments are often required, such as daily, pre-release, and online environments. If it is logical isolation, namespaces can be used. Nacos supports namespaces to support multi-environment isolation, and multiple namespaces can be created in the Nacos console. If physical isolation is required, multiple sets of Nacos environments must be deployed.
3.2 Configure Nacos namespace
By default, there is a public namespace in Nacos. All configurations are obtained in this namespace when no namespace is specified. In actual development, different namespaces can be created for different environments.
Note: The default space cannot be deleted.
3.2.1 New namespace
Add namespace g
create namespace
[Namespace ID] If it is not filled in when adding, the Nacos server will automatically generate a namespace ID randomly. Each namespace has a unique ID, which is the unique identifier of the specified space when reading the configuration. After clicking [OK], a row of records will be added in the namespace list.
Suggestion: In official projects, it is recommended to set [namespace ID] and [namespace name] to be the same, that is, set both to dev. Different names are set here only to clearly illustrate the difference between ID and name in the yml configuration file.
Record
3.2.2 yml configuration
Add the configuration to the application-dev.yml configuration of the mall-member service
spring: application: name: mall-member cloud: nacos: config: server-addr: 127.0.0.1:8848 discovery: namespace: dev_id
Supplementary Note NO.1
Some articles will configure the nacos username and password, which are as follows:
spring: application: name: mall-member cloud: nacos: config: server-addr: 127.0.0.1:8848 username: nacos password: abc123 discovery: namespace: dev_id
In fact, this user name and password are used for Naocs Dashboard login. There is no need to configure the service registration here, and of course no error will be reported if it is configured.
3.2.3 Restart the mall-member service to view the nacos service list
Under the dev_name namespace, the mall-member service is displayed.
dev_name namespace service list
4. Modify Nacos login password and login name
Generally, after installing Nacos, the login password defaults to nacos/nacos, but this is definitely not safe in a formal production environment.
4.1 Nacos stand-alone default embedded database
Nacos stand-alone mode uses the embedded database as the storage engine by default, so we cannot directly modify the data, so we can modify the password through Nacos Dashboard.
change Password
change Password
4.2 Change MySQL password
4.2.1 View Nacos source code encryption method
The underlying source code of Nacos is encrypted by the BCryptPasswordEncoder encryptor, which we can use here.
package com.alibaba.nacos.console.utils; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class PasswordEncoderUtil { public static void main(String[] args) { System.out.println(new BCryptPasswordEncoder().encode("nacos")); } public static Boolean matches(String raw, String encoded) { return new BCryptPasswordEncoder(). matches(raw, encoded); } public static String encode(String raw) { return new BCryptPasswordEncoder().encode(raw); } }
Encrypt with BCryptPasswordEncoder
Import Security dependencies
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency>
Encrypt to get ciphertext
public class UserServerApplication { public static void main(String[] args) { System.out.println(new BCryptPasswordEncoder().encode("nacosDev")); } }
ciphertext
4.2.2 Construct user and change password
Copy it to the password field in the user table of nacos. I constructed a username here: nacosDev, and the password is also the ciphertext encrypted by nacosDev.
change Password
Log in with the set user password
Log in
5. Nacos shared configuration
In daily development, multiple modules may have many shared configurations, such as database connection information, Redis connection information, RabbitMQ connection information, monitoring configuration, and so on. So at this time, we hope that multiple configurations can be loaded, and multiple projects share the same configuration and other functions. Nacos Config does support it.
5.1 New common.yml
Log in to the Naocs platform, create a new common.yml configuration file under the namespace dev_name, and extract the public configuration into this configuration, as follows:
spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://192.168.100.51:3306/ac_db?serverTimezone=Asia/Shanghai &useUnicode=true &tinyInt1isBit=false &characterEncoding=utf-8 &zeroDateTimeBehavior=convertToNull & useSSL=false & allowPublicKeyRetrieval=true username: ac_u password: ac_PWD_123 #hikari database connection pool hikari: pool-name: YH_HikariCP minimum-idle: 10 #minimum number of idle connections idle-timeout: 600000 #The maximum time for an idle connection to survive, the default is 600000 (10 minutes) maximum-pool-size: 100 #The maximum number of connections in the connection pool, the default is 10 auto-commit: true #This property controls the default auto-commit behavior of connections returned from the pool, default value: true max-lifetime: 1800000 #This attribute controls the longest life cycle of the connection in the pool, the value 0 means infinite life cycle, the default is 1800000, which is 30 minutes connection-timeout: 30000 #Database connection timeout, the default is 30 seconds, which is 30000 connection-test-query: SELECT 1 mybatis-plus: configuration: log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
common.yml configuration file
5.2 configuration file change application to bootstrap
The scope of application.yml is that the current application is valid, and the system-level configuration of bootstrap.yml is valid (usually only used when remote configuration is used).
Therefore, change the original application.yml and application-dev.yml in the project to bootstrap.yml and bootstrap-dev.yml.
5.3 Modify mall-member service configuration
bootstrap-dev.yml
server: port: 8080 spring: application: name: mall-member cloud: nacos: config: server-addr: 127.0.0.1:8848 namespace: dev_id file-extension: yml shared-configs: - data-id: common.yml group: DEFAULT_GROUP refresh: true discovery: namespace: dev_id swagger: enabled: true title: User Services basePackage: com.ac.member.controller version: 1.0 description: user service related interface
bootstrap.yml
spring: profiles: active: dev
The configuration of other services such as mall-product is the same.
mall-member
5.4 Restart the service to view the Nacos service list
image.png
6. IDEA configures Active profiles
The configuration files of each environment (such as switching between development and testing), we have previously switched through the bootstrap.yml configuration, as follows:
spring: profiles: active: dev
Generally, in project development, each member of the team will generally create an independent namespace to avoid affecting others. If everyone modifies the configuration items in bootstrap.yml, the code is prone to conflict, so spring.profiles We can remove .active from bootstrap.yml and configure it in IDEA.
configuration
Configure Active Profiles
Restart the service, and the configuration file is in the dev environment.
6. Nacos configure MySQL database
Refer to the official website: Nacos Deployment Manual
6.1 Preface
Before version 0.7, nacos used an embedded database to store data in stand-alone mode, and it was inconvenient to observe the basic situation of data storage. The ability to support mysql data sources has been added after version 0.7.
6.2 Nacos configure MySQL
nacos supports the configuration of multiple databases, controlled by the configuration of db.num and db.url.index. Nacos configures the mysql database only needs the following three points to complete:
- Install the database, version requirements: 5.6.5 +
- Initialize the mysql database, database initialization file: nacos-mysql.sql
- Modify the conf/application.properties file, add support for mysql data source configuration (currently only supports mysql), and add the url, user name and password of the mysql data source.
#************** 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://192.168.100.51:3306/ac_db?characterEncoding=utf8 & amp;connectTimeout=1000 & amp;socketTimeout=3000 &autoReconnect=true &useUnicode=true & useSSL=false & serverTimezone=UTC db.user.0=ac_u db.password.0=ac_PWD_123
import sql
Import sql successfully
Modify the configuration file
6.3 Verification
After launching Nacos, open the Nacos management interface, and create a development environment configuration namespace dev_name in the namespace module, as shown in the following figure:
Create a new namespace
At this time, check the dev_name record that has been created in our database table tenant_info, as shown in the following figure:
query form