注冊中心(nacos)
一、版本管理
- Spring Boot 2.2.5.RELEASE
- Spring Cloud Hoxton.SR3
- Spring Cloud Alibaba 2.2.1.RELEASE
二、依賴引入
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
<spring-cloud.version>Hoxton.SR3</spring-cloud.version>
</properties>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>2.2.1.RELEASE</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>
</dependencies>
</dependencyManagement>
三、接入項目
1、注冊中心依賴
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
2、bootstrap.properties
spring.cloud.nacos.server-addr=127.0.0.1:8848
spring.application.name=test-demo
有時新建的properties文件會圖標異常,配置沒有提示。
IntelliJ IDEA按一下步驟操作:
- File ==> Project Settings ==> Modules ==> Spring
- 點擊右側上方的綠色圖標(Spring的icon)
- 點擊“+”號
- 選擇文件后,一路“OK”即可。
3、application.yml
spring:
cloud:
nacos:
config:
server-addr: 127.0.0.1:8848 # nacos-server 地址
application:
# 項目名稱
name: test-demo # 項目名稱
4、啟動類配置
@SpringBootApplication
// @EnableDiscoveryClient注解開啟服務注冊與發現功能
@EnableDiscoveryClient
public class ProviderApplication {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
四、OpenFeign
1、引入open-feign
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2、啟動類
@SpringBootApplication
// Feign掃描的包路徑
@EnableFeignClients(basePackages = "xxx.xxx.xxx")
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}
3、service
// test-demo為想要調用接口在注冊中心中的名稱
@FeignClient("test-demo")
public interface DemoService {
// 此處路徑要寫全。比如調用接口的請求路徑為/demo/show,此處也為/demo/show
@RequestMapping("/demo/show")
public String show();
}
4、controller
@Controller
public class DemoController {
// 正常注入即可
@Autowired
DemoService demoService;
@RequestMapping("/hello")
public String helloName() {
return demoService.show();
}
}