前言
在当今快速变化的技术领域,微服务架构已经成为许多企业和开发团队的首选。而要构建和管理这样的架构,就需要一个强大的服务注册与配置中心。Nacos作为一款开源的动态服务发现、配置管理和服务管理平台,正获得越来越多团队的青睐。本指南将带您深入了解Nacos的核心概念和功能,助您在微服务的道路上驶向成功。
正文
一. 搭建父项目
-
项目名:nacos-parent-2.1
-
添加坐标
xml<parent> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-build</artifactId> <version>2.3.5.RELEASE</version> </parent> <properties> <spring.cloud.version>Hoxton.SR12</spring.cloud.version> <spring.cloud.alibaba.version>2.2.7.RELEASE</spring.cloud.alibaba.version> <mybatis.plus.starter.version>3.4.0</mybatis.plus.starter.version> <durid.starter.version>1.1.10</durid.starter.version> <swagger.version>2.7.0</swagger.version> <jwt.jjwt.version>0.9.0</jwt.jjwt.version> <jwt.joda.version>2.9.7</jwt.joda.version> </properties> <dependencyManagement> <dependencies> <!-- Spring 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>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring.cloud.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> <!-- mybatis-plus --> <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-boot-starter</artifactId> <version>${mybatis.plus.starter.version}</version> </dependency> <!-- Druid连接池 --> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>${durid.starter.version}</version> </dependency> <!--swagger2--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>${swagger.version}</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>${swagger.version}</version> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-javadoc-plugin</artifactId> <configuration> <skip>true</skip> </configuration> </plugin> </plugins> </build>
项目目录结构
二. 服务提供者 Provider
1 搭建服务
-
创建项目:nacos-service-provider-2.1
-
添加依赖:
xml<dependencies> <!-- web 启动类 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- nacos 服务发现 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
-
创建yml文件
yaml#server.port=8070 #spring.application.name=service-provider #spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848 #端口号 server: port: 8070 spring: application: name: service-provider #服务名 cloud: nacos: discovery: server-addr: 127.0.0.1:8848 #nacos服务地址
2 创建服务
- 启动类
*
java
package com.czxy.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@SpringBootApplication
@EnableDiscoveryClient //服务发现
public class TestNacosProviderApplication {
public static void main(String[] args) {
SpringApplication.run(TestNacosProviderApplication.class, args );
}
}
- 处理类controller
kotlin
```
package com.czxy.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@RestController
public class EchoController {
@Resource
private HttpServletRequest request;
@GetMapping("/echo/{string}")
public String echo(@PathVariable String string) {
int serverPort = request.getServerPort();
return "Hello Nacos Discovery " + string + ":" + serverPort;
}
}
```
3 查看服务
- 通过浏览器访问
通过浏览器访问
bash
http://localhost:8070/echo/abc
通过Nacos控制台查看
4 注册异常
三. 服务消费者 Consumer
1 搭建服务
-
项目名:nacos-service-consumer-2.1
-
添加依赖
xml<dependencies> <!-- web 启动类 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- nacos 服务发现 --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- openfeign 远程调用 --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency> </dependencies>
-
创建配置文件
yaml
![1655138182431]()
```
#server.port=8071
#spring.application.name=service-consumer
#spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#端口号
server:
port: 8071
spring:
application:
name: service-consumer #服务名
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848 #nacos服务地址
```
2 创建服务
- 创建启动类
typescript
package com.czxy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@SpringBootApplication
@EnableDiscoveryClient //服务发现
public class TestNacosConsumerApplication {
public static void main(String[] args) {
SpringApplication.run(TestNacosConsumerApplication.class, args );
}
}
- 远程调用配置类
kotlin
package com.czxy.config;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@Component
public class RestTemplateConfig {
@LoadBalanced //负载均衡(通过服务名访问服务)
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
-
处理类
kotlinpackage com.czxy.controller; import org.springframework.web.bind.annotation.*; import org.springframework.web.client.RestTemplate; import javax.annotation.Resource; /** * @author 桐叔 * @email liangtong@itcast.cn */ @RestController public class TestRestController { @Resource private RestTemplate restTemplate; @GetMapping("/echo/{str}") public String echo(@PathVariable String str) { // String url = "http://localhost:8070/echo/" + str; String url = "http://service-provider/echo/" + str; return restTemplate.getForObject(url, String.class); } }
3 查询服务
-
通过浏览器访问
bashhttp://localhost:8071/echo/abc
- 通过Nacos控制台查看
四 配置中心
-
需求:在controller中获得配置信息
- 获得配置的默认值
- 获得yml配置内容
- 获得nacos的配置内容
1 搭建服务
-
项目名:nacos-config-2.1
-
添加坐标:
xml
<dependencies>
<!-- web 启动器 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- nacos 服务发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacos 配置-->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
</dependencies>
- 创建yml配置文件:bootstrap.yml
yaml
server:
port: 8072 # 端口号
spring:
application:
name: config-service # 服务名
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 # nacos 服务地址
prefix: ${spring.application.name} #data ID的前缀,默认服务名
file-extension: yaml # data ID的后缀:config-service.yaml
group: DEFAULT_GROUP # 组名
discovery:
server-addr: 127.0.0.1:8848 #nacos服务地址
2 创建服务
- 编写启动类
typescript
package com.czxy.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@SpringBootApplication
@EnableDiscoveryClient
public class TestNacosCloudConfigApplication {
public static void main(String[] args) {
SpringApplication.run(TestNacosCloudConfigApplication.class, args);
}
}
- 编写处理类
kotlin
package com.czxy.nacos.controller;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* @author 桐叔
* @email liangtong@itcast.cn
*/
@RestController
@RequestMapping("/config")
@RefreshScope // 动态刷新配置信息
public class ConfigController {
@Value("${czxy.message:默认值}")
private String msg;
/**
* http://localhost:8072/config/get
*/
@RequestMapping("/get")
public String get() {
return msg;
}
}
3 查询服务
- 情况1,访问"默认数据"
bash
http://localhost:8072/config/get
-
情况2,访问yml文件配置信息
yamlczxy: message: 测试数据
- 情况3:访问nacos中的配置数据
3.4.4 整合知多少
- 在 Nacos Spring Cloud 中,
dataId
的完整格式如下
bash
${prefix}-${spring.profile.active}.${file-extension}
-
显示profile中的数据
- 1)编写profile:application-demo.yml
yml
server:
port: 8073 # 端口号
czxy:
message: demo数据
2)修改启动项
ini
-Dspring.profiles.active=demo
* 3)删除nacos配置后,测试
* nacos 默认配置
markdown
* 1)nacos配置 `config-service.yaml` 的 Data ID
- 2)测试
-
nacos 配置 profile
- 1)配置nacos profile :
config-service-demo.yaml
- 1)配置nacos profile :
* 2)测试
5 nacos 配置文件加载顺序1
-
spring boot、nacos各种配置文件的加载顺序
1.bootstrap.yml #引导文件,由spring cloud提供
2.application.yml #应用程序文件,有spring boot提供
3.application-[profile].yml #应用程序profile文件,有spring boot提供
4.[serviceName].yml #nacos配置
5.[serviceName]-[profile].yml #nacos配置
- 后面加载的文件,将覆盖前面文件的配置内容
* 参考官方文实例档
arduino
https://nacos.io/zh-cn/docs/quick-start-spring-cloud.html
结语
通过本指南,您已经对Nacos有了了解,希望您能够通过Nacos轻松构建和管理微服务架构,实现更高效的开发和部署。在不断变化的技术世界中,保持对新技术的学习和掌握将会成为您成功的关键。感谢您阅读本指南,祝您在微服务架构的旅途中一帆风顺!