nacos 注册中心示例

This commit is contained in:
YunaiV
2020-01-24 22:14:31 +08:00
parent ac9fbbeab3
commit 2cb44e639e
3 changed files with 32 additions and 14 deletions

View File

@@ -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);
}

View File

@@ -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";
}
}

View File

@@ -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: # 集群名,默认为空。