3.2 建立微服务并向Nacos注册服务
- 建立微服务工程项目
-
勾选Nacos Service Discovery依赖
-
打开pom.xml,下载依赖
<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”>
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.2.9.RELEASE
nacos.democonsumer
sentinel
0.0.1-SNAPSHOT
sentinel
Demo project for Spring Boot
<java.version>1.8</java.version>
<spring-cloud-alibaba.version>2.2.1.RELEASE</spring-cloud-alibaba.version>
org.springframework.boot
spring-boot-starter-web
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
org.springframework.boot
spring-boot-starter-test
test
org.junit.vintage
junit-vintage-engine
com.alibaba.cloud
spring-cloud-alibaba-dependencies
${spring-cloud-alibaba.version}
pom
import
org.springframework.boot
spring-boot-maven-plugin
- 设置项目配置文件:application.yml
端口
server:
port: 8083
spring:
application:
name: goods-service
cloud:
nacos服务注册
nacos:
discovery:
server-addr: 172.16.109.118:8848
- 通过 Spring Cloud Alibaba原生注解 @EnableDiscoveryClient 开启服务注册发现功能
// 通过 Spring Cloud 原生注解 @EnableDiscoveryClient 开启服务注册发现功能
@EnableDiscoveryClient
@SpringBootApplication
public class DemoServiceApplication {
public static void main(String[] args) {
SpringApplication.run(DemoServiceApplication.class, args);
}
}
- 建立HTTP接口的商品信息微服务,模拟返回商品列表
/**
- 商品信息微服务-模拟返回商品列表
*/
@RestController
@RequestMapping(“api/goods”)
public class GoodsService {
public static final Logger logger = LoggerFactory.getLogger(GoodsService.class);
// 返回商品列表
@GetMapping
public List getAllGoods(HttpServletRequest httpServletRequest) {
List goods = new ArrayList<>();