通過Spring Boot + Mybatis + Redis快速搭建現(xiàn)代化Web項(xiàng)目
背景
SpringBoot因其提供了各種開箱即用的插件,使得它成為了當(dāng)今最為主流的Java Web開發(fā)框架之一。Mybatis是一個十分輕量好用的ORM框架。Redis是當(dāng)今十分主流的分布式key-value型數(shù)據(jù)庫,在web開發(fā)中,我們常用它來緩存數(shù)據(jù)庫的查詢結(jié)果。
本篇博客將介紹如何使用SpringBoot快速搭建一個Web應(yīng)用,并且采用Mybatis作為我們的ORM框架。為了提升性能,我們將Redis作為Mybatis的二級緩存。為了測試我們的代碼,我們編寫了單元測試,并且用H2內(nèi)存數(shù)據(jù)庫來生成我們的測試數(shù)據(jù)。通過該項(xiàng)目,我們希望讀者可以快速掌握現(xiàn)代化Java Web開發(fā)的技巧以及最佳實(shí)踐。
本文的示例代碼可在Github中下載:https://github.com/Lovelcp/spring-boot-mybatis-with-redis/tree/master
環(huán)境
開發(fā)環(huán)境: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
新建項(xiàng)目
首先,我們需要初始化我們的Spring-Boot工程。通過Intellij的Spring Initializer,新建一個Spring-Boot工程變得十分簡單。首先我們在Intellij中選擇New一個Project:

然后在選擇依賴的界面,勾選Web、Mybatis、Redis、Mysql、H2:

新建工程成功之后,我們可以看到項(xiàng)目的初始結(jié)構(gòu)如下圖所示:

Spring Initializer已經(jīng)幫我們自動生成了一個啟動類——SpringBootMybatisWithRedisApplication。該類的代碼十分簡單:
@SpringBootApplication
public class SpringBootMybatisWithRedisApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootMybatisWithRedisApplication.class, args);
}
}
@SpringBootApplication注解表示啟用Spring Boot的自動配置特性。好了,至此我們的項(xiàng)目骨架已經(jīng)搭建成功,感興趣的讀者可以通過Intellij啟動看看效果。
新建API接口
接下來,我們要編寫Web API。假設(shè)我們的Web工程負(fù)責(zé)處理商家的產(chǎn)品(Product)。我們需要提供根據(jù)product id返回product信息的get接口和更新product信息的put接口。首先我們定義Product類,該類包括產(chǎn)品id,產(chǎn)品名稱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內(nèi)部使用Spring MVC作為它的Web組件,所以我們可以通過注解的方式快速開發(fā)我們的接口類:
@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;
}
}
我們簡單介紹一下上述代碼中所用到的注解的作用:
@RestController:表示該類為Controller,并且提供Rest接口,即所有接口的值以Json格式返回。該注解其實(shí)是@Controller和@ResponseBody的組合注解,便于我們開發(fā)Rest API。
@RequestMapping、@GetMapping、@PutMapping:表示接口的URL地址。標(biāo)注在類上的@RequestMapping注解表示該類下的所有接口的URL都以/product開頭。@GetMapping表示這是一個Get HTTP接口,@PutMapping表示這是一個Put HTTP接口。
@PathVariable、@RequestBody:表示參數(shù)的映射關(guān)系。假設(shè)有個Get請求訪問的是/product/123,那么該請求會由getProductInfo方法處理,其中URL里的123會被映射到productId中。同理,如果是Put請求的話,請求的body會被映射到newProduct對象中。
這里我們只定義了接口,實(shí)際的處理邏輯還未完成,因?yàn)閜roduct的信息都存在數(shù)據(jù)庫中。接下來我們將在項(xiàng)目中集成mybatis,并且與數(shù)據(jù)庫做交互。
集成Mybatis
配置數(shù)據(jù)源
首先我們需要在配置文件中配置我們的數(shù)據(jù)源。我們采用mysql作為我們的數(shù)據(jù)庫。這里我們采用yaml作為我們配置文件的格式。我們在resources目錄下新建application.yml文件:
spring:
# 數(shù)據(jù)庫配置
datasource:
url: jdbc:mysql://{your_host}/{your_db}
username: {your_username}
password: {your_password}
driver-class-name: org.gjt.mm.mysql.Driver
由于Spring Boot擁有自動配置的特性,我們不用新建一個DataSource的配置類,Sping Boot會自動加載配置文件并且根據(jù)配置文件的信息建立數(shù)據(jù)庫的連接池,十分便捷。
筆者推薦大家采用yaml作為配置文件的格式。xml顯得冗長,properties沒有層級結(jié)構(gòu),yaml剛好彌補(bǔ)了這兩者的缺點(diǎn)。這也是Spring Boot默認(rèn)就支持yaml格式的原因。
配置Mybatis
我們已經(jīng)通過Spring Initializer在pom.xml中引入了mybatis-spring-boot-starte庫,該庫會自動幫我們初始化mybatis。首先我們在application.yml中填寫mybatis的相關(guān)配置:
# mybatis配置 mybatis: # 配置映射類所在包名 type-aliases-package: com.wooyoo.learning.dao.domain # 配置mapper xml文件所在路徑,這里是一個數(shù)組 mapper-locations: - mappers/ProductMapper.xml
然后,再在代碼中定義ProductMapper類:
@Mapper
public interface ProductMapper {
Product select(
@Param("id")
long id);
void update(Product product);
}
這里,只要我們加上了@Mapper注解,Spring Boot在初始化mybatis時會自動加載該mapper類。
Spring Boot之所以這么流行,最大的原因是它自動配置的特性。開發(fā)者只需要關(guān)注組件的配置(比如數(shù)據(jù)庫的連接信息),而無需關(guān)心如何初始化各個組件,這使得我們可以集中精力專注于業(yè)務(wù)的實(shí)現(xiàn),簡化開發(fā)流程。
訪問數(shù)據(jù)庫
完成了Mybatis的配置之后,我們就可以在我們的接口中訪問數(shù)據(jù)庫了。我們在ProductController下通過@Autowired引入mapper類,并且調(diào)用對應(yīng)的方法實(shí)現(xiàn)對product的查詢和更新操作,這里我們以查詢接口為例:
@RestController
@RequestMapping("/product")
public class ProductController {
@Autowired
private ProductMapper productMapper;
@GetMapping("/{id}")
public Product getProductInfo(
@PathVariable("id")
Long productId) {
return productMapper.select(productId);
}
// 避免篇幅過長,省略updateProductInfo的代碼
}
然后在你的mysql中插入幾條product的信息,就可以運(yùn)行該項(xiàng)目看看是否能夠查詢成功了。
至此,我們已經(jīng)成功地在項(xiàng)目中集成了Mybatis,增添了與數(shù)據(jù)庫交互的能力。但是這還不夠,一個現(xiàn)代化的Web項(xiàng)目,肯定會上緩存加速我們的數(shù)據(jù)庫查詢。接下來,將介紹如何科學(xué)地將Redis集成到Mybatis的二級緩存中,實(shí)現(xiàn)數(shù)據(jù)庫查詢的自動緩存。
集成Redis
配置Redis
同訪問數(shù)據(jù)庫一樣,我們需要配置Redis的連接信息。在application.yml文件中增加如下配置:
spring: redis: # redis數(shù)據(jù)庫索引(默認(rèn)為0),我們使用索引為3的數(shù)據(jù)庫,避免和其他數(shù)據(jù)庫沖突 database: 3 # redis服務(wù)器地址(默認(rèn)為localhost) host: localhost # redis端口(默認(rèn)為6379) port: 6379 # redis訪問密碼(默認(rèn)為空) password: # redis連接超時時間(單位為毫秒) timeout: 0 # redis連接池配置 pool: # 最大可用連接數(shù)(默認(rèn)為8,負(fù)數(shù)表示無限) max-active: 8 # 最大空閑連接數(shù)(默認(rèn)為8,負(fù)數(shù)表示無限) max-idle: 8 # 最小空閑連接數(shù)(默認(rèn)為0,該值只有為正數(shù)才有作用) min-idle: 0 # 從連接池中獲取連接最大等待時間(默認(rèn)為-1,單位為毫秒,負(fù)數(shù)表示無限) max-wait: -1
上述列出的都為常用配置,讀者可以通過注釋信息了解每個配置項(xiàng)的具體作用。由于我們在pom.xml中已經(jīng)引入了spring-boot-starter-data-redis庫,所以Spring Boot會幫我們自動加載Redis的連接,具體的配置類
org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration。通過該配置類,我們可以發(fā)現(xiàn)底層默認(rèn)使用Jedis庫,并且提供了開箱即用的redisTemplate和stringTemplate。
將Redis作為二級緩存
Mybatis的二級緩存原理本文不再贅述,讀者只要知道,Mybatis的二級緩存可以自動地對數(shù)據(jù)庫的查詢做緩存,并且可以在更新數(shù)據(jù)時同時自動地更新緩存。
實(shí)現(xiàn)Mybatis的二級緩存很簡單,只需要新建一個類實(shí)現(xiàn)org.apache.ibatis.cache.Cache接口即可。
該接口共有以下五個方法:
String getId():mybatis緩存操作對象的標(biāo)識符。一個mapper對應(yīng)一個mybatis的緩存操作對象。
void putObject(Object key, Object value):將查詢結(jié)果塞入緩存。
Object getObject(Object key):從緩存中獲取被緩存的查詢結(jié)果。
Object removeObject(Object key):從緩存中刪除對應(yīng)的key、value。只有在回滾時觸發(fā)。一般我們也可以不用實(shí)現(xiàn),具體使用方式請參考:org.apache.ibatis.cache.decorators.TransactionalCache。
void clear():發(fā)生更新時,清除緩存。
int getSize():可選實(shí)現(xiàn)。返回緩存的數(shù)量。
ReadWriteLock getReadWriteLock():可選實(shí)現(xiàn)。用于實(shí)現(xiàn)原子性的緩存操作。
接下來,我們新建RedisCache類,實(shí)現(xiàn)Cache接口:
public class RedisCache implements Cache {
private static final Logger logger = LoggerFactory.getLogger(RedisCache.class);
private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
private final String id; // cache instance id
private RedisTemplate redisTemplate;
private static final long EXPIRE_TIME_IN_MINUTES = 30; // redis過期時間
public RedisCache(String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
}
@Override
public String getId() {
return id;
}
/**
* Put query result to redis
*
* @param key
* @param value
*/
@Override
@SuppressWarnings("unchecked")
public void putObject(Object key, Object value) {
RedisTemplate redisTemplate = getRedisTemplate();
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, value, EXPIRE_TIME_IN_MINUTES, TimeUnit.MINUTES);
logger.debug("Put query result to redis");
}
/**
* Get cached query result from redis
*
* @param key
* @return
*/
@Override
public Object getObject(Object key) {
RedisTemplate redisTemplate = getRedisTemplate();
ValueOperations opsForValue = redisTemplate.opsForValue();
logger.debug("Get cached query result from redis");
return opsForValue.get(key);
}
/**
* Remove cached query result from redis
*
* @param key
* @return
*/
@Override
@SuppressWarnings("unchecked")
public Object removeObject(Object key) {
RedisTemplate redisTemplate = getRedisTemplate();
redisTemplate.delete(key);
logger.debug("Remove cached query result from redis");
return null;
}
/**
* Clears this cache instance
*/
@Override
public void clear() {
RedisTemplate redisTemplate = getRedisTemplate();
redisTemplate.execute((RedisCallback) connection -> {
connection.flushDb();
return null;
});
logger.debug("Clear all the cached query result from redis");
}
@Override
public int getSize() {
return 0;
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
private RedisTemplate getRedisTemplate() {
if (redisTemplate == null) {
redisTemplate = ApplicationContextHolder.getBean("redisTemplate");
}
return redisTemplate;
}
}
講解一下上述代碼中一些關(guān)鍵點(diǎn):
自己實(shí)現(xiàn)的二級緩存,必須要有一個帶id的構(gòu)造函數(shù),否則會報錯。
我們使用Spring封裝的redisTemplate來操作Redis。網(wǎng)上所有介紹redis做二級緩存的文章都是直接用jedis庫,但是筆者認(rèn)為這樣不夠Spring Style,而且,redisTemplate封裝了底層的實(shí)現(xiàn),未來如果我們不用jedis了,我們可以直接更換底層的庫,而不用修改上層的代碼。更方便的是,使用redisTemplate,我們不用關(guān)心redis連接的釋放問題,否則新手很容易忘記釋放連接而導(dǎo)致應(yīng)用卡死。
需要注意的是,這里不能通過autowire的方式引用redisTemplate,因?yàn)镽edisCache并不是Spring容器里的bean。所以我們需要手動地去調(diào)用容器的getBean方法來拿到這個bean,具體的實(shí)現(xiàn)方式請參考Github中的代碼。
我們采用的redis序列化方式是默認(rèn)的jdk序列化。所以數(shù)據(jù)庫的查詢對象(比如Product類)需要實(shí)現(xiàn)Serializable接口。
這樣,我們就實(shí)現(xiàn)了一個優(yōu)雅的、科學(xué)的并且具有Spring Style的Redis緩存類。
開啟二級緩存
接下來,我們需要在ProductMapper.xml中開啟二級緩存:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wooyoo.learning.dao.mapper.ProductMapper">
<!-- 開啟基于redis的二級緩存 -->
<cache type="com.wooyoo.learning.util.RedisCache"/>
<select id="select" resultType="Product">
SELECT * FROM products WHERE id = #{id} LIMIT 1
</select>
<update id="update" parameterType="Product" flushCache="true">
UPDATE products SET name = #{name}, price = #{price} WHERE id = #{id} LIMIT 1
</update>
</mapper>
<cache type="com.wooyoo.learning.util.RedisCache"/>表示開啟基于redis的二級緩存,并且在update語句中,我們設(shè)置flushCache為true,這樣在更新product信息時,能夠自動失效緩存(本質(zhì)上調(diào)用的是clear方法)。
測試
配置H2內(nèi)存數(shù)據(jù)庫
至此我們已經(jīng)完成了所有代碼的開發(fā),接下來我們需要書寫單元測試代碼來測試我們代碼的質(zhì)量。我們剛才開發(fā)的過程中采用的是mysql數(shù)據(jù)庫,而一般我們在測試時經(jīng)常采用的是內(nèi)存數(shù)據(jù)庫。這里我們使用H2作為我們測試場景中使用的數(shù)據(jù)庫。
要使用H2也很簡單,只需要跟使用mysql時配置一下即可。在application.yml文件中:
--- spring: profiles: test # 數(shù)據(jù)庫配置 datasource: url: jdbc:h2:mem:test username: root password: 123456 driver-class-name: org.h2.Driver schema: classpath:schema.sql data: classpath:data.sql
為了避免和默認(rèn)的配置沖突,我們用---另起一段,并且用profiles: test表明這是test環(huán)境下的配置。然后只要在我們的測試類中加上@ActiveProfiles(profiles = "test")注解來啟用test環(huán)境下的配置,這樣就能一鍵從mysql數(shù)據(jù)庫切換到h2數(shù)據(jù)庫。
在上述配置中,schema.sql用于存放我們的建表語句,data.sql用于存放insert的數(shù)據(jù)。這樣當(dāng)我們測試時,h2就會讀取這兩個文件,初始化我們所需要的表結(jié)構(gòu)以及數(shù)據(jù),然后在測試結(jié)束時銷毀,不會對我們的mysql數(shù)據(jù)庫產(chǎn)生任何影響。這就是內(nèi)存數(shù)據(jù)庫的好處。另外,別忘了在pom.xml中將h2的依賴的scope設(shè)置為test。
使用Spring Boot就是這么簡單,無需修改任何代碼,輕松完成數(shù)據(jù)庫在不同環(huán)境下的切換。
編寫測試代碼
因?yàn)槲覀兪峭ㄟ^Spring Initializer初始化的項(xiàng)目,所以已經(jīng)有了一個測試類——SpringBootMybatisWithRedisApplicationTests。
Spring Boot提供了一些方便我們進(jìn)行Web接口測試的工具類,比如TestRestTemplate。然后在配置文件中我們將log等級調(diào)成DEBUG,方便觀察調(diào)試日志。具體的測試代碼如下:
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@ActiveProfiles(profiles = "test")
public class SpringBootMybatisWithRedisApplicationTests {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void test() {
long productId = 1;
Product product = restTemplate.getForObject("http://localhost:" + port + "/product/" + productId, Product.class);
assertThat(product.getPrice()).isEqualTo(200);
Product newProduct = new Product();
long newPrice = new Random().nextLong();
newProduct.setName("new name");
newProduct.setPrice(newPrice);
restTemplate.put("http://localhost:" + port + "/product/" + productId, newProduct);
Product testProduct = restTemplate.getForObject("http://localhost:" + port + "/product/" + productId, Product.class);
assertThat(testProduct.getPrice()).isEqualTo(newPrice);
}
}
在上述測試代碼中:
我們首先調(diào)用get接口,通過assert語句判斷是否得到了預(yù)期的對象。此時該product對象會存入redis中。
然后我們調(diào)用put接口更新該product對象,此時redis緩存會失效。
最后我們再次調(diào)用get接口,判斷是否獲取到了新的product對象。如果獲取到老的對象,說明緩存失效的代碼執(zhí)行失敗,代碼存在錯誤,反之則說明我們代碼是OK的。
書寫單元測試是一個良好的編程習(xí)慣。雖然會占用你一定的時間,但是當(dāng)你日后需要做一些重構(gòu)工作時,你就會感激過去寫過單元測試的自己。
查看測試結(jié)果
我們在Intellij中點(diǎn)擊執(zhí)行測試用例,測試結(jié)果如下:

顯示的是綠色,說明測試用例執(zhí)行成功了。
總結(jié)
本篇文章介紹了如何通過Spring Boot、Mybatis以及Redis快速搭建一個現(xiàn)代化的Web項(xiàng)目,并且同時介紹了如何在Spring Boot下優(yōu)雅地書寫單元測試來保證我們的代碼質(zhì)量。當(dāng)然這個項(xiàng)目還存在一個問題,那就是mybatis的二級緩存只能通過flush整個DB來實(shí)現(xiàn)緩存失效,這個時候可能會把一些不需要失效的緩存也給失效了,所以具有一定的局限性。
相關(guān)文章
Spring解決循環(huán)依賴問題的三種方法小結(jié)
在 Spring 中,循環(huán)依賴問題指的是兩個或多個 bean 之間相互依賴形成的閉環(huán),具體而言,當(dāng) bean A 依賴于 bean B,同時 bean B 也依賴于 bean A,就形成了循環(huán)依賴,本文就給大家介紹了Spring解決循環(huán)依賴問題的三種方法,需要的朋友可以參考下2023-09-09
commons fileupload實(shí)現(xiàn)文件上傳的實(shí)例代碼
這篇文章主要介紹了commons fileupload實(shí)現(xiàn)文件上傳的實(shí)例代碼,包括文件上傳的原理分析等相關(guān)知識點(diǎn),本文給大家介紹的非常詳細(xì),具有參考借鑒價值,感興趣的朋友一起看看吧2016-10-10
Java棧的應(yīng)用之括號匹配算法實(shí)例分析
這篇文章主要介紹了Java棧的應(yīng)用之括號匹配算法,結(jié)合實(shí)例形式分析了Java使用棧實(shí)現(xiàn)括號匹配算法的相關(guān)原理、操作技巧與注意事項(xiàng),需要的朋友可以參考下2020-03-03
SpringBoot實(shí)現(xiàn)短鏈接系統(tǒng)的使用示例
由于短鏈接可能涉及到用戶隱私和安全問題,所以短鏈接系統(tǒng)也需要符合相關(guān)的數(shù)據(jù)保護(hù)和安全標(biāo)準(zhǔn),本文主要介紹了SpringBoot實(shí)現(xiàn)短鏈接系統(tǒng)的使用示例,感興趣的可以了解一下2023-09-09

