多级缓存设计和实战应用 多级缓存的设计与应用(3)
多级缓存设计和实战应用

第一次访问,打印出SQL,说明查询了数据库:
21:28:49:535 DEBUG 3332 --- [nio-8081-exec-1] c.asdc.item.mapper.ItemMapper.selectOne : ==> Preparing: SELECT id,name,title,price,image,category,brand,spec,status,create_time,update_time FROM tb_item WHERE (status <> ? AND id = ?)
21:28:49:536 DEBUG 3332 --- [nio-8081-exec-1] c.asdc.item.mapper.ItemMapper.selectOne : ==> Parameters: 2(Integer), 10002(Long)
21:28:49:544 DEBUG 3332 --- [nio-8081-exec-1] c.asdc.item.mapper.ItemMapper.selectOne : <== Total: 1
第二次访问,未打印出SQL,说明直接查询的本地缓存。
因此,利用Caffeine实现缓存功能生效。
Redis缓存
redis 到底有多快?
根据官方数据,Redis 的 QPS 可以达到约 100000(每秒请求数),感兴趣的可参考:
官方Redis benchmark
以下摘自官网:
With high-end configurations, the number of client connections is also an important factor. Being based on epoll/kqueue, the Redis event loop is quite scalable. Redis has already been benchmarked at more than 60000 connections, and was still able to sustain 50000 q/s in these conditions. As a rule of thumb, an instance with 30000 connections can only process half the throughput achievable with 100 connections. Here is an example showing the throughput of a Redis instance per number of connections:
客户端连接数压测报告:

X轴:客户端连接数,Y轴:QPS
生产实践中如何使用redis做缓存?
基本流程:

程序实现:
1、导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2、配置连接
spring:
redis:
host: your_ip
database: 1
username: your_username
password: your_password
3、代码编写:
@Autowired
private StringRedisTemplate redisTemplate;
//JSON 转化
private static final ObjectMapper MAPPER = new ObjectMapper();
@GetMapping("/redis/{id}")
public String queryRedisItemData(@PathVariable("id") Long id) throws JsonProcessingException {
// 查询Redis缓存
String cachedResult = redisTemplate.opsForValue().get("item:id:" + id);
if (Strings.isNotBlank(cachedResult)) {
System.out.println("从Redis缓存中获取数据:" + cachedResult);
return cachedResult;
} else {
// 1.查询数据库
Item item = itemService.query().ne("status", 2).eq("id", id).one();
//转化成json
String dbResult = MAPPER.writeValueAsString(item);
System.out.println("从数据库中获取数据:" + dbResult);
// 将查询结果存入缓存
redisTemplate.opsForValue().set("item:id:" + id, dbResult);
return dbResult;
}
}
4、演示效果:
4.1. 测试前:redis中没有对应key:item:id:10002
相关阅读
-
服务器优化的重要性 服务器优化方法
如果想了解服务器优化的重要性的IT小经验,一定能解决您的问题的,一起来了解吧! 服务器优化是指通过对服务器硬件、软件和网络进行调整和优化,以提高服务器的性能和稳定性,从而提
-
怎么创建网络平台账号 创建网站免费注册
关于这个怎么创建网络平台账号和创建网站免费注册方面的知识,具体详情如下: 在当下,传统的线下营销渠道已经无法满足消费者的多样化需求,所以很多企业商家都会选择搭建一个网站平
-
创建一个网站要多少钱 自己做一个网站需要的费用
对于大多数网友来说创建一个网站要多少钱和自己做一个网站需要的费用的方法内容,继续往下看吧! 想搞一个网站,我们先了解一下搞个网站需要多少钱?网站建设费用主要包括:网站搭建
-
OSI七层网络模型传输层详解 传输层使用的协议有哪些
今日重点为您介绍OSI七层网络模型传输层详解的IT知识,接下来小编为网友介绍。 传输层是OSI七层网络模型中的第四层,主要负责为应用层提供端到端的数据传输服务,同时也可以对网络层提


