最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

 更新時(shí)間:2022年07月28日 10:02:48   作者:??summo???  
這篇文章主要介紹了使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫(kù),文章圍繞主題展開(kāi)詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下

前言

在訪問(wèn)量大的時(shí)候,為了提高查詢效率,我們會(huì)將數(shù)據(jù)先緩存到redis中。先查詢r(jià)edis,查詢不到再去查詢數(shù)據(jù)庫(kù),實(shí)現(xiàn)這個(gè)邏輯也不復(fù)雜,寫(xiě)一個(gè)if(...)else{...}也就行了。這種做法也不是不行,就是看起來(lái)有點(diǎn)兒粗糙,所以我想換一種更優(yōu)雅的寫(xiě)法。

栗子

現(xiàn)有一個(gè)使用商品名稱查詢商品的需求,要求先查詢緩存,查不到則去數(shù)據(jù)庫(kù)查詢;從數(shù)據(jù)庫(kù)查詢到之后加入緩存,再查詢時(shí)繼續(xù)先查詢緩存。

思路分析

可以寫(xiě)一個(gè)條件判斷,偽代碼如下:

//先從緩存中查詢
String goodsInfoStr = redis.get(goodsName);
if(StringUtils.isBlank(goodsInfoStr)){
	//如果緩存中查詢?yōu)榭?,則去數(shù)據(jù)庫(kù)中查詢
	Goods goods = goodsMapper.queryByName(goodsName);
	//將查詢到的數(shù)據(jù)存入緩存
	goodsName.set(goodsName,JSONObject.toJSONString(goods));
	//返回商品數(shù)據(jù)
	return goods;
}else{
	//將查詢到的str轉(zhuǎn)換為對(duì)象并返回
	return JSON.parseObject(goodsInfoStr, Goods.class);
}

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

上面這串代碼的問(wèn)題在于:入?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ù),無(wú)返回值
  • Function(函數(shù)):接受參數(shù),有返回值
  • Operator(操作):接受參數(shù),返回與參數(shù)同類型的值
  • Predicate(斷言):接受參數(shù),返回boolean類型
  • Supplier(供應(yīng)):無(wú)參數(shù),有返回值

具體我就不在贅述了,可以參考:Java 函數(shù)式編程梳理

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

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

項(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)

在這里插入圖片描述

 其中CacheService是從緩存中查詢數(shù)據(jù),GoodsService是從數(shù)據(jù)庫(kù)中查詢數(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ù)庫(kù)了,模擬一個(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;
    }
}

BaseUtil.java (核心類)

因?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ù)庫(kù)查詢方法
     * @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) {
                // 沒(méi)有記錄再查詢數(shù)據(jù)庫(kù)
                System.err.println("redis 中沒(méi)有查詢到");
                System.out.println("query data from database ······");
                return databaseSelector.get();
            } else {
                return t;
            }
        } catch (Exception e) {
            // 緩存查詢出錯(cuò),則去數(shù)據(jù)庫(kù)查詢
            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);
    }
}

第一次從數(shù)據(jù)中查詢

在這里插入圖片描述

第二次從緩存中查詢

在這里插入圖片描述

到此這篇關(guān)于使用Java實(shí)現(xiàn)先查詢緩存再查詢數(shù)據(jù)庫(kù)的文章就介紹到這了,更多相關(guān)ava查詢內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • RabbitMQ基礎(chǔ)概念之信道channel詳解

    RabbitMQ基礎(chǔ)概念之信道channel詳解

    這篇文章主要介紹了RabbitMQ基礎(chǔ)概念之信道channel詳解,信道是生產(chǎn)消費(fèi)者與rabbit通信的渠道,生產(chǎn)者publish或者消費(fèi)者消費(fèi)一個(gè)隊(duì)列都是需要通過(guò)信道來(lái)通信的,需要的朋友可以參考下
    2023-08-08
  • java懶惰評(píng)估實(shí)現(xiàn)方法

    java懶惰評(píng)估實(shí)現(xiàn)方法

    這篇文章主要介紹了java懶惰評(píng)估如何實(shí)現(xiàn)的相關(guān)內(nèi)容及實(shí)例,有興趣的朋友們可以學(xué)習(xí)參考下。
    2021-05-05
  • String?concat(String?str)使用小結(jié)

    String?concat(String?str)使用小結(jié)

    這篇文章主要介紹了String?concat(String?str)使用小結(jié),在了解concat()之前,首先需要明確的是String的兩點(diǎn)特殊性,一是長(zhǎng)度不可變二是值不可變,本文給大家詳細(xì)講解,需要的朋友可以參考下
    2022-11-11
  • SpringBoot根據(jù)參數(shù)動(dòng)態(tài)調(diào)用接口實(shí)現(xiàn)類方法

    SpringBoot根據(jù)參數(shù)動(dòng)態(tài)調(diào)用接口實(shí)現(xiàn)類方法

    在?Spring?Boot?開(kāi)發(fā)中,我們經(jīng)常會(huì)遇到根據(jù)不同參數(shù)調(diào)用接口不同實(shí)現(xiàn)類方法的需求,本文將詳細(xì)介紹如何實(shí)現(xiàn)這一功能,有需要的小伙伴可以參考下
    2025-02-02
  • Mybatis配置之properties和settings標(biāo)簽的用法

    Mybatis配置之properties和settings標(biāo)簽的用法

    這篇文章主要介紹了Mybatis配置之properties和settings標(biāo)簽的用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-07-07
  • Spring將一個(gè)的類配置成Bean的方式詳解

    Spring將一個(gè)的類配置成Bean的方式詳解

    這篇文章主要介紹了Spring將一個(gè)的類配置成Bean的方式,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)吧
    2023-03-03
  • SpringBoot配置類編寫(xiě)過(guò)程圖解

    SpringBoot配置類編寫(xiě)過(guò)程圖解

    這篇文章主要介紹了SpringBoot配置類編寫(xiě)過(guò)程圖解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-11-11
  • java遍歷HashMap簡(jiǎn)單的方法

    java遍歷HashMap簡(jiǎn)單的方法

    這篇文章主要介紹了java遍歷HashMap簡(jiǎn)單的方法,以實(shí)例形式簡(jiǎn)單分析了采用java遍歷HashMap的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-02-02
  • java 反射機(jī)制

    java 反射機(jī)制

    本文主要介紹了java反射機(jī)制的相關(guān)知識(shí),具有一定的參考價(jià)值,下面跟著小編一起來(lái)看下吧
    2017-02-02
  • Java利用策略模式實(shí)現(xiàn)條件判斷,告別if else

    Java利用策略模式實(shí)現(xiàn)條件判斷,告別if else

    策略模式定義了一系列算法,并且將每個(gè)算法封裝起來(lái),使得他們可以相互替換,而且算法的變化不會(huì)影響使用算法的客戶端。本文將通過(guò)案例講解如何利用Java的策略模式實(shí)現(xiàn)條件判斷,告別if----else條件硬編碼,需要的可以參考一下
    2022-02-02

最新評(píng)論

临沧市| 涿州市| 临高县| 镇江市| 旬邑县| 桃江县| 皮山县| 庆元县| 贡山| 新蔡县| 根河市| 溧阳市| 犍为县| 鄂尔多斯市| 五指山市| 蒙山县| 晴隆县| 兴和县| 临安市| 淮北市| 灌云县| 蒙山县| 新龙县| 芜湖市| 习水县| 苏尼特左旗| 秦皇岛市| 开江县| 长寿区| 建平县| 犍为县| 基隆市| 兖州市| 张家港市| 木兰县| 玉环县| 桂东县| 昌邑市| 三河市| 宁津县| 丽水市|