Springboot Episode 24: Architecture mongodbmanager, Redis, Mybatis, Spring Security

e93ee59b1cadd582526ed9699abbff9a.png

image.png
30fd824e101fa10fef107af8053e6aa1.png
image.png
188169dbb159e4c1146dd4acb5d17fd6.png
image.png
41bb87c9ae29a36fabeba218f3f65047.png
image.png
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-pool2</artifactId>
</dependency>

Spring Boot provides a component package for Redis integration: spring-boot-starter-data-redis, spring-boot-starter-data-redisdepends on spring-data-redis and  lettuce .

Lettuce is a scalable thread-safe Redis client. Multiple threads can share the same RedisConnection. It uses the excellent netty NIO framework to efficiently manage multiple connections.

# Redis数据库索引(默认为0)
spring.redis.database=0  
# Redis服务器地址
spring.redis.host=localhost
# Redis服务器连接端口
spring.redis.port=6379  
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制) 默认 8
spring.redis.lettuce.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制) 默认 -1
spring.redis.lettuce.pool.max-wait=-1
# 连接池中的最大空闲连接 默认 8
spring.redis.lettuce.pool.max-idle=8
# 连接池中的最小空闲连接 默认 0
spring.redis.lettuce.pool.min-idle=0

Spring Session provides a set of solutions for creating and managing Servlet HttpSession. Spring Session provides the function of Clustered Sessions (Clustered Sessions). By default, external Redis is used to store Session data, so as to solve the problem of Session sharing.

Add scan for mapper package in startup class@MapperScan

@SpringBootApplication
@MapperScan("com.xxx.mapper")
public class MybatisAnnotationApplication {

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

Or add annotations directly on the Mapper class@Mapper

public interface UserMapper {
	
	@Select("SELECT * FROM users")
	@Results({
		@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
		@Result(property = "nickName", column = "nick_name")
	})
	List<UserEntity> getAll();
	
	@Select("SELECT * FROM users WHERE id = #{id}")
	@Results({
		@Result(property = "userSex",  column = "user_sex", javaType = UserSexEnum.class),
		@Result(property = "nickName", column = "nick_name")
	})
	UserEntity getOne(Long id);

	@Insert("INSERT INTO users(userName,passWord,user_sex) VALUES(#{userName}, #{passWord}, #{userSex})")
	void insert(UserEntity user);

	@Update("UPDATE users SET userName=#{userName},nick_name=#{nickName} WHERE id =#{id}")
	void update(UserEntity user);

	@Delete("DELETE FROM users WHERE id =#{id}")
	void delete(Long id);

}
mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml

mybatis-config.xml configuration

<configuration>
	<typeAliases>
		<typeAlias alias="Integer" type="java.lang.Integer" />
		<typeAlias alias="Long" type="java.lang.Long" />
		<typeAlias alias="HashMap" type="java.util.HashMap" />
		<typeAlias alias="LinkedHashMap" type="java.util.LinkedHashMap" />
		<typeAlias alias="ArrayList" type="java.util.ArrayList" />
		<typeAlias alias="LinkedList" type="java.util.LinkedList" />
	</typeAliases>
</configuration>

RabbitMQ is a kind of message middleware that implements AMQP (Advanced Message Queuing Protocol). It originally originated from the financial system and is used to store and forward messages in distributed systems. It performs well in terms of ease of use, scalability, and high availability. . RabbitMQ is mainly implemented to achieve two-way decoupling between systems. When the producer produces a large amount of data, the consumer cannot consume it quickly, so an intermediate layer is needed. Save this data.

AMQP, or Advanced Message Queuing Protocol, is an open standard for application layer protocols designed for message-oriented middleware. Message middleware is mainly used for decoupling between components, and the sender of the message does not need to know the existence of the message user, and vice versa. The main features of AMQP are message-oriented, queue, routing (including point-to-point and publish/subscribe), reliability, and security.

RabbitMQ is an open source AMQP implementation. The server side is written in Erlang language and supports multiple clients, such as: Python, Ruby, .NET, Java, JMS, C, PHP, ActionScript, XMPP, STOMP, etc., and supports AJAX. It is used to store and forward messages in a distributed system, and performs well in terms of ease of use, scalability, and high availability.

  • Virtual host: A virtual host holds a set of exchanges, queues and bindings. Why do you need multiple virtual hosts? Very simple, in RabbitMQ, users can only control permissions at the granularity of virtual hosts.  Therefore, if group A needs to be prohibited from accessing group B's switches/queues/bindings, a virtual host must be created for A and B respectively. Every RabbitMQ server has a default virtual host "/".

  • Switch: Exchange is used to forward messages, but it does not store them  . If there is no Queue bind to Exchange, it will directly discard the messages sent by Producer. Here is a more important concept: routing key  . When the message reaches the switch, the interaction opportunity will be forwarded to the corresponding queue, so which queue to forward to depends on the routing key.

  • Binding: that is, the switch needs to be bound to the queue

The function of the switch is mainly to receive messages and forward them to the bound queue. The switch does not store messages. After the ack mode is enabled, the switch will return an error if it cannot find the queue. There are four types of switches: Direct, topic, Headers and Fanout

It is very simple to integrate RabbitMQ with Spring Boot. If it is just a simple use configuration, Spring Boot provides spring-boot-starter-amqp various support for projects.

easy to use

1. Configure the Pom package, mainly to add  spring-boot-starter-amqp support

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

2. Configuration file

Configure the installation address, port and account information of RabbitMQ

spring.application.name=Spring-boot-rabbitmq

spring.rabbitmq.host=192.168.0.86
spring.rabbitmq.port=5672
spring.rabbitmq.username=admin
spring.rabbitmq.password=123456

send email

Add  spring-boot-starter-mail a package reference in the pom package

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

ValidateCodeThe class only stores the verification code and expiration time

import java.time.LocalDateTime;
import lombok.Data;
@Data
public class ValidateCode {
 private String code;
 private LocalDateTime expireTime;
 public ValidateCode(String code, int expireIn) {
  this.code = code;
  this.expireTime = LocalDateTime.now().plusSeconds(expireIn);
 }
 public boolean isExpried() {
  return LocalDateTime.now().isAfter(getExpireTime());
 }
 public ValidateCode(String code, LocalDateTime expireTime) {
  super();
  this.code = code;
  this.expireTime = expireTime;
 }
}
import org.springframework.web.context.request.ServletWebRequest;
public interface ValidateCodeGenerator {
 ValidateCode generate(ServletWebRequest request);
}
// 短信验证码生成器
@Component("smsCodeGenerator")
public class SmsCodeGenerator implements ValidateCodeGenerator {
 @Override
 public ValidateCode generate(ServletWebRequest request) {
  String code = RandomStringUtils.randomNumeric(SecurityConstants.SMS_RANDOM_SIZE);
  return new ValidateCode(code, SecurityConstants.SMS_EXPIRE_SECOND);
 }
}
public interface SmsCodeSender {
 void send(String mobile, String code)
}
1bb13bcca29d613980f1e6da5a6230ad.png
image.png
technology illustrate official website
Spring Boot Container + MVC framework https://spring.io/projects/spring-boot
Spring Security Authentication and Authorization Framework https://spring.io/projects/spring-security
My shoe ORM framework http://www.mybatis.org/mybatis-3/zh/index.html
MyBatisGenerator Data layer code generation http://www.mybatis.org/generator/index.html
PageHelper MyBatis physical paging plugin http://git.oschina.net/free/Mybatis_PageHelper
Swagger-UI document generation tool https://github.com/swagger-api/swagger-ui
Elasticsearch search engine https://github.com/elastic/elasticsearch
RabbitMq message queue https://www.rabbitmq.com/
Redis distributed cache https://redis.io/
MongoDb document database https://www.mongodb.com/
zookeeper distributed lock https://zookeeper.apache.org/
Docker Application Container Engine https://www.docker.com/
Druid database connection pool https://github.com/alibaba/druid
OSS object storage https://github.com/aliyun/aliyun-oss-java-sdk
JWT JWT login support https://github.com/jwtk/jjwt
LogStash log collection https://github.com/logstash/logstash-logback-encoder
Lombok Simplify Object Encapsulation Tool https://github.com/rzwitserloot/lombok
Set Global transaction management framework https://github.com/seata/seata
Portainer Visual Docker container management https://github.com/portainer/portainer
canal data synchronization https://github.com/alibaba/canal
41ca63b4f0fb797681a6f04e64ab8790.png
image.png
6d2629d224bd6c01bacd2eb934e4d373.png
image.png
0da3f91aba7a73dbdd23d35cd0201696.png
image.png

https://www.rabbitmq.com/install-homebrew.html

da0d38044545bfd56c16df3ea049beb9.png
image.png

redis, mongodb and rabbitmq

spring:  
datasource:  
url:jdbc:mysql://localhost:3306/xxx?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8  
username:druid  
password:druid705  
druid:  
initial-size:5#连接池初始化大小  
min-idle:10#最小空闲连接数  
max-active:20#最大连接数  
web-stat-filter:  
exclusions:"*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"#不统计这些请求数据  
stat-view-servlet:#访问监控网页的登录用户名和密码  
login-username:druid  
login-password:druid  
data:  
mongodb:  
host:134.175.187.61  
uri:mongodb://mongod:<password>@134.175.187.61:27017/test  
redis:  
host:134.175.187.61# Redis服务器地址  
database:0# Redis数据库索引(默认为0)  
port:6379# Redis服务器连接端口  
password:# Redis服务器连接密码(默认为空)  
jedis:  
pool:  
max-active:8# 连接池最大连接数(使用负值表示没有限制)  
max-wait:-1ms# 连接池最大阻塞等待时间(使用负值表示没有限制)  
max-idle:8# 连接池中的最大空闲连接  
min-idle:0# 连接池中的最小空闲连接  
timeout:3000ms# 连接超时时间(毫秒)  
rabbitmq:  
host:localhost  
port:5672  
virtual-host:/#xxx  
username:admin  
password:admin123  
publisher-confirms:true#如果对异步消息需要回调必须设置为true

Mongodb database connection on Tencent cloud server

spring:  
datasource:  
url:jdbc:mysql://localhost:3306/xxx`?serverTimezone=UTC&useSSL=false&useUnicode=true&characterEncoding=UTF-8  
username:druid  
password:druid705  
druid:  
initial-size:5#连接池初始化大小  
min-idle:10#最小空闲连接数  
max-active:20#最大连接数  
web-stat-filter:  
exclusions:"*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"#不统计这些请求数据  
stat-view-servlet:#访问监控网页的登录用户名和密码  
login-username:druid  
login-password:druid  
data:  
elasticsearch:  
repositories:  
enabled:true  
cluster-nodes:localhost:9200  
cluster-name:elasticsearch  
elasticsearch:  
rest:  
uris:["http://localhost:9200"]

Error:

ERROR: rpmdb: BDB0113 thread/process 12788/140191014115392 FAILURE: BDB1507 thread died in Berkeley DB library ERROR: db5 error from dbenv->failchk (-30973): BDB0087 DB_RUNRECOVERY: fatal error running database recovery error: unable to use db5 Opening Packages index in /var/lib/rpm - (-30973) ERROR: Unable to open Packages database CRITICAL:yum.main in /var/lib/rpm:

ERROR: rpmdb open failed

Zookeeper is an open source distributed coordination service that can be used to manage and coordinate distributed applications, providing functions such as distributed locks, naming services, configuration management, and cluster management. Download Zookeeper can be used to build high-availability, scalable distributed systems, and it is widely used in large-scale distributed storage, message queues, Hadoop clusters and other fields. If you need to build or manage distributed systems, Zookeeper will be a very useful tool.

Zookeeper is an open source distributed coordination service, mainly used for the coordination and management of distributed applications.

Install Nacos

Unzip and move to the installation directory

tar -zxvf nacos-server-1.4.1.tar.gz -C /usr/local/

Create a database named nacos_config, and then use the MySQL client to execute the /usr/local/nacos/conf/nacos-mysql.sql file to complete the table creation.

Open the core configuration file application.properties in the Nacos server, the file path is as follows:

/usr/local/nacos/conf/application.properties

Locate near the "data source" configuration of spring.datasource.platform on line 33. The default data source configuration is commented with #, delete the comment and configure the data source according to the example below.

### 设置数据库类型
spring.datasource.platform=mysql

### 数据库的数量,可配置多个数据:
db.num=1

### 数据库连接信息:
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=nacos_config
db.password.0=password

Set up the cluster configuration

After configuring multiple (at least three) Nacos services, execute the following command to create a cluster configuration file:

cp /usr/local/nacos/cluster.conf.example /usr/local/nacos/cluster.conf

Configure the cluster nodes in the file in the following format, and the default port 8848 can be left unconfigured

\#it is ip

# example

192.168.16.101:8847
192.168.16.102
192.168.16.103
b4d6457d908c4ef993c6b766bc6b0e10.png
image.png
cd /usr/local/nacos

# 以单机模式运行

bash startup.sh -m standalone

# 以集群模式运行

bash startup.sh

https://github.com/alibaba/nacos/releases

  • Unzip the installation package and run directly binunder the directory startup.cmd;

  • After running successfully, you http://localhost:8848/nacoscan visit the homepage of Nacos. The default account password is nacos.

  • Create nacos-user-service module and nacos-ribbon-service module;

<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>
  • Modify the relevant dependencies, and change the dependencies discovered by the original Consul registration to Nacos:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  • Modify the configuration file application.yml, and change the registration discovery configuration of Consul to that of Nacos:

server:
  port: 8206
spring:
  application:
    name: nacos-user-service
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #配置Nacos地址
management:
  endpoints:
    web:
      exposure:
        include: '*'

Create nacos-config-client module

  • Add related dependencies in pom.xml:

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  • Add the configuration file application.yml to enable the configuration of the dev environment:

spring:
  profiles:
    active: dev
  • Add the configuration file bootstrap.yml, mainly to configure the function of Nacos as the configuration center:

server:
  port: 9101
spring:
  application:
    name: nacos-config-client
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848 #Nacos地址
      config:
        server-addr: localhost:8848 #Nacos地址
        file-extension: yaml #这里我们获取的yaml格式的配置
  • Create a ConfigClientController to obtain configuration information from the Nacos configuration center:

@RestController
@RefreshScope
public class ConfigClientController {

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

    @GetMapping("/configInfo")
    public String getConfigInfo() {
        return configInfo;
    }
}
06b6030e42056047ce0b6c1e38f1923e.png
image.png
28e32bd3e7c83f313e52380e15c8b7e8.png
image.png

start_zookeeper.sh

/usr/local/kafka/bin/zookeeper-server-start.sh /usr/local/kafka/config/zookeeper.properties >zookeeper.log 2>&1 &

start_kafka.sh

/usr/local/kafka/bin/kafka-server-start.sh /usr/local/kafka/config/server.properties >kafka.log 2>&1 &

The operation of Nacos requires a database, and it supports two kinds of databases: local database Derby, and MySQL database. So the corresponding startup commands are as follows:

  • The Derby database runs in stand-alone mode: docker-compose -f example/standalone-derby.yaml up

  • MySQL 5.7 database runs in stand-alone mode: docker-compose -f example/standalone-mysql-5.7.yaml up

  • MySQL 8 database runs in stand-alone mode: docker-compose -f example/standalone-mysql-8.yaml up

Cluster mode startup: docker-compose -f example/cluster-hostname.yaml up

The error message you received indicates that the command is not installed on your system docker-compose, or it is not in your system's PATH environment variable.

Assuming you already have Docker installed, you can install it as follows docker-compose:

  1. Open a terminal window.

  2. Run the following command to download the latest version  docker-compose:

sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose

This will download docker-composethe binaries and store them in /usr/local/binthe directory.

  1. Make  docker-compose the binary executable:

sudo chmod +x /usr/local/bin/docker-compose

docker-compose 4. Verify that it was installed correctly by running the following command  :

docker-compose --version

This should show the version number that was just installed docker-compose.

After installation docker-compose, you can try to run your command again.

Upgrading your Docker version can resolve many issues, including issues related to deprecated flags and commands. Here are the steps to upgrade Docker:

  1. First, you need to determine which version of Docker is currently installed. You can run the following commands in a terminal:

docker version

This command will display version information for the Docker client and server.

  1. Download and install the latest version of Docker. Depending on your operating system, you can download the appropriate installer from the official Docker website. If you are using a Linux system, you can run the following command to upgrade Docker:

sudo apt-get update && sudo apt-get install docker-ce

This will update the package list and install the latest version of Docker.

  1. After the installation is complete, you need to restart the Docker service. This can be done with the following command:

sudo systemctl restart docker

4. Finally, you can run the following command again to verify the Docker version:

docker version

If all steps are correct, you should see the latest version of Docker installed. Please note that some data or configuration files may be lost during the upgrade process, please make sure to back up important data and follow the recommendations of the official documentation.

This error usually occurs because you are running a system that is not based on Debian or Ubuntu, and apt-getthe command is only available on those systems. If you are running another system such as CentOS, Fedora or macOS, you will need to use the appropriate package manager or install Docker manually.

Here are some ways to install Docker on different operating systems:

  • For CentOS, Docker can be installed using the yum package manager:sudo yum install docker-ce

  • For Fedora, Docker can be installed using the dnf package manager:sudo dnf install docker-ce

  • For macOS, you can download and install Docker for Mac from the official Docker website.

Nacos is dedicated to helping you discover, configure and manage microservices. Nacos provides a set of easy-to-use feature sets to help you quickly realize dynamic service discovery, service configuration, service metadata, and traffic management. Nacos helps you build, deliver and manage microservice platforms more agilely and easily. Nacos is a service infrastructure for building a "service"-centric modern application architecture (such as microservice paradigm, cloud native paradigm).

Download the latest stable version nacos-server-2.0.3.tar.gzpackage under Linux environment, and use FinalShellthe cloud server client connection tool to log in to the cloud server and upload it to /usr/localthe directory of the cloud server:

Then execute the unzip command and change to nacos/binthe directory:

Start the service: nacos/binExecute the start service command after switching to the directory nacos(the start command standalonerepresents stand-alone mode operation, non-cluster mode)

sh startup.sh -m standalone

nacos is starting with standalone
nacos is starting, you can check the /usr/local/nacos/nacos/logs/start.out

By default, Nacos starts in background mode, use the tail command to view the startup log. You can see that the default port of Nacos is 8848

tail -f ./logs/start.out
fcccbe1af32b1b56461f54505ba402a1.png
image.png
4a83eab5943eff0d9c0d8e05c8e39976.png
image.png
62a31fcc47c26a8ddee073da4b6a51ea.png
image.png
6aaa348c34d79b54416dfdfdc6dd74af.png
image.png

https://www.elastic.co/cn/kibana/

https://grafana.com/

ef3d15a1710794d0dcb9a29dfc82d824.png
image.png
docker pull containerize/elastichd

Quick Start:

docker run -p 9200:9200 -d --name elasticsearch elasticsearch
docker run -p 9800:9800 -d --link elasticsearch:demo containerize/elastichd

https://github.com/dushixiang/kafka-map

Nacos Docker Quick Start

Steps

  • Clone project

    git clone https://github.com/nacos-group/nacos-docker.git
    cd nacos-docker
  • Stand-alone mode Derby

    docker-compose -f example/standalone-derby.yaml up
  • Standalone mode MySQL

If you want to use MySQL5.7

docker-compose -f example/standalone-mysql-5.7.yaml up

If you want to use MySQL8

docker-compose -f example/standalone-mysql-8.yaml up
  • cluster mode

    docker-compose -f example/cluster-hostname.yaml up
  • service registration

    curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'
  • service discovery

    curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instance/list?serviceName=nacos.naming.serviceName'
  • publish configuration

    curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=helloWorld"
  • get configuration

    curl -X GET "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test"
  • Nacos console

    link:http://127.0.0.1:8848/nacos/

    sh startup.sh -m standalone

nacos is starting with standalone
nacos is starting,you can check the /usr/local/nacos/logs/start.out

Service Registration & Discovery and Configuration Management

service registration

curl -X POST 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'

service discovery

curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instance/list?serviceName=nacos.naming.serviceName'

publish configuration

curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=HelloWorld"

get configuration

curl -X GET "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test"

5. Shut down the server

Linux/Unix/Mac

sh shutdown.sh

Nacos Docker

Quick Start

docker run --name nacos-quick -e MODE=standalone -p 8849:8848 -d nacos/nacos-server:2.0.2

Advanced Usage

  • Tips: You can change the version of the Nacos image in the compose file from the following configuration. example/.env

NACOS_VERSION=2.0.2

Run the following command:

  • Clone project

    git clone --depth 1 https://github.com/nacos-group/nacos-docker.git
    cd nacos-docker
  • Standalone Derby

    docker-compose -f example/standalone-derby.yaml up
  • Standalone Mysql

    # Using mysql 5.7
    docker-compose -f example/standalone-mysql-5.7.yaml up
    
    # Using mysql 8
    docker-compose -f example/standalone-mysql-8.yaml up
  • Cluster

    docker-compose -f example/cluster-hostname.yaml up
  • Service registration

    curl -X PUT 'http://127.0.0.1:8848/nacos/v1/ns/instance?serviceName=nacos.naming.serviceName&ip=20.18.7.10&port=8080'
  • Service discovery

    curl -X GET 'http://127.0.0.1:8848/nacos/v1/ns/instances?serviceName=nacos.naming.serviceName'
  • Publish config

    curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test&content=helloWorld"
  • Get config

    curl -X GET "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=nacos.cfg.dataId&group=test"
  • Open the Nacos console in your browser

    link:http://127.0.0.1:8848/nacos/

  1. Open Ports Firewall and Security Groups

By default, the CentOS system does not open port 7848/8848 to the outside world. It is necessary to set up a firewall to allow port 7848/8848.

Among them, port 8848 is the port where Nacos provides services to clients, and port 7848 is the communication port of Nacos cluster, which is used for election and detection among Nacos clusters. In addition, after Nacos 2.0, ports 9848 and 9849 for long-term connections are added for grpccommunication between the client and the server, and these two ports need to be opened together.

e1f9cab2e8572b1359e47e03e1201970.png
image.png

Log in to the UI management interface of Nacos, the user name and password are both nacos

4988d047b86bf1fce34ff7072b84d1bb.png
image.png

Select Custom on the right, and write the Aliyun address [start.aliyun.com], the default [start.spring.io].

a0cebfe6ac2e841c4b8d1565b44f068a.png
image.png

Click the Next button in the interface to enter Dependenciesthe interface, select Spring Cloud Alibabathe module and check it in the dependencies on the right Nacos Service Discovery; after selecting Webthe module, check the dependencies in the dependencies on the right Spring Web.

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lagou</groupId>
    <artifactId>nacos-sample</artifactId>
    <version>1.0.0-SNAPSHOT</version>
    <name>nacos-sample</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <spring-boot.version>2.3.7.RELEASE</spring-boot.version>
        <spring-cloud-alibaba.version>2.2.2.RELEASE</spring-cloud-alibaba.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
    </dependencies>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.3.7.RELEASE</version>
                <configuration>
                    <mainClass>com.lagou.nacossample.NacosSampleApplication</mainClass>
                </configuration>
                <executions>
                    <execution>
                        <id>repackage</id>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
</project>

modify application.propertiesfile

# 应用名称
spring.application.name=nacos-sample
# 应用服务 WEB 访问端口
server.port=9000
# Nacos帮助文档: https://nacos.io/zh-cn/docs/concepts.html
# Nacos认证信息
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口
#spring.cloud.nacos.discovery.server-addr=mse-6d50f4f0-p.nacos-ans.mse.aliyuncs.com:8848
spring.cloud.nacos.discovery.server-addr=http://xxxxxxxx:8848
# 注册到 nacos 的指定 namespace,默认为 public
spring.cloud.nacos.discovery.namespace=public
#spring.cloud.nacos.discovery.endpoint=nacos
spring.cloud.nacos.discovery.log-name=nacosLog
spring.cloud.nacos.discovery.cluster-name=nacos-cluster
spring.cloud.nacos.discovery.group=nacos-group
spring.cloud.loadbalancer.ribbon.enabled=true
management.endpoints.web.exposure.include=*
  • The Derby database runs in stand-alone mode: docker-compose -f example/standalone-derby.yaml up

  • MySQL 5.7 database runs in stand-alone mode: docker-compose -f example/standalone-mysql-5.7.yaml up

  • MySQL 8 database runs in stand-alone mode: docker-compose -f example/standalone-mysql-8.yaml up

docker-compose is an orchestration tool for defining and running multi-container Docker applications. After using docker-compose, it is no longer necessary to create and start containers one by one. You can use a YML file to configure all the services your application needs, and then use a single command to create and start all the services from the YML file configuration. But docker-compose needs to be installed separately, otherwise the following error will occur

solution:

cd /usr/local/bin
wget https://github.com/docker/compose/releases/download/1.14.0-rc2/docker-compose-Linux-x86_64
rename docker-compose-Linux-x86_64 docker-compose docker-compose-Linux-x86_64
chmod +x /usr/local/bin/docker-compose
docker-compose version
b884bbac02a2a75629d09b5b7b1b8639.png
image.png

Using docker-compose may prompt "ERROR: no such image: nacos/nacos-server:: invalid reference format", invalid parameter format

Solution: Modify the configuration item of example/standalone-mysql-5.7.yaml in the Nacos source code, and change "image: nacos/nacos-server:{ {{ NACOS_VERSION}}" to: "image: nacos/nacos-server:latest ".

da465384ae458f6f48987f4b0c924b17.png
image.png
a06fe347aeda2a5f2f0de46da2ac3ef6.png
image.png
f0d839d255cead8049ad205cb37a1bfd.png
image.png

The Spring Cloud Alibaba Nacos project mainly has two dependencies

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

在配置文件 application.properties 中要填写 Nacos 的相关信息,具体内容如下:

# 应用名称(也是 Nacos 中的服务名)
spring.application.name=spring-cloud-nacos-producer
# 应用服务 WEB 访问端口
server.port=8082
# Nacos认证信息
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口
spring.cloud.nacos.discovery.server-addr=mse-6d50f4f0-p.nacos-ans.mse.aliyuncs.com:8848
# 注册到 nacos 的指定 namespace,默认为 public
spring.cloud.nacos.discovery.namespace=public

# 应用名称
spring.application.name=springcloud-nacos-consumer
# 应用服务 WEB 访问端口
server.port=8082
# Nacos帮助文档: https://nacos.io/zh-cn/docs/concepts.html
# Nacos认证信息
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos 服务发现与注册配置,其中子属性 server-addr 指定 Nacos 服务器主机和端口
spring.cloud.nacos.discovery.server-addr=xx.xxx.xxx.xx:8848
# 注册到 nacos 的指定 namespace,默认为 public
spring.cloud.nacos.discovery.namespace=public

install zookeeper

1. Download

docker pull zookeeper

Two, run

docker run -p 2181:2181 -d zookeeper

3. Enter the container

docker exec -it 容器id bash

Install nacos (stand-alone, mysql):

1. Download

docker pull nacos/nacos-server

2. Mount the directory for mapping to the container

mkdir -p /home/docker/nacos/logs/
mkdir -p /home/docker/nacos/init.d/

3. Modify the configuration file

vim /home/docker/nacos/init.d/custom.properties

The content is as follows:

server.contextPath=/nacos
server.servlet.contextPath=/nacos
server.port=8848

spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://localhost:3306/nacos_devtest_prod?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=user
db.password=pass

nacos.cmdb.dumpTaskInterval=3600
nacos.cmdb.eventTaskInterval=10
nacos.cmdb.labelTaskInterval=300
nacos.cmdb.loadDataAtStart=false
management.metrics.export.elastic.enabled=false
management.metrics.export.influx.enabled=false
server.tomcat.accesslog.enabled=true
server.tomcat.accesslog.pattern=%h %l %u %t "%r" %s %b %D %{User-Agent}i 
nacos.security.ignore.urls=/,/**/*.css,/**/*.js,/**/*.html,/**/*.map,/**/*.svg,/**/*.png,/**/*.ico,/console-fe/public/**,/v1/auth/login,/v1/console/health/**,/v1/cs/**,/v1/ns/**,/v1/cmdb/**,/actuator/**,/v1/console/server/**
nacos.naming.distro.taskDispatchThreadCount=1
nacos.naming.distro.taskDispatchPeriod=200
nacos.naming.distro.batchSyncKeyCount=1000
nacos.naming.distro.initDataRatio=0.9
nacos.naming.distro.syncRetryDelay=5000
nacos.naming.data.warmup=true
nacos.naming.expireInstance=true

Fourth, execute the sql statement

1、下载 
https://github.com/alibaba/nacos/blob/master/config/src/main/resources/META-INF/nacos-db.sql
2、在 mysql 中创建数据库,并且执行 sql 语句
3、修改配置文件信息

5. Start the container

docker run --name nacos -d -p 8848:8848 --privileged=true --restart=always -e JVM_XMS=256m -e JVM_XMX=256m -e MODE=standalone -e PREFER_HOST_MODE=hostname -v /home/docker/nacos/logs/ -v /home/docker/nacos/init.d/custom.properties:/home/nacos/init.d/custom.properties nacos/nacos-server

https://juejin.cn/post/7232959782281920567

Add the group to contact the author vx: xiaoda0423

Warehouse address: https://github.com/webVueBlog/JavaGuideInterview

Guess you like

Origin blog.csdn.net/qq_36232611/article/details/130939522