所有代码都在github上:https://github.com/demonruin/cloud2020/tree/master
所有的资料都来源官网,首先先打开Spring的官网https://spring.io,然后进入Projects分类,进入SpringCloud的官网https://spring.io/projects/spring-cloud,再点击Spring Cloud Alibaba,选择learn,选择版本进入Reference Doc. 然后选择Spring Cloud Alibaba Nacos Discovery.
下面开始演示构建基于Nacos注册中心的9001服务提供者案例
1、构建项目module,cloudalibaba-nacos-provider-payment9001
2、添加pom依赖
①在父工程pom中添加依赖:如果您是Maven Central用户,则将我们的BOM添加到pom.xml <dependencyManagement>部分。这将允许您忽略任何Maven依赖项的版本,而是将版本委派给BOM。
<!--spring cloud alibaba 2.1.0.RELEASE-->
<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>
②在本微服务中添加nacos依赖,及其他相关依赖组件
<dependencies>
<!--SpringCloud ailibaba nacos -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- SpringBoot整合Web组件 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--日常通用jar包配置-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</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>
</dependency>
</dependencies>
3、构建yml文件,添加nacos相关配置,来源依旧是官网的配置
server:
port: 9001
spring:
application:
name: nacos-provider-payment
cloud:
nacos:
discovery:
server-addr: localhost:8848
#暴露所有端点,和actuator监控有关
management:
endpoints:
web:
exposure:
exclude: "*"
4、构建主启动类,并添加@EnableDiscoveryClient等相关注解
@SpringBootApplication
@EnableDiscoveryClient
public class NacosProviderPaymentMain9001 {
public static void main(String[] args) {
SpringApplication.run(NacosProviderPaymentMain9001.class,args);
}
}
5、构建controller业务类,进行测试~
package com.king.springcloud.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
/**
* created by king on 2020/5/8 12:38 下午
*/
@RestController
@Slf4j
public class PaymentController {
@Value("${server.port}")
private String serverPort;
@GetMapping("/nacos/payment/{id}")
public String getNacosPayment(@PathVariable("id") Integer id){
return "this is Nacos Payment Service id=\t"+id+"\t server port :\t"+serverPort;
}
}
6、启动main函数,然后进入nacos控制台查看是否注册进注册中心了
7、测试接口地址是否畅通
为了测试微服务的负载均衡模式,需要多提供几个服务提供者,所以依法炮制一个cloudalibaba-nacos-provider-payment9002,只需要改端口号即可~,然后可以在nacos控制台查看多了一个微服务实例