您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“怎么使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實(shí)用性強(qiáng)。下面就讓小編來帶大家學(xué)習(xí)“怎么使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”吧!
現(xiàn)有一個(gè)使用商品名稱查詢商品的需求,要求先查詢緩存,查不到則去數(shù)據(jù)庫查詢;從數(shù)據(jù)庫查詢到之后加入緩存,再查詢時(shí)繼續(xù)先查詢緩存。
可以寫一個(gè)條件判斷,偽代碼如下:
//先從緩存中查詢 String goodsInfoStr = redis.get(goodsName); if(StringUtils.isBlank(goodsInfoStr)){ //如果緩存中查詢?yōu)榭眨瑒t去數(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); }
上面這串代碼也可以實(shí)現(xiàn)查詢效果,看起來也不是很復(fù)雜,但是這串代碼是不可復(fù)用的
,只能用在這個(gè)場景。假設(shè)在我們的系統(tǒng)中還有很多類似上面商品查詢的需求,那么我們需要到處寫這樣的if(...)else{...}
。作為一個(gè)程序員,不能把類似的或者重復(fù)的代碼統(tǒng)一起來是一件很難受的事情,所以需要對這種場景的代碼進(jìn)行優(yōu)化。
上面這串代碼的問題在于:入?yún)⒉还潭?、返回值也不固定,如果僅僅是參數(shù)不固定,使用泛型即可。但最關(guān)鍵的是查詢方法也是不固定的,比如查詢商品和查詢用戶肯定不是一個(gè)查詢方法吧。
所以如果我們可以把一個(gè)方法(即上面的各種查詢方法)也能當(dāng)做一個(gè)參數(shù)傳入一個(gè)統(tǒng)一的判斷方法就好了,類似于:
/** * 這個(gè)方法的作用是:先執(zhí)行method1方法,如果method1查詢或執(zhí)行不成功,再執(zhí)行method2方法 */ public static<T> T selectCacheByTemplate(method1,method2)
想要實(shí)現(xiàn)上面的這種效果,就不得不提到Java8的新特性:函數(shù)式編程
在Java中有一個(gè)package:java.util.function
,里面全部是接口,并且都被@FunctionalInterface
注解所修飾。
Function分類
Consumer(消費(fèi)):接受參數(shù),無返回值
Function(函數(shù)):接受參數(shù),有返回值
Operator(操作):接受參數(shù),返回與參數(shù)同類型的值
Predicate(斷言):接受參數(shù),返回boolean類型
Supplier(供應(yīng)):無參數(shù),有返回值
具體我就不在贅述了,可以參考:Java 函數(shù)式編程梳理
那么接下來就來使用Java優(yōu)雅的實(shí)現(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>
其中CacheService是從緩存中查詢數(shù)據(jù),GoodsService是從數(shù)據(jù)庫中查詢數(shù)據(jù)
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); } }
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 + '}'; } }
自定義函數(shù)式接口:
package com.example.springbootquery.function; @FunctionalInterface public interface CacheSelector<T> { T select() throws Exception; }
package com.example.springbootquery.service; import com.example.springbootquery.entity.Goods; public interface CacheService { /** * 從緩存中獲取商品 * * @param goodsName 商品名稱 * @return goods */ Goods getGoodsByName(String goodsName) throws Exception; }
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); } }
package com.example.springbootquery.service; import com.example.springbootquery.entity.Goods; public interface GoodsService { Goods getGoodsByName(String goodsName); }
這里我就不連接數(shù)據(jù)庫了,模擬一個(gè)返回
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; } }
因?yàn)槲也魂P(guān)心參數(shù),只需要一個(gè)返回值就行了,所以這里使用的是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) { // 緩存查詢出錯(cuò),則去數(shù)據(jù)庫查詢 e.printStackTrace(); System.err.println("redis 查詢出錯(cuò)"); 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); } }
到此,相信大家對“怎么使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”有了更深的了解,不妨來實(shí)際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進(jìn)入相關(guān)頻道進(jìn)行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。