Spring Boot + Mybatis + Redis二级缓存开发指南
Spring-Boot因其提供了各种开箱即用的插件,使得它成为了当今最为主流的Java Web开发框架之一。Mybatis是一个十分轻量好用的ORM框架。Redis是当今十分主流的分布式key-value型数据库,在web开发中,我们常用它来缓存数据库的查询结果。
本篇博客将介绍如何使用Spring-Boot快速搭建一个Web应用,并且采用Mybatis作为我们的ORM框架。为了提升性能,我们将Redis作为Mybatis的二级缓存。为了测试我们的代码,我们编写了单元测试,并且用H2内存数据库来生成我们的测试数据。通过该项目,我们希望读者可以快速掌握现代化Java Web开发的技巧以及最佳实践。
环境
- 开发环境:mac 10.11
- ide:Intellij 2017.1
- jdk:1.8
- Spring-Boot:1.5.3.RELEASE
- Redis:3.2.9
- Mysql:5.7
Spring-Boot
新建项目
首先,我们需要初始化我们的Spring-Boot工程。通过Intellij的Spring Initializer,新建一个Spring-Boot工程变得十分简单。首先我们在Intellij中选择New一个Project:
然后在选择依赖的界面,勾选Web、Mybatis、Redis、Mysql、H2:
新建工程成功之后,我们可以看到项目的初始结构如下图所示:
Spring Initializer已经帮我们自动生成了一个启动类——SpringBootMybatisWithRedisApplication。该类的代码十分简单:
@SpringBootApplication public class SpringBootMybatisWithRedisApplication { public static void main(String[] args) { SpringApplication.run(SpringBootMybatisWithRedisApplication.class, args); } }
@SpringBootApplication注解表示启用Spring Boot的自动配置特性。好了,至此我们的项目骨架已经搭建成功,感兴趣的读者可以通过Intellij启动看看效果。
新建API接口
接下来,我们要编写Web API。假设我们的Web工程负责处理商家的产品(Product)。我们需要提供根据product id返回product信息的get接口和更新product信息的put接口。首先我们定义Product类,该类包括产品id,产品名称name以及价格price:
public class Product implements Serializable { private static final long serialVersionUID = 1435515995276255188L; private long id; private String name; private long price; // getters setters }
然后我们需要定义Controller类。由于Spring Boot内部使用Spring MVC作为它的Web组件,所以我们可以通过注解的方式快速开发我们的接口类:
@RestController @RequestMapping("/product") public class ProductController { @GetMapping("/{id}") public Product getProductInfo( @PathVariable("id") Long productId) { // TODO return null; } @PutMapping("/{id}") public Product updateProductInfo( @PathVariable("id") Long productId, @RequestBody Product newProduct) { // TODO return null; } }