首頁  >  文章  >  Java  >  怎麼使用Java實作先查詢快取再查詢資料庫

怎麼使用Java實作先查詢快取再查詢資料庫

WBOY
WBOY轉載
2023-04-29 09:55:061241瀏覽

栗子

現有一個使用商品名稱查詢商品的需求,要求先查詢緩存,查不到則去資料庫查詢;從資料庫查詢到之後加入緩存,再查詢時繼續先查詢快取。

思路分析

可以寫一個條件判斷,偽代碼如下:

//先从缓存中查询
String goodsInfoStr = redis.get(goodsName);
if(StringUtils.isBlank(goodsInfoStr)){
	//如果缓存中查询为空,则去数据库中查询
	Goods goods = goodsMapper.queryByName(goodsName);
	//将查询到的数据存入缓存
	goodsName.set(goodsName,JSONObject.toJSONString(goods));
	//返回商品数据
	return goods;
}else{
	//将查询到的str转换为对象并返回
	return JSON.parseObject(goodsInfoStr, Goods.class);
}

上面這串程式碼也可以實現查詢效果,看起來也不是很複雜,但這串程式碼是不可重複使用的,只能用在這個場景。假設在我們的系統中還有很多類似上面商品查詢的需求,那麼我們需要到處寫這樣的if(...)else{...}。身為一個程式設計師,不能把類似的或重複的程式碼統一起來是一件很難受的事情,所以需要對這種場景的程式碼進行最佳化。

上面這串程式碼的問題在於:入參不固定、回傳值也不固定,如果只是參數不固定,使用泛型即可。但最關鍵的是查詢方法也是不固定的,例如查詢商品和查詢用戶肯定不是一個查詢方法吧。

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

/**
 * 这个方法的作用是:先执行method1方法,如果method1查询或执行不成功,再执行method2方法
 */
public static<T> T selectCacheByTemplate(method1,method2)

想要實現上面的這個效果,就不得不提到Java8的新功能:函數式程式設計

#原理介紹

在Java中有一個package: java.util.function ,裡面全部都是接口,而且都被@FunctionalInterface註解所修飾。

Function分類

  • #Consumer(消費):接受參數,無回傳值

  • ##Function(函數):接受參數,有傳回值

  • #Operator(運算):

    接受參數,傳回與參數同類型的值

  • Predicate(斷言):接受參數,傳回boolean型別

  • ##Supplier (供應):

    無參數,有回傳值

  • 具體我就不在贅述了,可以參考:Java 函數式程式設計梳理

程式碼實作

那麼接下來就來使用Java優雅的實作先查詢快取再查詢資料庫吧!

專案程式碼

設定檔

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>
專案結構

怎麼使用Java實作先查詢快取再查詢資料庫 其中CacheService是從快取中查詢數據,GoodsService是從資料庫查詢資料

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=&#39;" + goodsName + &#39;\&#39;&#39; +
                ", goodsTotal=&#39;" + goodsTotal + &#39;\&#39;&#39; +
                ", price=" + price +
                &#39;}&#39;;
    }
}
CacheSelector.java
自訂函數式介面:

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
這裡我就不連接資料庫了,模擬一個回傳

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 (核心類別)
因為我不關心參數,只需要一個回傳值就行了,所以這裡使用的是Supplier。

package com.example.springbootquery.util;
import com.example.springbootquery.function.CacheSelector;
import java.util.function.Supplier;
public class BaseUtil {
    /**
     * 缓存查询模板
     *
     * @param cacheSelector    查询缓存的方法
     * @param databaseSelector 数据库查询方法
     * @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) {
                // 没有记录再查询数据库
                System.err.println("redis 中没有查询到");
                System.out.println("query data from database ······");
                return databaseSelector.get();
            } else {
                return t;
            }
        } catch (Exception e) {
            // 缓存查询出错,则去数据库查询
            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);
    }
}

第一次從資料中查詢

怎麼使用Java實作先查詢快取再查詢資料庫#第二次從快取中查詢

#

以上是怎麼使用Java實作先查詢快取再查詢資料庫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:yisu.com。如有侵權,請聯絡admin@php.cn刪除