在上一篇筆記創(chuàng)建了名稱為helloworld的服務(wù)。
現(xiàn)在創(chuàng)建名為math的為服務(wù)。
準備工作
從上一篇筆記復(fù)制 application.properties 文件,修改端口號和service_description.name配置,完整的文件如下:
server.port=8081
APPLICATION_ID=hello
service_description.name=math
service_description.version=0.1
servicecomb.service.registry.address=http://127.0.0.1:30100
servicecomb.rest.address=0.0.0.0:${server.port}
service_description.environment=development
復(fù)制之前的Hello接口文件:
package io.github.redexpress.hello;
public interface Hello {
String hello();
}
注意:保持本文件與上文一摸一樣,包括package聲明。
這個接口代碼是重復(fù)的,重構(gòu)時可以考慮把接口放在一個單獨的項目中。
從上一篇筆記復(fù)制pom.xml的依賴項,并添加Lombok依賴:
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
添加代碼
創(chuàng)建SimpleEndpoint.java
@RestSchema(schemaId = "math")
@RequestMapping(path = "/")
public class SimpleEndpoint {
SimpleService simpleService;
@Autowired
public SimpleEndpoint(SimpleService simpleService) {
this.simpleService = simpleService;
}
@GetMapping(path = "/sayhello/{name}")
public HelloVO sayHello (@PathVariable(value = "name") String name) {
return simpleService.sayHello(name);
}
}
創(chuàng)建Java值對象類HelloVO.java:
@Data
@Builder
public class HelloVO {
String message;
String name;
String instanceId;
}
創(chuàng)建服務(wù)接口SimpleService.java:
public interface SimpleService {
HelloVO sayHello(String name);
String instanceId();
}
添加實現(xiàn):
這里介紹微服務(wù)調(diào)用的兩種方式:
- 使用
RestTemplate - 使用遠程接口
@RpcReference
使用RestTemplate
使用RestTemplate調(diào)用微服務(wù)的URL格式為:
cse://微服務(wù)名稱/微服務(wù)路徑
調(diào)用helloworld微服務(wù)的URL是"cse://helloworld/hello"
完整代碼
private static RestTemplate restTemplate = RestTemplateBuilder.create();
public HelloVO sayHello(String name) {
String message = restTemplate.getForObject("cse://helloworld/hello", String.class);
return HelloVO.builder().message(message).name(name).instanceId(instanceId()).build();
}
使用遠程接口
聲明遠程接口:
@RpcReference(microserviceName = "helloworld", schemaId = "hello")
private static Hello hello;
調(diào)用就很簡單了,和普通的Java方法調(diào)用類似,代碼如下:
private static Hello hello;
public HelloVO sayHello(String name) {
String message = hello.hello();
return HelloVO.builder().message(message).name(name).instanceId(instanceId()).build();
}
注意:1. 使用RestTemplate和遠程接口調(diào)用,要求互相調(diào)用的微服務(wù)的APPLICATION_ID是相同的。2. service_description.environment的值也要相同。
當(dāng)上面提到的微服務(wù)調(diào)用方式條件不滿足時怎么調(diào)用呢?直接用HTTP訪問就行了哦。
項目代碼還有一段顯示instanceId的代碼,本文就不列出了。
完整代碼在:https://github.com/redexpress/servicecomb-tutorial/tree/main/simpleweb
測試
啟動注冊中心,啟動helloworld服務(wù)、math服務(wù)
使用curl localhost:8081/sayhello/bill命令,返回類似:
{"message":"Hello World!","name":"bill","instanceId":"3c79097219dc11eb8d42acbc32a4ce49"}