Download link:
https://pan.baidu.com/s/1E9J52g6uW_VFWY34fHL6zA Extraction code: vneh
Spring Cloud Alibaba Service Registration and Configuration Center (very detailed)
jEnter the bin directory under the Nacos installation directory, enter cmd, and start Nacos in stand-alone mode
startup.cmd -m standalone
Visit the Nacos interface, http://localhost:8848/nacos
Build a service provider and register in Nacos
Add dependencies in pom.xml
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Added in the configuration file
spring:
application:
name: nacos-payment-provider # 服务的名称
cloud:
nacos:
discovery:
server-addr: localhost:8848 #配置Nacos地址
management:
endpoints:
web:
exposure:
include: '*'
Add annotations to the startup class
@EnableDiscoveryClient // 开启 Nacos 服务发现功能
@SpringBootApplication
public class PaymentMain9001
{
public static void main(String[] args) {
SpringApplication.run(PaymentMain9001.class, args);
}
}
controller layer
@RestController
public class PaymentController
{
@Value("${server.port}")
private String serverPort;
@GetMapping(value = "/payment/nacos/{id}")
public String getPayment(@PathVariable("id") Integer id)
{
return "nacos registry, serverPort: "+ serverPort+"\t id"+id;
}
}
Start the project, view the service list, and you can find that a service has been added to the service list
Build service consumers, register in Nacos
Introduce dependencies
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
configuration file
spring:
application:
name: nacos-order-consumer
cloud:
nacos:
discovery:
server-addr: localhost:8848
#消费者将要去访问的微服务名称(注册成功进nacos的微服务提供者)
service-url:
nacos-user-service: http://nacos-payment-provider
Annotate the startup class: @EnableDiscoveryClient
Ribbon is integrated in Nacos, so Nacos automatically supports load balancing.
Define the RestTemplate configuration class, which can be used to call the rest service
/**
* @auther zzyy
* @create 2020-02-23 14:45
*/
@Configuration
public class ApplicationContextConfig
{
@Bean
@LoadBalanced // 使用RestTemplate结合ribbon来做负载均衡的时候已经要加上这个注解
public RestTemplate getRestTemplate()
{
return new RestTemplate();
}
}
controller layer
@RestController
@Slf4j
public class OrderNacosController
{
@Resource
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serverURL;
@GetMapping(value = "/consumer/payment/nacos/{id}")
public String paymentInfo(@PathVariable("id") Long id)
{
return restTemplate.getForObject(serverURL+"/payment/nacos/"+id,String.class);
}
}
Start the project
Visit: http://localhost:83/consumer/payment/nacos/13 to view the effect
and find that 9001 and 9002 appear alternately
Nacos as a configuration center
add dependencies
<!--nacos-config-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<!--nacos-discovery-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Configuration center, Nacos as a configuration center has two configuration files bootstrap.yml and application.yml
Nacos is the same as springcloud-config. When the project is initialized, it is necessary to ensure that the configuration is pulled from the configuration center first . Only after the configuration is pulled can the project start normally.
The loading of configuration files in springboot is prioritized sequentially, and bootstrap has a higher priority than application
bootstrap.yml
# nacos配置
server:
port: 3377
spring:
application:
name: nacos-config-client
cloud:
nacos:
# 服务注册
discovery:
server-addr: localhost:8848 #Nacos服务注册中心地址
# 作为服务配置的客户端
config:
server-addr: localhost:8848 #Nacos作为配置中心地址
file-extension: yaml #指定yaml格式的配置
#group: DEV_GROUP
#namespace: 7d8f0f5a-6a53-4785-9686-dd460158e5d4
# ${spring.application.name}-${spring.profile.active}.${spring.cloud.nacos.config.file-extension}
# nacos-config-client-dev.yaml
# nacos-config-client-test.yaml ----> config.info
application.yml
spring:
profiles:
active: dev # 表示开发环境
#active: test # 表示测试环境
#active: info
Annotate the main startup class: @EnableDiscoveryClient
controller
@RestController
@RefreshScope //支持Nacos的动态刷新功能。
public class ConfigClientController
{
@Value("${config.info}")
private String configInfo;
@GetMapping("/config/info")
public String getConfigInfo() {
return configInfo;
}
}
The composition format of dataid in Nacos and the matching rules with the SpringBoot configuration file
Nacos add configuration file
Summary:
The naming rules of Data ID are as follows, pay attention to the suffix name to select the yaml
startup project, visit: http://localhost:3377/config/info
Nacos comes with dynamic refresh , modify the configuration content of nacos-config-client-dev.yaml in Nacos, and the result of the found request will also be returned
If you want to switch profiles now
There are two files
nacos-config-client-dev.yaml and nacos-config-client-test.yaml in the Nacos configuration. The difference between them is that they are different from tets and dev.
If you want to use the configuration file of the dev environment, you need to modify the Nacos Configure the application.yml configuration file of the central module
Nacos group configuration
The group configuration is to use the same configuration file name in different scenarios.
The DataID name is the same, the Group name is different , the same configuration file name, but not under the same group.
How to use configuration files under different groups?
Configure in bootstrap.yml The grouping to use is specified in the file
The combination of the following two configurations is to find the info configuration file under the DEV_GROUP group
Effect: It shows that the info configuration file under the DEV_GROUP group is used
Nacos namespace configuration
Select a new namespace in the namespace, and you can automatically generate
two more spaces in the namespace ID service list and configuration list
Add two configuration files in the dev space, the DataID is the same, but the grouping is different
in the bootstrap.yml configuration file Add group configuration and namespace configuration
namespace: used to specify the namespace
application.yml specifies the dev environment
The above two configurations will find the TEST_GROUP group in the namespace id: 63fcd633-6d24-4dc8-b2ae-fdee979b0507 , the configuration of the dev environment in
Result:
Summary: First find the namespace, then find the group, and finally find the environment
Nacos persistent configuration
Nacos comes with an embedded database derby by default.
Every Nacos comes with a derby database. When building a cluster, there is no way to ensure that the configuration of so many Nacos can be unified
Configure derby to switch to mysql database
There is a sql script file in the conf directory of Nacos: nacos-mysql.sql
1. Create a new database: nacos_config
2. Run the script file
3. Modify the conf/application.properties file to add support for mysql data source configuration (currently only supports mysql ), add the url, username and password of the mysql data source.
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=root
db.password=root
After restarting Nacos, the added configuration will be added to the mysql table
Nacos cluster configuration
Nacos 2.0.3 Linux system detailed tutorial on building a cluster.
In the actual production environment, there must be at least three Nacos. If there is only one, once a single point of failure occurs, the entire service will directly use the GG
cluster architecture:
- Nginx cluster
- Nacos cluster
- Mysql cluster (master-slave separation)
Install Nacos under Linux
Download nacos-server-2.1.0.tar.gz
Download nacos-server-1.4.2.tar.gz
Create a new mynacos under /opt, store the nacos cluster,
upload nacos-server-2.1.0.tar.gz to mynacos, decompress
tar -zxvf nacos-server-2.1.0.tar.gz
Configure nacos to correspond to mysql persistence
Configure the Nacos database address: Create a new database nacos-config, run the sql script under config,
modify the application.properties file, add
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=root
db.password=root
Nacos cluster configuration cluster.conf on Linux server
Use the hostname -i command to view the real ip of the machine.
This ip cannot be written as 127.0.0.1. It must be an ip that can be recognized by the Linux command hostname -i.
Set three machines as a cluster, and the ports are 333, 444, and 555 respectively
. Edit the cluster.conf* file and delete All content, then add the following content
你的ip:333
你的ip:444
你的ip:555
Build a cluster
Modify the application.properties file, configure mysql ,
modify the cluster.conf file, and configure the cluster port number.
Copy three points nacos_3333, nacos_4444, nacos_5555
and modify the server.port in the application.properties configuration file to 3333, 4444, 5555
respectively, enter the bin directory to start
./startup.sh
Execute the command to view the process after the startup is successful
ps -ef|grep nacos
configure nginx
Edit nginx configuration file, add:
upstream cluster{
server 127.0.0.1:3333
server 127.0.0.1:4444
server 127.0.0.1:5555
}
server {
listen 1111;
server_name localhost;
location / {
proxy_pass http://cluster;
}
}
Restart nginx ./nginx -c specifies the configuration file to start
./nginx -c /www/server/nginx/conf/nginx.conf