写在最前
什么是缓存?
在实际的业务场景中,缓存一般和其他数据库搭配使用,用来减轻后端数据库的压力,比如和关系型数据库 MySQL 配合使用。缓存会把 MySQL 中经常被查询的数据缓存起来,比如热点数据,这样当用户来访问的时候,就不需要到 MySQL 中去查询了,而是直接获取缓存数据,从而降低了后端数据库的读取压力。流程图如下所示:
Spring Boot 整合 Redis
Demo 地址:mingyue-springboot-redis
1.添加依赖
<!-- redis 依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2.修改 SpringBoot 配置文件
spring:
redis:
host: localhost # Redis服务器地址
database: 0 # Redis数据库索引(默认为0)
port: 6379 # Redis服务器连接端口
password: # Redis服务器连接密码(默认为空)
jedis:
pool:
max-active: 8 # 连接池最大连接数(使用负值表示没有限制)
max-wait: -1ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 8 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
timeout: 3000ms # 连接超时时间(毫秒)
3.添加 RedisService 接口
/**
* Redis 操作 Service
*
* @author Strive
* @date 2022/4/21 10:02
* @description
*/
public interface RedisService {
/** 存储数据 */
void set(String key, String value);
/** 获取数据 */
String get(String key);
/** 设置超期时间 */
boolean expire(String key, long expire);
/** 删除数据 */
void remove(String key);
/** 自增操作 */
Long increment(String key, long delta);
}
4.添加 RedisService 接口实现类
/**
* Redis 操作 Service 的实现类
*
* @author Strive
* @date 2022/4/21 10:03
* @description
*/
@Service
@RequiredArgsConstructor
public class RedisServiceImpl implements RedisService {
private final StringRedisTemplate stringRedisTemplate;
@Override
public void set(String key, String value) {
stringRedisTemplate.opsForValue().set(key, value);
}
@Override
public String get(String key) {
return stringRedisTemplate.opsForValue().get(key);
}
@Override
public boolean expire(String key, long expire) {
return Boolean.TRUE.equals(stringRedisTemplate.expire(key, expire, TimeUnit.SECONDS));
}
@Override
public void remove(String key) {
stringRedisTemplate.delete(key);
}
@Override
public Long increment(String key, long delta) {
return stringRedisTemplate.opsForValue().increment(key, delta);
}
}
5.查询结果放入缓存
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.csp.mingyue.redis.mapper.SysUserMapper;
import com.csp.mingyue.redis.model.MingYueUser;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
/** @author Strive */
@Slf4j
@Service
@RequiredArgsConstructor
public class MingYueUserService {
private final SysUserMapper sysUserMapper;
private final RedisService redisService;
/**
* 根据用户ID查询用户信息
*
* @param userId 用户ID
* @return 用户信息
*/
public MingYueUser queryUserById(Long userId) {
log.info("根据用户ID查询用户信息");
// 查询缓存中是否有查询的数据
String userJson = redisService.get(userId.toString());
// 缓存中没有数据则去数据库查询
if (StrUtil.isBlank(userJson)) {
MingYueUser mingYueUser = sysUserMapper.selectById(userId);
// 查询的结果放入缓存
redisService.set(userId.toString(), JSONUtil.toJsonStr(mingYueUser));
// 返回查询到的数据
return mingYueUser;
}
// 缓存中有对应数据直接返回
return JSONUtil.toBean(userJson, MingYueUser.class);
}
}
6.测试接口
启动 Demo 访问 Swagger 直接测试接口:http://localhost:8080/swagger-ui/index.html#/%E7%94%A8%E6%88%B7%E6%A8%A1%E5%9D%97/queryUserByIdUsingGET
第一次测试接口
2022-04-21 10:21:23.426 INFO 34708 --- [nio-8080-exec-1] c.c.m.redis.service.MingYueUserService : 根据用户ID查询用户信息
2022-04-21 10:21:25.224 INFO 34708 --- [nio-8080-exec-1] c.c.m.redis.service.MingYueUserService : 缓存中没有数据则去数据库查询
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1b2734ac] was not registered for synchronization because synchronization is not active
2022-04-21 10:21:25.240 INFO 34708 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Starting...
2022-04-21 10:21:26.112 INFO 34708 --- [nio-8080-exec-1] com.zaxxer.hikari.HikariDataSource : HikariPool-1 - Start completed.
JDBC Connection [HikariProxyConnection@1753123278 wrapping com.mysql.cj.jdbc.ConnectionImpl@4023b41d] will not be managed by Spring
==> Preparing: SELECT user_id,username FROM sys_user WHERE user_id=?
==> Parameters: 2(Long)
<== Columns: user_id, username
<== Row: 2, Strive
<== Total: 1
Closing non transactional SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@1b2734ac]
第二次测试接口
请求已经没有发到数据库了,直接取了缓存数据
2022-04-21 10:23:15.382 INFO 34708 --- [nio-8080-exec-7] c.c.m.redis.service.MingYueUserService : 根据用户ID查询用户信息
2022-04-21 10:23:15.394 INFO 34708 --- [nio-8080-exec-7] c.c.m.redis.service.MingYueUserService : 缓存中有对应数据直接返回
查看 Redis
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/78336.html