- 创建SpringBoot项目 (user-server)
- 引入依赖
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>net.logstash.logback</groupId>
<artifactId>logstash-logback-encoder</artifactId>
</dependency>
</dependencies>
- application.yml 配置
# 配置服务端口
server:
port: 8801
spring:
# 配置服务名称
application:
name: user-server
# 配置nacos注册中心地址
cloud:
nacos:
discovery:
server-addr: localhost:8848
- 以同样的步骤创建一个 order-server
-
启动服务,在nacos页面可以看到两个服务已经注册
- order-server 提供一个API
# order-server
@RestController
@RequestMapping("/orders")
public class OrderController {
@GetMapping("/{orderId}")
public String getOrderById(@PathVariable String orderId) {
return orderId + " - orders";
}
}
- user-server 使用 RestTemplate 实现调用 order-server
# user-server
@Service
public class UserServiceImpl implements UserService {
@Autowired
private DiscoveryClient discoveryClient;
@Autowired
private RestTemplate restTemplate;
@Override
public String getUserOrderById(String orderId) {
List<ServiceInstance> instances = discoveryClient.getInstances("order-server");
String userServerAddress = instances.stream()
.map(ServiceInstance::getUri)
.findFirst().orElseThrow(() -> new RuntimeException("No Instances."))
.toString();
return restTemplate.getForObject(
userServerAddress + "/orders/{orderId}",
String.class,
orderId);
}
}
- 为了方便测试,这里使用junit,停掉已经启动的 user-server
@Autowired
private UserService userService;
@Test
public void getOrderById() {
String order = userService.getUserOrderById("E000202003170001");
System.out.println(order);
}
-
结果