Java微服務(wù)初體驗(yàn)之Sping Boot

微服務(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等多種組件集成的功能囚霸,有豐富的文檔可供參考激才,值得大家嘗試瘸恼。

參考

  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

擴(kuò)展閱讀

  1. 互聯(lián)網(wǎng)架構(gòu)為什么要做服務(wù)化压固?
  2. 微服務(wù)架構(gòu)多“微”才合適靠闭?

<small>閱讀原文</small>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市谣光,隨后出現(xiàn)的幾起案子抢肛,更是在濱河造成了極大的恐慌捡絮,老刑警劉巖福稳,帶你破解...
    沈念sama閱讀 218,858評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件的圆,死亡現(xiàn)場(chǎng)離奇詭異越妈,居然都是意外死亡梅掠,警方通過查閱死者的電腦和手機(jī)店归,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,372評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門且叁,熙熙樓的掌柜王于貴愁眉苦臉地迎上來秩伞,“玉大人,你說我怎么就攤上這事展氓〈ィ” “怎么了?”我有些...
    開封第一講書人閱讀 165,282評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵,是天一觀的道長(zhǎng)酪耕。 經(jīng)常有香客問我轨淌,道長(zhǎng)递鹉,這世上最難降的妖魔是什么躏结? 我笑而不...
    開封第一講書人閱讀 58,842評(píng)論 1 295
  • 正文 為了忘掉前任媳拴,我火速辦了婚禮屈溉,結(jié)果婚禮上子巾,老公的妹妹穿的比我還像新娘砰左。我一直安慰自己缠导,他們只是感情好僻造,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,857評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著镀娶,像睡著了一般。 火紅的嫁衣襯著肌膚如雪宝泵。 梳的紋絲不亂的頭發(fā)上儿奶,一...
    開封第一講書人閱讀 51,679評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音椰弊,去河邊找鬼瓤鼻。 笑死茬祷,一個(gè)胖子當(dāng)著我的面吹牛清焕,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播牲迫,決...
    沈念sama閱讀 40,406評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼耐朴,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了盹憎?” 一聲冷哼從身側(cè)響起筛峭,我...
    開封第一講書人閱讀 39,311評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎陪每,沒想到半個(gè)月后影晓,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,767評(píng)論 1 315
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡檩禾,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,945評(píng)論 3 336
  • 正文 我和宋清朗相戀三年饵婆,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了灌灾。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片些己。...
    茶點(diǎn)故事閱讀 40,090評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡功偿,死狀恐怖虑灰,靈堂內(nèi)的尸體忽然破棺而出对湃,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,785評(píng)論 5 346
  • 正文 年R本政府宣布汁讼,位于F島的核電站,受9級(jí)特大地震影響筐高,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜扮宠,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,420評(píng)論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,988評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春饵沧,著一層夾襖步出監(jiān)牢的瞬間捷泞,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,101評(píng)論 1 271
  • 我被黑心中介騙來泰國(guó)打工拂到, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留码泞,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,298評(píng)論 3 372
  • 正文 我出身青樓绪撵,卻偏偏與公主長(zhǎng)得像细溅,于是被迫代替她去往敵國(guó)和親承疲。 傳聞我的和親對(duì)象是個(gè)殘疾皇子鸥拧,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,033評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • Spring Cloud為開發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見模式的工具(例如配置管理砰蠢,服務(wù)發(fā)現(xiàn),斷路器唉铜,智...
    卡卡羅2017閱讀 134,659評(píng)論 18 139
  • Spring Boot 參考指南 介紹 轉(zhuǎn)載自:https://www.gitbook.com/book/qbgb...
    毛宇鵬閱讀 46,822評(píng)論 6 342
  • 構(gòu)建用戶管理微服務(wù)翻譯自:https://springuni.com 構(gòu)建用戶管理微服務(wù)(一):定義領(lǐng)域模型和 R...
    極樂君閱讀 1,526評(píng)論 0 10
  • 《Spring Boot開發(fā):從0到1》 大綱結(jié)構(gòu)v2.0 第一部分Spring Boot基礎(chǔ) 第1章 Sprin...
    光劍書架上的書閱讀 10,956評(píng)論 1 70
  • 感賞韻謙的課程啟發(fā)我?guī)准舻遁p松獲得幾條漂亮流行的褲子台舱;感賞女兒的自控力,刷QQ到點(diǎn)自動(dòng)放下手機(jī)潭流;感賞老公中午做得好...
    悄然h閱讀 142評(píng)論 0 0