>>分享流行的Java框架以及开源软件,对孙卫琴的《精通Spring:Java Web开发技术详解》提供技术支持 书籍支持  卫琴直播  品书摘要  在线测试  资源下载  联系我们
发表一个新主题 开启一个新投票 回复文章 您是本文章第 23862 个阅读者 刷新本主题
 * 贴子主题:  Java微服务初体验之Sping Boot 回复文章 点赞(0)  收藏  
作者:javathinker    发表时间:2018-07-14 09:06:17     消息  查看  搜索  好友  复制  引用

微服务架构

微服务架构近年来受到很多人的推崇,什么是微服务架构?先参考一段定义:
微服务架构(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

添加依赖
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等多种组件集成的功能,有丰富的文档可供参考,值得大家尝试。




程序猿的技术大观园:www.javathinker.net
  Java面向对象编程-->Java常用类(下)
  JavaWeb开发-->自定义JSP标签(Ⅰ)
  JSP与Hibernate开发-->Java应用分层架构及软件模型
  Java网络编程-->通过JavaMail API收发邮件
  精通Spring-->绑定表单
  Vue3开发-->组合(Composition)API
  Maven 安装及环境配置
  MessagePack反序列化使用示例
  Netty的粘包和拆包问题分析
  从零开始手写 spring ioc 框架,深入学习 spring 源码
  Spring事务容易掉入的坑
  Spring MVC处理静态资源文件的方式
  Spring Boot、SpringMVC进行i18n国际化支持:使用MessageSou...
  POJO与JavaBean与SpringBean的概念与区别
  探讨通过Feign配合Hystrix进行调用时异常的处理
  Nginx技术探秘
  开发一个Java项目的基本流程
  一睹Web服务真面目,有商业价值的Web服务是这样的
  spring源码阅读环境(几分钟下载包)
  Spring MVC:切面的应用
  spring整合WebService入门详解
  更多...
 IPIP: 已设置保密
树形列表:   
[url=http://www.zhent.com]... nihaota 2022-10-28 21:39:34
1页 1条记录 当前第1
发表一个新主题 开启一个新投票 回复文章


中文版权所有: JavaThinker技术网站 Copyright 2016-2026 沪ICP备16029593号-2
荟萃Java程序员智慧的结晶,分享交流Java前沿技术。  联系我们
如有技术文章涉及侵权,请与本站管理员联系。