使用Java实现先查询缓存再查询数据库
作者:??summo??? 发布时间:2024-01-14 02:18:05
前言
在访问量大的时候,为了提高查询效率,我们会将数据先缓存到redis中。先查询redis,查询不到再去查询数据库,实现这个逻辑也不复杂,写一个if(...)else{...}
也就行了。这种做法也不是不行,就是看起来有点儿粗糙,所以我想换一种更优雅的写法。
栗子
现有一个使用商品名称查询商品的需求,要求先查询缓存,查不到则去数据库查询;从数据库查询到之后加入缓存,再查询时继续先查询缓存。
思路分析
可以写一个条件判断,伪代码如下:
//先从缓存中查询
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>
项目结构
其中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='" + goodsName + '\'' +
", goodsTotal='" + goodsTotal + '\'' +
", price=" + price +
'}';
}
}
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);
}
}
第一次从数据中查询
第二次从缓存中查询
来源:https://juejin.cn/post/7124885941117779998


猜你喜欢
- 前段时间,接到一个需求,要求下载某一个网站的视频,然后自己从网上查阅了相关的资料,在这里做一个总结。1. m3u8文件m3u8是苹果公司推出
- 首先总结的意义就是让杂乱无章变得更加井然有序,这样在使用的过程思路会更加清晰。数组使用方法注意点:变异方法和非变异方法。即变异方法使用会改变
- 在Python中的break语句终止当前循环,继续执行下一个语句,就像C语言中的break一样。break最常见的用途是当一些外
- 如何用net/http构建一个简单的web服务Golang提供了简洁的方法来构建web服务package main import ( &nb
- 一 前言 问题的存在 从代码级别上,也就是应用层次上考虑代码安全的话(也就是不考虑底层的语言本身等问题的漏洞),脚本安全问题就是函数和变量的
- Oracle查询结果集,随机排序select * from table1 order by dbms_random.value();MySQ
- 目录1. pgzeropgzero的安装2. 游戏设计的过程3. pgzero基础4. pgzero游戏例子5. 总结6. 参考资料1. p
- Python是一种非常富有表现力的语言。它为我们提供了一个庞大的标准库和许多内置模块,帮助我们快速完成工作。然而,许多人可能会迷失在它提供的
- Python中sorted()用法sorted() 作为 Python 内置函数之一,其功能是对序列(列表、元组、字典、
- 1、需要模块以及测试工具模块名:pyserial使用命令下载:python -m pip install pyserial串口调试工具:ss
- 用了腾讯QQ也有将近十年了,今天心血来潮想模仿腾讯QQ的登陆面板做一个web版的登陆面板,然后参考了一些代码,自己模仿,学写了一个。&nbs
- pyenv简单介绍在日常运维中, 经常遇到这样的情况: 系统自带的Python是2.x,而业务部署需要Python 3.x 环境, 此时需要
- 在本文中,我想向您介绍如何在Django中使用聚合,聚合的含义是“内容相关项的集合,以便它们可以显示或链接到”。在Django中,我们使用的
- 引言在Scrapy中,在很多种情况下,需要一层层地进行爬取网页数据,就是基于url爬取网页,然后在从网页中提取url,继续爬取,循环往复。本
- 前言tkinter:GUI桌面应用开发模块,写软件界面你还可以打包成exe软件, 哪怕你没有python环境, 一样可以用虽然不一定要有界面
- python读取pdf文档一、 准备工作安装对应的库pip install pdfminer3kpip install pdfminer.s
- parse_dates : boolean or list of ints or names or list of lists or dic
- 说到Web Framework,Ruby的世界Rails一统江湖,而Python则是一个百花齐放的世界,各种micro-framework、
- 本文实例讲述了php+jQuery实现的 * 导航栏下拉菜单显示效果。分享给大家供大家参考,具体如下:首先看看效果图:1.数据配置文件 db.
- 昨晚看了用svg如何制作富有动态的tooltip,于是今天就心血来潮学着做一下,于是也成功做出来,也明白其中的原理,收获颇多阿!接下来要多去