springbootconfigSpringBoot之路Spring Boot

Java微服务初体验之Sping Boot

2017-01-17  本文已影响5059人  LeonLu

微服务架构

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

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

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

开发环境

添加依赖

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

程序结构

|____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);
    }
}

利用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());
        }
    }
}

利用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);
}

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);
    }
}

利用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());
    }  
}

用Maven打包并运行

总结

基于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. 微服务架构多“微”才合适?

<small>阅读原文</small>

上一篇下一篇

猜你喜欢

热点阅读