mirror of
https://gitee.com/yudaocode/SpringBoot-Labs.git
synced 2026-09-03 05:53:54 +08:00
nacos 注册中心示例
This commit is contained in:
@@ -12,28 +12,28 @@ import org.springframework.web.client.RestTemplate;
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/demo")
|
||||
public class DemoController {
|
||||
@RequestMapping("/consumer")
|
||||
public class ConsumerController {
|
||||
|
||||
@NacosInjected
|
||||
private NamingService namingService;
|
||||
|
||||
private RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
@GetMapping("/provider")
|
||||
public String provider() {
|
||||
return "echo";
|
||||
}
|
||||
|
||||
@GetMapping("/consumer")
|
||||
@GetMapping("/demo")
|
||||
public String consumer() throws IllegalStateException, NacosException {
|
||||
// 获得实例
|
||||
List<Instance> instances = namingService.getAllInstances("demo-application");
|
||||
// 获得首个实例,进行调用
|
||||
Instance instance = instances.stream().findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("未找到对应的 Instance"));
|
||||
Instance instance = null;
|
||||
if (false) {
|
||||
List<Instance> instances = namingService.getAllInstances("demo-application");
|
||||
// 获得首个实例,进行调用
|
||||
instance = instances.stream().findFirst()
|
||||
.orElseThrow(() -> new IllegalStateException("未找到对应的 Instance"));
|
||||
} else {
|
||||
instance = namingService.selectOneHealthyInstance("demo-application");
|
||||
}
|
||||
// 执行请求
|
||||
return restTemplate.getForObject("http://" + instance.toInetAddr() + "/demo/provider",
|
||||
return restTemplate.getForObject("http://" + instance.toInetAddr() + "/provider/demo",
|
||||
String.class);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
package cn.iocoder.springboot.lab44.nacosdemo.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/provider")
|
||||
public class ProviderController {
|
||||
|
||||
@GetMapping("/demo")
|
||||
public String provider() {
|
||||
return "echo";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -3,10 +3,12 @@ spring:
|
||||
name: demo-application # 应用名
|
||||
|
||||
nacos:
|
||||
# Nacos 配置中心的配置项,对应 NacosDiscoveryProperties 配置类
|
||||
discovery:
|
||||
server-addr: 127.0.0.1:18848 # Nacos 服务器地址
|
||||
auto-register: true # 是否自动注册到 Nacos 中。默认为 false。
|
||||
namespace: # 使用的 Nacos 的命名空间,默认为 null。
|
||||
register:
|
||||
service-name: ${spring.application.name} # 注册到 Nacos 的服务名
|
||||
group-name: DEFAULT_GROUP # 使用的 Nacos 服务分组,默认为 DEFAULT_GROUP。
|
||||
cluster-name: cluster01 # 集群名,默认为空。
|
||||
cluster-name: # 集群名,默认为空。
|
||||
|
||||
Reference in New Issue
Block a user