ServiceComb官方的示例還是太復雜了,本文創建一個更簡單的ServiceComb restful項目。
一、創建項目
創建一個Maven項目,編輯pom.xml文件,添加如下依賴:
<dependencies>
<dependency>
<groupId>org.apache.servicecomb</groupId>
<artifactId>java-chassis-spring-boot-starter-servlet</artifactId>
</dependency>
</dependencies>
applicaton.properties 文件
server.port=8080
APPLICATION_ID=hello
service_description.name=helloworld
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
除了最后一行
service_description.environment=development
,每一行都是必須的。最后一行的作用是:在開發階段,可以不太關注服務的版本號,否者可能會提示服務名及版本號的問題。
其中服務注冊中心是:http://127.0.0.1:30100,先不使用,等到文末再介紹。
Java代碼
程序入口代碼添加@EnableServiceComb
@SpringBootApplication
@EnableServiceComb
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
創建hello服務,新建HelloEndpoint.java
,內容如下:
@RestSchema(schemaId = "hello")
@RequestMapping(path = "/")
public class HelloEndpoint {
@GetMapping(path = "/hello")
public String hello() {
return "Hello World!";
}
}
注意:
@RequestMapping(path = "/")
不可省略,這和Spring Boot 的@RestController
不同。
運行應用:
mvn spring-boot:run
使用curl localhost:8080/hello
訪問站點
$ curl localhost:8080/hello
"Hello World!"
注意:返回值是帶雙引號的,這與Spring Boot web項目不同。
返回的結果是帶引號的字符串,而一般情況返回字符串,我們不希望帶引號,可以修改HelloEndpoint.java
@RequestMapping(path = "/", produces = MediaType.TEXT_PLAIN_VALUE)
再次訪問,返回值就不帶引號了。
$ curl localhost:8080/hello
Hello World!
添加依賴:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
添加本依賴后可以使用IDE運行程序了。
完整代碼請訪問:https://github.com/redexpress/servicecomb-tutorial/tree/main/hello
重構代碼
新增加一個Hello接口
public interface Hello {
String hello();
}
讓HelloEndpoint 實現 Hello接口
public class HelloEndpoint implements Hello {
省略其它代碼
二、啟用注冊中心
從https://servicecomb.apache.org/release/service-center-downloads/下載ServiceComb Service-Center
我下載的是Mac系統使用的Apache ServiceComb Service-Center 1.3.0 (LATEST) Darwin版。
start-service-center.sh
啟動注冊中心服務,端口30100。
start-frontend.sh
啟動注冊中心前端頁面,端口是30103。
從圖上可以看到我們部署的helloworld服務。