使用Java實現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫
前言
在訪問量大的時候,為了提高查詢效率,我們會將數(shù)據(jù)先緩存到redis中。先查詢redis,查詢不到再去查詢數(shù)據(jù)庫,實現(xiàn)這個邏輯也不復雜,寫一個if(...)else{...}也就行了。這種做法也不是不行,就是看起來有點兒粗糙,所以我想換一種更優(yōu)雅的寫法。
栗子
現(xiàn)有一個使用商品名稱查詢商品的需求,要求先查詢緩存,查不到則去數(shù)據(jù)庫查詢;從數(shù)據(jù)庫查詢到之后加入緩存,再查詢時繼續(xù)先查詢緩存。
思路分析
可以寫一個條件判斷,偽代碼如下:
//先從緩存中查詢
String goodsInfoStr = redis.get(goodsName);
if(StringUtils.isBlank(goodsInfoStr)){
//如果緩存中查詢?yōu)榭?,則去數(shù)據(jù)庫中查詢
Goods goods = goodsMapper.queryByName(goodsName);
//將查詢到的數(shù)據(jù)存入緩存
goodsName.set(goodsName,JSONObject.toJSONString(goods));
//返回商品數(shù)據(jù)
return goods;
}else{
//將查詢到的str轉(zhuǎn)換為對象并返回
return JSON.parseObject(goodsInfoStr, Goods.class);
}上面這串代碼也可以實現(xiàn)查詢效果,看起來也不是很復雜,但是這串代碼是不可復用的,只能用在這個場景。假設在我們的系統(tǒng)中還有很多類似上面商品查詢的需求,那么我們需要到處寫這樣的if(...)else{...}。作為一個程序員,不能把類似的或者重復的代碼統(tǒng)一起來是一件很難受的事情,所以需要對這種場景的代碼進行優(yōu)化。
上面這串代碼的問題在于:入?yún)⒉还潭?、返回值也不固定,如果僅僅是參數(shù)不固定,使用泛型即可。但最關鍵的是查詢方法也是不固定的,比如查詢商品和查詢用戶肯定不是一個查詢方法吧。
所以如果我們可以把一個方法(即上面的各種查詢方法)也能當做一個參數(shù)傳入一個統(tǒng)一的判斷方法就好了,類似于:
/** * 這個方法的作用是:先執(zhí)行method1方法,如果method1查詢或執(zhí)行不成功,再執(zhí)行method2方法 */ public static<T> T selectCacheByTemplate(method1,method2)
想要實現(xiàn)上面的這種效果,就不得不提到Java8的新特性:函數(shù)式編程
原理介紹
在Java中有一個package:java.util.function ,里面全部是接口,并且都被@FunctionalInterface注解所修飾。
Function分類
- Consumer(消費):接受參數(shù),無返回值
- Function(函數(shù)):接受參數(shù),有返回值
- Operator(操作):接受參數(shù),返回與參數(shù)同類型的值
- Predicate(斷言):接受參數(shù),返回boolean類型
- Supplier(供應):無參數(shù),有返回值
具體我就不在贅述了,可以參考:Java 函數(shù)式編程梳理
代碼實現(xiàn)
那么接下來就來使用Java優(yōu)雅的實現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫吧!
項目代碼
配置文件
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>SpringBoot-query</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringBoot-query</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.83</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>項目結(jié)構

其中CacheService是從緩存中查詢數(shù)據(jù),GoodsService是從數(shù)據(jù)庫中查詢數(shù)據(jù)
SpringBootQueryApplication.java
package com.example.springbootquery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringBootQueryApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootQueryApplication.class, args);
}
}Goods.java
package com.example.springbootquery.entity;
public class Goods {
private String goodsName;
private Integer goodsTotal;
private Double price;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public Integer getGoodsTotal() {
return goodsTotal;
}
public void setGoodsTotal(Integer goodsTotal) {
this.goodsTotal = goodsTotal;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"goodsName='" + goodsName + '\'' +
", goodsTotal='" + goodsTotal + '\'' +
", price=" + price +
'}';
}
}CacheSelector.java
自定義函數(shù)式接口:
package com.example.springbootquery.function;
@FunctionalInterface
public interface CacheSelector<T> {
T select() throws Exception;
}CacheService.java
package com.example.springbootquery.service;
import com.example.springbootquery.entity.Goods;
public interface CacheService {
/**
* 從緩存中獲取商品
*
* @param goodsName 商品名稱
* @return goods
*/
Goods getGoodsByName(String goodsName) throws Exception;
}CacheServiceImpl.java
package com.example.springbootquery.service.impl;
import com.alibaba.fastjson.JSON;
import com.example.springbootquery.entity.Goods;
import com.example.springbootquery.service.CacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service("cacheService")
public class CacheServiceImpl implements CacheService {
@Autowired
private StringRedisTemplate redisTemplate;
@Override
public Goods getGoodsByName(String goodsName) throws Exception {
String s = redisTemplate.opsForValue().get(goodsName);
return null == s ? null : JSON.parseObject(s, Goods.class);
}
}GoodsService.java
package com.example.springbootquery.service;
import com.example.springbootquery.entity.Goods;
public interface GoodsService {
Goods getGoodsByName(String goodsName);
}GoodsServiceImpl.java
這里我就不連接數(shù)據(jù)庫了,模擬一個返回
package com.example.springbootquery.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootquery.entity.Goods;
import com.example.springbootquery.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Override
public Goods getGoodsByName(String goodsName) {
Goods goods = new Goods();
goods.setGoodsName("商品名1");
goods.setGoodsTotal(20);
goods.setPrice(30.0D);
stringRedisTemplate.opsForValue().set(goodsName, JSONObject.toJSONString(goods));
return goods;
}
}BaseUtil.java (核心類)
因為我不關心參數(shù),只需要一個返回值就行了,所以這里使用的是Supplier。
package com.example.springbootquery.util;
import com.example.springbootquery.function.CacheSelector;
import java.util.function.Supplier;
public class BaseUtil {
/**
* 緩存查詢模板
*
* @param cacheSelector 查詢緩存的方法
* @param databaseSelector 數(shù)據(jù)庫查詢方法
* @return T
*/
public static <T> T selectCacheByTemplate(CacheSelector<T> cacheSelector, Supplier<T> databaseSelector) {
try {
System.out.println("query data from redis ······");
// 先查 Redis緩存
T t = cacheSelector.select();
if (t == null) {
// 沒有記錄再查詢數(shù)據(jù)庫
System.err.println("redis 中沒有查詢到");
System.out.println("query data from database ······");
return databaseSelector.get();
} else {
return t;
}
} catch (Exception e) {
// 緩存查詢出錯,則去數(shù)據(jù)庫查詢
e.printStackTrace();
System.err.println("redis 查詢出錯");
System.out.println("query data from database ······");
return databaseSelector.get();
}
}
}用法
package com.example.springbootquery;
import com.example.springbootquery.entity.Goods;
import com.example.springbootquery.service.CacheService;
import com.example.springbootquery.service.GoodsService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import static com.example.springbootquery.util.BaseUtil.selectCacheByTemplate;
@SpringBootTest
class SpringBootQueryApplicationTests {
@Autowired
private CacheService cacheService;
@Autowired
private GoodsService userService;
@Test
void contextLoads() throws Exception {
Goods user = selectCacheByTemplate(
() -> cacheService.getGoodsByName("商品名1"),
() -> userService.getGoodsByName("商品名1")
);
System.out.println(user);
}
}第一次從數(shù)據(jù)中查詢

第二次從緩存中查詢

到此這篇關于使用Java實現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫的文章就介紹到這了,更多相關ava查詢內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring mvc Json處理實現(xiàn)流程代碼實例
這篇文章主要介紹了Spring mvc Json處理實現(xiàn)流程代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-09-09
SpringBoot實現(xiàn)短信驗證碼校驗方法思路詳解
最近做項目遇到這樣的需求,前端是基于BootStrap,html代碼中有BootStrap樣式實現(xiàn)的,具體后臺實現(xiàn)代碼大家通過本文一起學習吧2017-08-08
JAVA統(tǒng)計字符串中某個字符出現(xiàn)次數(shù)的方法實現(xiàn)
本文主要介紹了JAVA統(tǒng)計字符串中某個字符出現(xiàn)次數(shù)的方法實現(xiàn),可以循環(huán)使用String的charAt(int index)函數(shù),具有一定的參考價值,感興趣的可以了解一下2023-11-11
SpringBoot Security整合JWT授權RestAPI的實現(xiàn)
這篇文章主要介紹了SpringBoot Security整合JWT授權RestAPI的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-11-11

