ServiceComb官方的示例還是太復(fù)雜了,本文創(chuàng)建一個更簡單的ServiceComb restful項目。
一、創(chuàng)建項目
創(chuàng)建一個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,每一行都是必須的。最后一行的作用是:在開發(fā)階段,可以不太關(guān)注服務(wù)的版本號,否者可能會提示服務(wù)名及版本號的問題。
其中服務(wù)注冊中心是:http://127.0.0.1:30100,先不使用,等到文末再介紹。
Java代碼
程序入口代碼添加@EnableServiceComb
@SpringBootApplication
@EnableServiceComb
public class HelloApplication {
public static void main(String[] args) {
SpringApplication.run(HelloApplication.class, args);
}
}
創(chuàng)建hello服務(wù),新建HelloEndpoint.java,內(nèi)容如下:
@RestSchema(schemaId = "hello")
@RequestMapping(path = "/")
public class HelloEndpoint {
@GetMapping(path = "/hello")
public String hello() {
return "Hello World!";
}
}
注意:
@RequestMapping(path = "/")不可省略,這和Spring Boot 的@RestController不同。
運行應(yīng)用:
mvn spring-boot:run
使用curl localhost:8080/hello訪問站點
$ curl localhost:8080/hello
"Hello World!"
注意:返回值是帶雙引號的,這與Spring Boot web項目不同。
返回的結(jié)果是帶引號的字符串,而一般情況返回字符串,我們不希望帶引號,可以修改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
重構(gòu)代碼
新增加一個Hello接口
public interface Hello {
String hello();
}
讓HelloEndpoint 實現(xiàn) Hello接口
public class HelloEndpoint implements Hello {
省略其它代碼
二、啟用注冊中心
從https://servicecomb.apache.org/release/service-center-downloads/下載ServiceComb Service-Center
我下載的是Mac系統(tǒng)使用的Apache ServiceComb Service-Center 1.3.0 (LATEST) Darwin版。
start-service-center.sh啟動注冊中心服務(wù),端口30100。
start-frontend.sh啟動注冊中心前端頁面,端口是30103。

從圖上可以看到我們部署的helloworld服務(wù)。