Spring Cloud Alibaba系列之Nacos服务注册与发现
1、前言简介
服务注册与发现是微服务架构体系中最关键的组件之一。Spring Cloud Alibaba Nacos Discovery组件提供了服务自动注册到 Nacos 服务端的功能,并且能够动态感知和刷新某个服务实例的服务列表。除此之外,Nacos Discovery 也将服务实例的一些元数据信息,例如 host,port, 健康检查 URL,主页等内容注册到 Nacos
2、实验环境准备
- 环境准备:
- 64bit JDK 1.8
- SpringBoot2.3.7.RELEASE
- SpringCloud(Hoxton.SR9)
- SpringCloudAlibaba2.2.2.RELEASE
- Maven 3.2+
- 开发工具
- IntelliJ IDEA
- smartGit
3、启动Nacos Server
学习本博客的服务注册和发现,需要先启动Nacos Server,Nacos Server是一个服务的注册中心,详情可以参考上一篇博客,也可以参考Nacos快速开始手册:https://nacos.io/zh-cn/docs/quick-start.html
4、Aliyun Java Initializr
阿里云提供了可以快速构建项目的网站Aliyun Java Initializr,Java 工程脚手架,用于帮助开发者快速生成工程骨架,链接:https://start.aliyun.com/bootstrap.html,对于初学者还是自己进行maven配置,熟练的开发者可以使用此平台快速构建项目:
5、Sandbox 沙箱环境
阿里的Sandbox 沙箱环境,为开发者带来一套快速上手、免除任何环境依赖、免费、便捷的开发和运行环境。链接:https://start.aliyun.com/handson
6、IDEA Spring Initializr
在IDEA开发软件中,可以使用initializr service url,用于快速创建项目:https://start.aliyun.com
7、启动Nacos服务提供者
选择jdk版本,pom package方式
选择Nacos的Nacos Discovery
自动生成的pom参考,初学者可以自行配置一下maven:
<?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.example.springcloud.alibaba</groupId>
<artifactId>springcloud-alibaba-nacos-discovery</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springcloud-alibaba-nacos-discovery</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>
<!-- Spring WebMVC Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot Actuator Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!-- Spring Cloud Alibaba Nacos Discovert Starter -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</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.example.springcloud.alibaba.nacosdiscovery.SpringcloudAlibabaNacosDiscoveryApplication
</mainClass>
</configuration>
<executions>
<execution>
<id>repackage</id>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
application.properties配置:
# 应用名称
spring.application.name=springcloud-alibaba-nacos-discovery
# 应用服务 WEB 访问端口
server.port=8080
# 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=127.0.0.1:8848
# 注册到 nacos 的指定 namespace,默认为 public
spring.cloud.nacos.discovery.namespace=public
激活Nacos Discovery服务注册和发现
package com.example.springcloud.alibaba.nacosdiscovery.nacosdiscovery;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Configuration;
@EnableDiscoveryClient
@Configuration
public class NacosDiscoveryConfiguration {
}
写个接口测试:
package com.example.springcloud.alibaba.nacosdiscovery.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* <pre>
* ServerController
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/12/25 10:49 修改内容:
* </pre>
*/
@RestController
public class ServerController {
@GetMapping("/api/test/{message}")
public String echo(@PathVariable String message) {
return String.format("echo message:%s", message);
}
}
linux测试接口:
[www@localhost ~]$ curl http://127.0.0.1:8080/api/test/hello
echo message:hello
8、Nacos服务调用
新建一个nacos服务调用例子,服务消费者:
如果需要openFeign,可以加上对应配置:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
在前面的SpringCloud学习,博客链接:SpringCloud博客专栏 ,我们已经接触过SpringCloud服务调用的两种方法:一种是ribbon+restTemplate,另一种是feign服务调用
8.1、@LoadBalanced RestTemplate服务调用
注意加上@LoadBalanced
,实现负载均衡:
package com.example.nacos.nacosdiscovery;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;
@EnableDiscoveryClient
@Configuration
public class NacosDiscoveryConfiguration {
@LoadBalanced
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
}
RestTemplate 调用服务:
package com.example.nacos.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
/**
* <pre>
* RestTemplateController
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/12/25 11:44 修改内容:
* </pre>
*/
@RestController
public class RestTemplateController {
@Autowired
RestTemplate restTemplate;
@GetMapping(value = {
"/api/call/{message}"})
public String call(@PathVariable String message){
return restTemplate.getForObject("http://springcloud-alibaba-nacos-discovery/api/test/"+message,String.class);
}
}
测试:
[www@localhost ~]$ curl http://127.0.0.1:8081/api/call/hello
echo message:hello
8.2、使用OpenFeign服务调用
package com.example.nacos.service;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
/**
* <pre>
* FeignClientService
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/12/25 14:08 修改内容:
* </pre>
*/
@FeignClient(value = "springcloud-alibaba-nacos-discovery")
@Service
public interface FeignClientService {
@GetMapping(value = {
"/api/test/{message}"})
String call(@PathVariable(value = "message") String message);
}
package com.example.nacos.controller;
import com.example.nacos.service.FeignClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* <pre>
* OpenFeignController
* </pre>
*
* <pre>
* @author mazq
* 修改记录
* 修改后版本: 修改人: 修改日期: 2020/12/25 14:32 修改内容:
* </pre>
*/
@RestController
public class OpenFeignController {
@Autowired
private FeignClientService feignClientService;
@GetMapping(value = {
"/api/feign/call/{message}"})
public String feignCall(@PathVariable String message){
return feignClientService.call(message);
}
}
[www@localhost ~]$ curl http://127.0.0.1:8081/api/feign/call/hello
echo message:hello
激活OpenFeign配置:
package com.example.nacos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
public class NacosDiscoveryConsumerSampleApplication {
public static void main(String[] args) {
SpringApplication.run(NacosDiscoveryConsumerSampleApplication.class, args);
}
}
注意要点:
①、@EnableFeignClients要加在Application类?加在配置类SpringBoot扫描不到,原因不是很清楚,估计需要跟下源码才清楚
②、@PathVariable
最好加上value属性,才能匹配到
本博客的例子代码可以在github找到下载链接:代码下载
9、Nacos参考资料
- Nacos中文手册:https://nacos.io/zh-cn/docs/what-is-nacos.html
- Nacos Github WIKI:https://github.com/alibaba/nacos/wiki
- Nacos官网博客:https://nacos.io/zh-cn/blog/index.html
本文同步分享在 博客“smileNicky”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。