缓存是⼀个高速数据交换的存储器,使用它可以快速的访问和操作数据。
举个通俗的例子。
小明经营着一家饭店,在刚开张的时候由于名气不足,客源少,生意并不是很忙,平时没事的时候就闲着,有客人来了再进厨房安排做菜。随着饭店的日益发展,此时的饭店已经不同往日,有着大量的稳定客源,并且在某些节假日的时候甚至爆满。按照以前的做法,那肯定是行不通了,在用餐高峰期的时候因为备餐慢导致了客户的长时间等待,使得饭店的屡遭投诉。
为解决这一问题,小明想到了一个办法,可以在空闲的时候,提前将热门的菜做完后放入保温柜,等用餐高峰期时再拿出来加热后就可以直接上菜,就规避了短时间内大量客源而导致的备餐慢的问题,通过这一方法,即使在高峰期,也能很好的应对。
这就是缓存的本质,将热点资源(高频读、低频写)提前放入离用户最近、访问速度更快的地方,以提高访问速度。
使用缓存后,效率会大大的提升,减少了不必要的资源消耗,提升了用户体验。
redis的特点:
redis的优势:
(1)完全基于内存,数据存在内存中,绝大部分请求是纯粹的内存操作,非常快速,跟传统的磁盘文件数据存储相比,避免了通过磁盘IO读取到内存这部分的开销。
(2)数据结构简单,对数据操作也简单。Redis中的数据结构是专门进行设计的,每种数据结构都有一种或多种数据结构来支持。Redis正是依赖这些灵活的数据结构,来提升读取和写入的性能。
(3)采用单线程,省去了很多上下文切换的时间以及CPU消耗,不存在竞争条件,不用去考虑各种锁的问题,不存在加锁释放锁操作,也不会出现死锁而导致的性能消耗。
(4)使用基于IO多路复用机制的线程模型,可以处理并发的链接。
数据库表结构:
CREATE TABLE `blade_user` (`id` bigint(20) NOT NULL COMMENT '主键',`tenant_id` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT '000000' COMMENT '租户ID',`code` varchar(12) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '用户编号',`user_type` int(11) DEFAULT NULL COMMENT '用户平台',`account` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '账号',`password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '密码',`name` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '昵称',`real_name` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '真名',`avatar` varchar(500) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '头像',`email` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '邮箱',`phone` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '手机',`birthday` datetime DEFAULT NULL COMMENT '生日',`sex` int(11) DEFAULT NULL COMMENT '性别',`role_id` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '角色id',`dept_id` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '部门id',`post_id` varchar(1000) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '岗位id',`create_user` bigint(20) DEFAULT NULL COMMENT '创建人',`create_dept` bigint(20) DEFAULT NULL COMMENT '创建部门',`create_time` datetime DEFAULT NULL COMMENT '创建时间',`update_user` bigint(20) DEFAULT NULL COMMENT '修改人',`update_time` datetime DEFAULT NULL COMMENT '修改时间',`status` int(11) DEFAULT NULL COMMENT '状态',`is_deleted` int(11) DEFAULT '0' COMMENT '是否已删除',PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci ROW_FORMAT=DYNAMIC COMMENT='用户表';
完整pom.xml文件:
4.0.0 org.springframework.boot spring-boot-starter-parent 2.7.8 com.redis.demo springboot-redis 0.0.1-SNAPSHOT springboot-redis Demo project for Spring Boot 1.8 org.springframework.boot spring-boot-starter-web org.projectlombok lombok true org.springframework.boot spring-boot-starter-test test com.baomidou mybatis-plus-boot-starter 3.4.2 org.springframework.boot spring-boot-starter-data-redis mysql mysql-connector-java 8.0.15 cn.hutool hutool-all 5.8.5 com.alibaba fastjson 1.2.41 org.springframework.boot spring-boot-starter-cache org.springframework.boot spring-boot-maven-plugin org.projectlombok lombok
application.yml文件:
server:port: 8081spring:datasource:driver-class-name: com.mysql.cj.jdbc.Driverurl: jdbc:mysql://3.129.36.183:3306/test?serverTimezone=GMT%2B8&useUnicode=true&characterEncoding=UTF-8username: rootpassword: root#redisredis:host: 3.129.36.183#Redis服务器连接端口port: 6379#Redis服务器连接密码password: 123456mybatis-plus:configuration:log-impl: org.apache.ibatis.logging.stdout.StdOutImpl #开启sql日志# 将带有下划线的表字段映射为驼峰格式的实体类属性map-underscore-to-camel-case: true#配置类型别名所对应的包type-aliases-package: com.redis.demo.entity#配置SQL输出语句com.winsun.dataclean.mappermapper-locations: com/redis/demo/dao/*.xml
RedisUtils:
package com.redis.demo.utils;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;/*** Redis工具类** @author*/
@Component
public class RedisUtils {@Autowiredprivate RedisTemplate redisTemplate;// =============================common============================/*** 指定缓存失效时间** @param key 键* @param time 时间(秒)* @return*/public boolean expire(String key, long time) {try {if (time > 0) {redisTemplate.expire(key, time, TimeUnit.SECONDS);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 根据key 获取过期时间** @param key 键 不能为null* @return 时间(秒) 返回0代表为永久有效*/public long getExpire(String key) {return redisTemplate.getExpire(key, TimeUnit.SECONDS);}/*** 判断key是否存在** @param key 键* @return true 存在 false不存在*/public boolean hasKey(String key) {try {return redisTemplate.hasKey(key);} catch (Exception e) {e.printStackTrace();return false;}}/*** 删除缓存** @param key 可以传一个值 或多个*/@SuppressWarnings("unchecked")public void del(String... key) {if (key != null && key.length > 0) {if (key.length == 1) {redisTemplate.delete(key[0]);} else {redisTemplate.delete(CollectionUtils.arrayToList(key));}}}// ============================String=============================/*** 普通缓存获取** @param key 键* @return 值*/public Object get(String key) {return key == null ? null : redisTemplate.opsForValue().get(key);}/*** 普通缓存放入** @param key 键* @param value 值* @return true成功 false失败*/public boolean set(String key, Object value) {try {redisTemplate.opsForValue().set(key, value);return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 普通缓存放入并设置时间** @param key 键* @param value 值* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期* @return true成功 false 失败*/public boolean set(String key, Object value, long time) {try {if (time > 0) {redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);} else {set(key, value);}return true;} catch (Exception e) {e.printStackTrace();return false;}}/*** 递增** @param key 键* @param delta 要增加几(大于0)* @return*/public long incr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递增因子必须大于0");}return redisTemplate.opsForValue().increment(key, delta);}/*** 递减** @param key 键* @param delta 要减少几(小于0)* @return*/public long decr(String key, long delta) {if (delta < 0) {throw new RuntimeException("递减因子必须大于0");}return redisTemplate.opsForValue().increment(key, -delta);}// ================================Map=================================/*** HashGet** @param key 键 不能为null* @param item 项 不能为null* @return 值*/public Object hget(String key, String item) {return redisTemplate.opsForHash().get(key, item);}/*** 获取hashKey对应的所有键值** @param key 键* @return 对应的多个键值*/public Map
RedisConfig:
package com.redis.demo.config;import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.redis.demo.utils.MapUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;import javax.annotation.PostConstruct;
import java.util.Map;/*** @Author: laz* @CreateTime: 2023-02-20 11:55* @Version: 1.0** 序列化*/
@Configuration
public class RedisConfig {@Autowiredprivate RedisTemplate redisTemplate;@PostConstructpublic void init() {initRedisTemplate();}private void initRedisTemplate() {RedisSerializer stringSerializer = redisTemplate.getStringSerializer();redisTemplate.setKeySerializer(stringSerializer);redisTemplate.setHashKeySerializer(stringSerializer);redisTemplate.setValueSerializer(stringSerializer);redisTemplate.setHashValueSerializer(stringSerializer);}}
package com.redis.demo.dao;import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.redis.demo.entity.BladeUser;/*** * 用户表 Mapper 接口*
** @author laz* @since 2023-03-09*/
public interface BladeUserMapper extends BaseMapper {}
IBladeUserService:
package com.redis.demo.service;import com.baomidou.mybatisplus.extension.service.IService;
import com.redis.demo.entity.BladeUser;
import com.redis.demo.result.DealResult;/*** * 用户表 服务类*
** @author laz* @since 2023-03-09*/
public interface IBladeUserService extends IService {DealResult getById(Long id);
}
BladeUserServiceImpl:
package com.redis.demo.service.impl;import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redis.demo.constant.RedisConstants;
import com.redis.demo.dao.BladeUserMapper;
import com.redis.demo.entity.BladeUser;
import com.redis.demo.result.DealResult;
import com.redis.demo.service.IBladeUserService;
import com.redis.demo.status.CacheNameStatus;
import com.redis.demo.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;/*** * 用户表 服务实现类*
** @author laz* @since 2023-03-09*/
@Service
public class BladeUserServiceImpl extends ServiceImpl implements IBladeUserService {@Autowiredprivate RedisUtils redisUtils;@Overridepublic DealResult getById(Long id) {String userKey = RedisConstants.CACHE_USER_KEY+id;Object user = redisUtils.get(userKey);if (!ObjectUtils.isEmpty(user)){return DealResult.data(JSONUtil.toBean(JSONUtil.toJsonStr(user),BladeUser.class));}BladeUser bladeUser = baseMapper.selectById(id);redisUtils.set(userKey, JSON.toJSONString(bladeUser));return DealResult.data(bladeUser);}}
package com.redis.demo.controller;import com.redis.demo.result.DealResult;
import com.redis.demo.service.IBladeUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;/*** * 用户表 前端控制器*
** @author laz* @since 2023-03-09*/
@RestController
@RequestMapping("/bladeUser")
public class BladeUserController {@Autowiredprivate IBladeUserService bladeUserService;@RequestMapping("getById/{id}")public DealResult getById(@PathVariable("id")Long id){return bladeUserService.getById(id);}}
启动项目,使用postman访问该接口,连续请求两次,观察响应时长:
第一次:
第二次:
可以看到,第一次3.34s,第二次43ms,效率明显提高!
以方式一为准
@EnableCaching
注解package com.redis.demo.service.impl;import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.redis.demo.constant.RedisConstants;
import com.redis.demo.dao.BladeUserMapper;
import com.redis.demo.entity.BladeUser;
import com.redis.demo.result.DealResult;
import com.redis.demo.service.IBladeUserService;
import com.redis.demo.status.CacheNameStatus;
import com.redis.demo.utils.RedisUtils;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;/*** * 用户表 服务实现类*
** @author laz* @since 2023-03-09*/
@Service
public class BladeUserServiceImpl extends ServiceImpl implements IBladeUserService {@Autowiredprivate RedisUtils redisUtils;// @Override
// public DealResult getById(Long id) {
//
// String userKey = RedisConstants.CACHE_USER_KEY+id;
// Object user = redisUtils.get(userKey);
// if (!ObjectUtils.isEmpty(user)){
//
// return DealResult.data(JSONUtil.toBean(JSONUtil.toJsonStr(user),BladeUser.class));
// }
//
// BladeUser bladeUser = baseMapper.selectById(id);
// redisUtils.set(userKey, JSON.toJSONString(bladeUser));
// return DealResult.data(bladeUser);
// }@Cacheable(cacheNames = CacheNameStatus.BLADE_USER,keyGenerator = CacheNameStatus.KEY_GENERATOR)@Overridepublic DealResult getById(Long id) {BladeUser bladeUser = baseMapper.selectById(id);return DealResult.data(bladeUser);}
}
在配置类中添加自定义KeyGenerator
/*** 自定义KeyGenerator* @return*/@Beanpublic KeyGenerator simpleKeyGenerator() {return (o, method, objects) -> {StringBuilder stringBuilder = new StringBuilder();stringBuilder.append(o.getClass().getSimpleName());stringBuilder.append(".");stringBuilder.append(method.getName());stringBuilder.append("[");for (Object obj : objects) {if(obj.toString().indexOf("Vo@")!= -1){Map map = MapUtil.getAttrFromModel(obj);stringBuilder.append("[");for(String item:map.keySet()){stringBuilder.append(",");stringBuilder.append(map.get(item));}stringBuilder.append(",");stringBuilder.deleteCharAt(stringBuilder.length() - 1);stringBuilder.append("]");}else {stringBuilder.append(obj);stringBuilder.append(",");}}stringBuilder.append("]");return stringBuilder.toString();};}
注:关于 @Cacheable
注解的参数,不懂的可以点击查看。
重启项目,再次访问以上接口,观察响应时间:
第一次:
第二次:
可以看到,第一次2.52s,第二次44ms,效率明显提高!
通过Redis可视化工具观察缓存数据:
通过观察缓存数据大小可知:方式一449字节,方式二976字节,如果从内存占用大小的角度考虑,博主认为使用RedisTemplate
方式做缓存更合适,因为这种方式所占内存相对较少。
以上就是该篇文章的所有内容,代码已上传至git:https://gitee.com/lianaozhe/springboot-redis.git