Java微服务初体验之Sping Boot


微服务架构

微服务架构近年来受到很多人的推崇,什么是微服务架构?先参考一段定义:

微服务架构(Microservices Architecture)是一种架构风格(Architectural Style)和设计模式,提倡将应用分割成一系列细小的服务,每个服务专注于单一业务功能,运行于独立的进程中,服务之间边界清晰,采用轻量级通信机制(如HTTP/REST)相互沟通、配合来实现完整的应用,满足业务和用户的需求。
引用 - 基于容器云的微服务架构实践

简而言之就是服务轻量级化和模块化,可独立部署。其带来的好处包括:解耦合程度更高,屏蔽底层复杂度;技术选型灵活,可方便其他模块调用;易于部署和扩展等。与NodeJs等其他语言相比,Java相对来说实现微服务较为复杂一些,开发一个Web应用需要经历编码-编译打包-部署到Web容器-启动运行四步,但是开源框架Spring Boot的出现,让Java微服务的实现变得很简单,由于内嵌了Web服务器,无需“部署到Web容器”,三步即可实现一个Web微服务。而且由于Spring Boot可以和Spring社区的其他框架进行集成,对于熟悉Spring的开发者来说很容易上手。下面本文会描述一个简易用户管理微服务的实例,初步体验Spring Boot微服务开发。

开发环境

  • 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的默认配置,然后依次引入

  • spring-boot-starter-web 用来构建REST微服务
  • spring-boot-starter-data-jpa 利用JPA用来访问数据库
  • h2 Spring Boot集成的内存数据库
  • spring-boot-starter-test 用来构建单元测试,内含JUnit

程序结构

|____sample
| |____webapp
| | |____ws
| | | |____App.java 启动程序
| | | |____controller
| | | | |____UserController.java 用户管理的RESTful API
| | | |____domain
| | | | |____User.java 用户信息
| | | |____exception
| | | | |____GlobalExceptionHandler.java 异常处理
| | | | |____UserNotFoundException.java 用户不存在的异常
| | | |____repository
| | | | |____UserRepository.java 访问用户数据库的接口
| | | |____rest
| | | | |____RestResultResponse.java Rest请求的状态结果
| | | |____service
| | | | |____UserService.java 用户管理的服务

用SpringApplication实现启动程序

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相当于@Configuration,@EnableAutoConfiguration,@ComponentScan三个注解。用于自动完成Spring的配置和Bean的构建。
  • main方法中的SpringApplication.run将启动内嵌的Tomcat服务器,默认端口为8080
  • CommandLineRunner用于在启动后调用UserService,创建5个新用户

利用RestController构建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的构造方法注入了userService,后者提供了用户管理的基本方法
  • 所有方法的默认的Http返回状态是200,addUser方法通过添加@ResponseStatus(HttpStatus.CREATED)注解,将返回状态设置为201。方法中抛出的异常的默认Http返回状态为500,而IllegalArgumentException的状态由于在GlobalExceptionHandler中做了定义,设置为了400 bad request.
  • deleteUser()外,其余方法的返回结果皆为User对象,在Http结果中Spring Boot会自动转换为Json格式。而deleteUser()的返回结果RestResultResponse,是自定义的操作结果的状态

利用CrudRepository访问数据库

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方法,相当于执行"select a from User a where a.username = :username"查询
  • 这里仅需要定义UserRepository的接口,Spring Boot会自动定义其实现类

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()中,对于不存在的用户,会抛出UserNotFoundException异常。这是一个自定义异常,其返回状态为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的默认异常返回结果,除了通过对自定义对异常添加@ResponseStatus注解之外(如上文中的UserNotFoundException),开发者可通过@ExceptionHandler注解对某些异常的返回状态和返回结果进行自定义。
  • @ControllerAdvice的作用是对全局的Controller进行统一的设置

用Maven打包并运行

  • 打包 mvn clean package
  • 运行 java -jar JAR_NAME
  • 用curl访问localhost:8080/user验证结果
    $ 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}]

总结

基于Spring Boot可快速构建Java微服务,而且官方提供了与Docker,Redis,JMS等多种组件集成的功能,有丰富的文档可供参考,值得大家尝试。

参考

  1. Building REST services with Spring
  2. Accessing Data with JPA
  3. Spring Boot Reference Guide
  4. SpringBoot : How to do Exception Handling in Rest Application
  5. Post JSON to spring REST webservice

扩展阅读

  1. 互联网架构为什么要做服务化?
  2. 微服务架构多“微”才合适?