1. 概述
在本教程中,我們將展示使用 MSF4J 框架進行 微服務開發。
這是一個輕量級工具,提供了一種便捷的方式來構建各種高性能服務。
2. Maven 依賴項
為了構建基於 MSF4J 的微服務,我們需要比平時更多的 Maven 配置。該框架的簡潔性和強大性也伴隨着一定的代價:基本上,我們需要定義一個父級 Artifact,以及主類:<parent>
<groupId>org.wso2.msf4j</groupId>
<artifactId>msf4j-service</artifactId>
<version>2.6.0</version>
</parent>
<properties>
<microservice.mainClass>
com.baeldung.msf4j.Application
</microservice.mainClass>
</properties>
最新版本的 msf4j-service 可在 Maven Central 上找到。
接下來,我們將展示三種不同的微服務場景。首先,一個極簡示例,然後是 RESTful API,最後是 Spring 集成示例。
3. 基本項目
3.1. 簡單 API
我們將發佈一個簡單的 Web 資源。
此服務提供了一個類,使用了註解,其中每個方法處理請求。通過這些註解,我們設置了方法、路徑和每個請求所需的參數。
返回的內容類型是純文本:
@Path("/")
public class SimpleService {
@GET
public String index() {
return "Default content";
}
@GET
@Path("/say/{name}")
public String say(@PathParam("name") String name) {
return "Hello " + name;
}
}
請記住,所有類和註解都只是 標準 JAX-RS 元素,我們已經在本文中討論過。
3.2. 應用程序
我們可以使用以下主類啓動微服務,其中我們設置、部署和運行前面定義的服務:
public class Application {
public static void main(String[] args) {
new MicroservicesRunner()
.deploy(new SimpleService())
.start();
}
}
如果我們想要,可以在此處鏈接 deploy 調用以同時運行多個服務:
new MicroservicesRunner()
.deploy(new SimpleService())
.deploy(new ComplexService())
.start()
3.3. 運行微服務
要運行 MSF4J 微服務,我們有幾個選項:
- 在 IDE 中,作為 Java 應用程序運行
- 運行生成的 jar 包
一旦啓動,您可以在 http://localhost:9090 上查看結果。
3.4. 啓動配置
我們可以通過向啓動代碼添加條款來調整配置 很多方式:
new MicroservicesRunner()
.addInterceptor(new MetricsInterceptor())
.deploy(new SimpleService())
.start();
或者,我們可以添加全局攔截器,例如用於身份驗證的攔截器:
new MicroservicesRunner()
.addGlobalRequestInterceptor(newUsernamePasswordSecurityInterceptor())
.deploy(new SimpleService())
.start();
或者,如果我們需要會話管理,我們可以設置會話管理器:
new MicroservicesRunner()
.deploy(new SimpleService())
.setSessionManager(new PersistentSessionManager())
.start();
有關這些場景的更多詳細信息,以及一些工作示例,請查看 MSF4J 的 官方 GitHub 倉庫。
4. 構建 API 微服務
我們展示了最簡單的例子。現在我們將轉向一個更現實的項目。
這次,我們展示瞭如何使用所有典型 CRUD 操作構建一個管理餐食倉庫的 API。
4.1. 模型
模型只是一個簡單的 POJO,表示一餐:
public class Meal {
private String name;
private Float price;
// getters and setters
}
4.2. API
我們將 API 構建為 Web 控制器。使用標準註解,我們為每個函數設置如下:
- URL 路徑
- HTTP 方法:GET、POST 等
- 輸入(@Consumes)內容類型
- 輸出(@Produces)內容類型
因此,我們為每個標準 CRUD 操作創建一個方法:
@Path("/menu")
public class MenuService {
private List<Meal> meals = new ArrayList<Meal>();
@GET
@Path("/")
@Produces({ "application/json" })
public Response index() {
return Response.ok()
.entity(meals)
.build();
}
@GET
@Path("/{id}")
@Produces({ "application/json" })
public Response meal(@PathParam("id") int id) {
return Response.ok()
.entity(meals.get(id))
.build();
}
@POST
@Path("/")
@Consumes("application/json")
@Produces({ "application/json" })
public Response create(Meal meal) {
meals.add(meal);
return Response.ok()
.entity(meal)
.build();
}
// ... 其他 CRUD 操作
}
4.3. 數據轉換功能
MSF4J 提供了對不同數據轉換庫的支持,例如 GSON(通過默認提供)和 Jackson(通過 msf4j-feature 依賴)。例如,我們可以顯式使用 GSON:
@GET
@Path("/{id}")
@Produces({ "application/json" })
public String meal(@PathParam("id") int id) {
Gson gson = new Gson();
return gson.toJson(meals.get(id));
}
順便一提,我們已經在 @Consumes 和 @Produces 註解中使用花括號,以便可以設置多個 mime 類型。
4.4. 運行 API 微服務
我們像以前的示例一樣運行微服務,通過一個 Application 類來發布 MenuService。
啓動後,您可以在 http://localhost:9090/menu 處查看結果。
5. MSF4J and Spring
We can also apply Spring to our MSF4J-based microservices, from which we’ll get its dependency injection features.
5.1. Maven Dependencies
We’ll have to add the appropriate dependencies to the previous Maven configuration to add Spring and Mustache support:
<dependencies>
<dependency>
<groupId>org.wso2.msf4j</groupId>
<artifactId>msf4j-spring</artifactId>
<version>2.8.11</version>
</dependency>
<dependency>
<groupId>org.wso2.msf4j</groupId>
<artifactId>msf4j-mustache-template</artifactId>
<version>2.8.11</version>
</dependency>
</dependencies>
The latest version of msf4j-spring and msf4j-mustache-template can be found on Maven Central.
5.2. Meal API
This API is just a simple service, using a mock meal repository. Notice how we use Spring annotations for auto-wiring and to set this class as a Spring service component.
@Service
public class MealService {
@Autowired
private MealRepository mealRepository;
public Meal find(int id) {
return mealRepository.find(id);
}
public List<Meal> findAll() {
return mealRepository.findAll();
}
public void create(Meal meal) {
mealRepository.create(meal);
}
}
5.3. Controller
We declare the controller as a component and Spring provides the service through auto-wiring. The first method shows how to serve a Mustache template and the second a JSON resource:
@Component
@Path("/meal")
public class MealResource {
@Autowired
private MealService mealService;
@GET
@Path("/")
public Response all() {
Map map = Collections.singletonMap("meals", mealService.findAll());
String html = MustacheTemplateEngine.instance()
.render("meals.mustache", map);
return Response.ok()
.type(MediaType.TEXT_HTML)
.entity(html)
.build();
}
@GET
@Path("/{id}")
@Produces({ "application/json" })
public Response meal(@PathParam("id") int id) {
return Response.ok()
.entity(mealService.find(id))
.build();
}
}
5.4. Main Program
In the Spring scenario, this is how we get the microservice started:
public class Application {
public static void main(String[] args) {
MSF4JSpringApplication.run(Application.class, args);
}
}
Once started, we can see the result at http://localhost:8080/meals. The default port differs in Spring projects, but we can set it to whatever port we want.
5.5. Configuration Beans
To enable specific settings, including interceptors and session management, we can add configuration beans.
For example, this one changes the default port for the microservice:
@Configuration
public class PortConfiguration {
@Bean
public HTTPTransportConfig http() {
return new HTTPTransportConfig(9090);
}
}
6. 結論
在本文中,我們介紹了 MSF4J 框架,通過不同的場景構建基於 Java 的微服務。
關於這個概念有很多討論,但 已經有一些理論背景,MSF4J 提供了一種便捷且標準化的方式來應用這個模式。
此外,如果您想進一步閲讀,可以查看使用 Eclipse Microprofile 構建微服務,以及我們關於 Spring Boot 和 Spring Cloud 中 Spring 微服務的指南。