溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫

發(fā)布時間:2023-05-10 10:32:52 來源:億速云 閱讀:91 作者:iii 欄目:編程語言

這篇文章主要介紹“如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”的相關(guān)知識,小編通過實(shí)際案例向大家展示操作過程,操作方法簡單快捷,實(shí)用性強(qiáng),希望這篇“如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”文章能幫助大家解決問題。

栗子

現(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);
}

上面這串代碼也可以實(shí)現(xiàn)查詢效果,看起來也不是很復(fù)雜,但是這串代碼是不可復(fù)用的,只能用在這個場景。假設(shè)在我們的系統(tǒng)中還有很多類似上面商品查詢的需求,那么我們需要到處寫這樣的if(...)else{...}。作為一個程序員,不能把類似的或者重復(fù)的代碼統(tǒng)一起來是一件很難受的事情,所以需要對這種場景的代碼進(jìn)行優(yōu)化。

上面這串代碼的問題在于:入?yún)⒉还潭ā⒎祷刂狄膊还潭?,如果僅僅是參數(shù)不固定,使用泛型即可。但最關(guān)鍵的是查詢方法也是不固定的,比如查詢商品和查詢用戶肯定不是一個查詢方法吧。

所以如果我們可以把一個方法(即上面的各種查詢方法)也能當(dāng)做一個參數(shù)傳入一個統(tǒng)一的判斷方法就好了,類似于:

/**
 * 這個方法的作用是:先執(zhí)行method1方法,如果method1查詢或執(zhí)行不成功,再執(zhí)行method2方法
 */
public static<T> T selectCacheByTemplate(method1,method2)

想要實(shí)現(xiàn)上面的這種效果,就不得不提到Java8的新特性:函數(shù)式編程

原理介紹

在Java中有一個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ù)式編程梳理

代碼實(shí)現(xiàn)

那么接下來就來使用Java優(yōu)雅的實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫吧!

項(xiàng)目代碼
配置文件

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>
項(xiàng)目結(jié)構(gòu)

如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫

其中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 (核心類)

因?yàn)槲也魂P(guān)心參數(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實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫

第二次從緩存中查詢

如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫

關(guān)于“如何使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點(diǎn)。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI