微服務(wù)架構(gòu)
微服務(wù)架構(gòu)近年來受到很多人的推崇,什么是微服務(wù)架構(gòu)?先參考一段定義:
微服務(wù)架構(gòu)(Microservices Architecture)是一種架構(gòu)風(fēng)格(Architectural Style)和設(shè)計(jì)模式,提倡將應(yīng)用分割成一系列細(xì)小的服務(wù)糠排,每個(gè)服務(wù)專注于單一業(yè)務(wù)功能,運(yùn)行于獨(dú)立的進(jìn)程中,服務(wù)之間邊界清晰螺垢,采用輕量級(jí)通信機(jī)制(如HTTP/REST)相互溝通、配合來實(shí)現(xiàn)完整的應(yīng)用赖歌,滿足業(yè)務(wù)和用戶的需求枉圃。
引用 - 基于容器云的微服務(wù)架構(gòu)實(shí)踐
簡(jiǎn)而言之就是服務(wù)輕量級(jí)化和模塊化,可獨(dú)立部署庐冯。其帶來的好處包括:解耦合程度更高孽亲,屏蔽底層復(fù)雜度展父;技術(shù)選型靈活赁酝,可方便其他模塊調(diào)用;易于部署和擴(kuò)展等旭等。與NodeJs等其他語言相比酌呆,Java相對(duì)來說實(shí)現(xiàn)微服務(wù)較為復(fù)雜一些,開發(fā)一個(gè)Web應(yīng)用需要經(jīng)歷編碼-編譯打包-部署到Web容器-啟動(dòng)運(yùn)行
四步搔耕,但是開源框架Spring Boot的出現(xiàn)隙袁,讓Java微服務(wù)的實(shí)現(xiàn)變得很簡(jiǎn)單,由于內(nèi)嵌了Web服務(wù)器弃榨,無需“部署到Web容器”菩收,三步即可實(shí)現(xiàn)一個(gè)Web微服務(wù)。而且由于Spring Boot可以和Spring社區(qū)的其他框架進(jìn)行集成鲸睛,對(duì)于熟悉Spring的開發(fā)者來說很容易上手娜饵。下面本文會(huì)描述一個(gè)簡(jiǎn)易用戶管理微服務(wù)的實(shí)例,初步體驗(yàn)Spring Boot微服務(wù)開發(fā)官辈。
開發(fā)環(huán)境
- JDK 1.8
- Maven 3.0+
- Eclipse或其他IDE
- 本文程序可到github下載
添加依賴
maven的pom.xml配置文件
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<!-- inherit defaults from Spring Boot -->
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.0.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Spring Boot starter POMs -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Spring Boot JPA POMs -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Spring Boot Test POMs -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
<!-- H2 POMs -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
</dependencies>
<build>
<finalName>webapp-springboot-angularjs-seed</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
這里首先繼承了spring-boot-starter-parent
的默認(rèn)配置箱舞,然后依次引入
-
spring-boot-starter-web
用來構(gòu)建REST微服務(wù) -
spring-boot-starter-data-jpa
利用JPA用來訪問數(shù)據(jù)庫 -
h2
Spring Boot集成的內(nèi)存數(shù)據(jù)庫 -
spring-boot-starter-test
用來構(gòu)建單元測(cè)試,內(nèi)含JUnit
程序結(jié)構(gòu)
|____sample
| |____webapp
| | |____ws
| | | |____App.java 啟動(dòng)程序
| | | |____controller
| | | | |____UserController.java 用戶管理的RESTful API
| | | |____domain
| | | | |____User.java 用戶信息
| | | |____exception
| | | | |____GlobalExceptionHandler.java 異常處理
| | | | |____UserNotFoundException.java 用戶不存在的異常
| | | |____repository
| | | | |____UserRepository.java 訪問用戶數(shù)據(jù)庫的接口
| | | |____rest
| | | | |____RestResultResponse.java Rest請(qǐng)求的狀態(tài)結(jié)果
| | | |____service
| | | | |____UserService.java 用戶管理的服務(wù)
用SpringApplication實(shí)現(xiàn)啟動(dòng)程序
import java.util.Arrays;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import com.leonlu.code.sample.webapp.ws.domain.User;
import com.leonlu.code.sample.webapp.ws.service.UserService;
@SpringBootApplication
public class App {
@Bean
CommandLineRunner init(UserService userService) {
// add 5 new users after app are started
return (evt) -> Arrays.asList("john,alex,mike,mary,jenny".split(","))
.forEach(item -> {
User user = new User(item, (int)(20 + Math.random() * 10));
userService.addUser(user);});
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
-
@SpringBootApplication
相當(dāng)于@Configuration
,@EnableAutoConfiguration
,@ComponentScan
三個(gè)注解拳亿。用于自動(dòng)完成Spring的配置和Bean的構(gòu)建晴股。 - main方法中的SpringApplication.run將啟動(dòng)內(nèi)嵌的Tomcat服務(wù)器,默認(rèn)端口為8080
- CommandLineRunner用于在啟動(dòng)后調(diào)用UserService肺魁,創(chuàng)建5個(gè)新用戶
利用RestController構(gòu)建Restful API
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.leonlu.code.sample.webapp.ws.domain.User;
import com.leonlu.code.sample.webapp.ws.rest.RestResultResponse;
import com.leonlu.code.sample.webapp.ws.service.UserService;
@RestController
@RequestMapping("/user")
public class UserController {
private UserService userService;
@Autowired
public UserController(UserService userService) {
this.userService = userService;
}
@RequestMapping(method = RequestMethod.GET)
public Collection<User> getUsers() {
return userService.getAllUsers();
}
@RequestMapping(method = RequestMethod.POST, consumes = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public User addUser(@RequestBody User user) {
if(user.getName() == null || user.getName().isEmpty()) {
throw new IllegalArgumentException("Parameter 'name' must not be null or empty");
}
if(user.getAge() == null) {
throw new IllegalArgumentException("Parameter 'age' must not be null or empty");
}
return userService.addUser(user);
}
@RequestMapping(value="/{id}", method = RequestMethod.GET)
public User getUser(@PathVariable("id") Long id) {
return userService.getUserById(id);
}
@RequestMapping(value="/{id}", method = RequestMethod.PUT, consumes = "application/json")
public User updateUser(@PathVariable("id") String id, @RequestBody User user) {
if(user.getName() == null && user.getAge() == null) {
throw new IllegalArgumentException("Parameter 'name' and 'age' must not both be null");
}
return userService.addUser(user);
}
@RequestMapping(value="/{id}", method = RequestMethod.DELETE)
public RestResultResponse deleteUser(@PathVariable("id") Long id) {
try {
userService.deleteUser(id);
return new RestResultResponse(true);
} catch(Exception e) {
return new RestResultResponse(false, e.getMessage());
}
}
}
- UserController的構(gòu)造方法注入了userService电湘,后者提供了用戶管理的基本方法
- 所有方法的默認(rèn)的Http返回狀態(tài)是200,addUser方法通過添加@ResponseStatus(HttpStatus.CREATED)注解鹅经,將返回狀態(tài)設(shè)置為201寂呛。方法中拋出的異常的默認(rèn)Http返回狀態(tài)為500,而IllegalArgumentException的狀態(tài)由于在GlobalExceptionHandler中做了定義瘾晃,設(shè)置為了400 bad request.
- 除
deleteUser()
外贷痪,其余方法的返回結(jié)果皆為User對(duì)象,在Http結(jié)果中Spring Boot會(huì)自動(dòng)轉(zhuǎn)換為Json格式酗捌。而deleteUser()
的返回結(jié)果RestResultResponse
呢诬,是自定義的操作結(jié)果的狀態(tài)
利用CrudRepository訪問數(shù)據(jù)庫
import java.util.Optional;
import org.springframework.data.repository.CrudRepository;
import com.leonlu.code.sample.webapp.ws.domain.User;
public interface UserRepository extends CrudRepository<User, Long> {
Optional<User> findByName(String name);
}
- CrudRepository提供了
save()
,findAll()
,findOne()
等通用的JPA方法,這里自定義了findByName方法胖缤,相當(dāng)于執(zhí)行"select a from User a where a.username = :username"
查詢 - 這里僅需要定義UserRepository的接口尚镰,Spring Boot會(huì)自動(dòng)定義其實(shí)現(xiàn)類
UserService封裝用戶管理基本功能
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.leonlu.code.sample.webapp.ws.domain.User;
import com.leonlu.code.sample.webapp.ws.exception.UserNotFoundException;
import com.leonlu.code.sample.webapp.ws.repository.UserRepository;
@Service
public class UserService {
private UserRepository userRepository;
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public Collection<User> getAllUsers() {
Iterable<User> userIter = userRepository.findAll();
ArrayList<User> userList = new ArrayList<User>();
userIter.forEach(item -> {
userList.add(item);
});
return userList;
}
public User getUserById(Long id) {
User user = userRepository.findOne(id);
if(user == null) {
throw new UserNotFoundException(id);
}
return user;
}
public User getUserByName(String name) {
return userRepository.findByName(name)
.orElseThrow(() -> new UserNotFoundException(name));
}
public User addUser(User user) {
return userRepository.save(user);
}
public User updateUser(User user) {
return userRepository.save(user);
}
public void deleteUser(Long id) {
userRepository.delete(id);
}
}
- 在
getUserById()
和getUserByName()
中狗唉,對(duì)于不存在的用戶分俯,會(huì)拋出UserNotFoundException異常缸剪。這是一個(gè)自定義異常,其返回狀態(tài)為HttpStatus.NOT_FOUND唬渗,即404:
示例效果如下:import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ResponseStatus; @ResponseStatus(HttpStatus.NOT_FOUND) public class UserNotFoundException extends RuntimeException{ public UserNotFoundException(Long userId) { super("could not find user '" + userId + "'."); } public UserNotFoundException(String userName) { super("could not find user '" + userName + "'."); } }
$ curl localhost:8080/user/12 -i HTTP/1.1 404 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 20 Aug 2016 14:00:41 GMT {"timestamp":1471788041171,"status":404,"error":"Not Found","exception":"com.leonlu.code.sample.webapp.ws.exception.UserNotFoundException","message":"could not find user '12'.","path":"/user/12"}
利用ControllerAdvice完成異常處理
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = IllegalArgumentException.class)
public void handleException(Exception e, HttpServletResponse response) throws IOException{
response.sendError(HttpStatus.BAD_REQUEST.value());
}
}
- 要修改Spring Boot的默認(rèn)異常返回結(jié)果,除了通過對(duì)自定義對(duì)異常添加
@ResponseStatus
注解之外(如上文中的UserNotFoundException)嫉鲸,開發(fā)者可通過@ExceptionHandler
注解對(duì)某些異常的返回狀態(tài)和返回結(jié)果進(jìn)行自定義玄渗。 -
@ControllerAdvice
的作用是對(duì)全局的Controller進(jìn)行統(tǒng)一的設(shè)置
用Maven打包并運(yùn)行
- 打包
mvn clean package
- 運(yùn)行
java -jar JAR_NAME
- 用curl訪問localhost:8080/user驗(yàn)證結(jié)果
$ curl -i localhost:8080/user HTTP/1.1 200 Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 20 Aug 2016 14:32:06 GMT [{"id":1,"name":"john","age":29},{"id":2,"name":"alex","age":29},{"id":3,"name":"mike","age":27},{"id":4,"name":"mary","age":21},{"id":5,"name":"jenny","age":27}]
總結(jié)
基于Spring Boot可快速構(gòu)建Java微服務(wù)辈灼,而且官方提供了與Docker也榄,Redis甜紫,JMS等多種組件集成的功能囚霸,有豐富的文檔可供參考激才,值得大家嘗試瘸恼。
參考
- Building REST services with Spring
- Accessing Data with JPA
- Spring Boot Reference Guide
- SpringBoot : How to do Exception Handling in Rest Application
- Post JSON to spring REST webservice