SpringBoot中使用Redis
在SpringBoot中使用Redis,思路如下:
查询时先查Redis缓存,如果缓存中存在信息,就直接从缓存中获取。
如果缓存中没有相关信息,就去数据库中查找,查完顺便将信息存放进缓存里,以便下一次查询。
另外,更新或者删除数据库数据时,记得删除相关的缓存。
在SpringBoot中使用Redis的步骤如下:
1.首先,添加依赖包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-redis</artifactId> <version>1.3.2.RELEASE</version> </dependency>
2.在application.properties中添加Redis配置:
## Redis 配置
## Redis数据库索引(默认为0)
spring.redis.database=0
## Redis服务器地址
spring.redis.host=127.0.0.1
## Redis服务器连接端口
spring.redis.port=6379
## Redis服务器连接密码(默认为空)
spring.redis.password=
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
## 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
## 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
## 连接超时时间(毫秒)
spring.redis.timeout=0
3.对象序列化后才能存储到Redis。我们需要将对象类实现序列化接口 RedisSerializer,并生成serialVersionUID。
如果不实现RedisSerializer接口,会报异常:
IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type
serialVersionUID在eclipse和Intellij Idea中都可以自动生成。详情百度查找。
public class User implements Serializable { private static final long serialVersionUID = 4798316249512579846L; private String uid; private String userName; private String name; private String password; //省略其他的构造方法、getter()、setter()等 }
4.在服务层进行缓存操作,如下所示:
@Service public class UserServiceImpl implements UserSerevice { @Autowired private UserDao userDao; //redisTemplate在注入时,无需声明泛型 @Autowired private RedisTemplate redisTemplate;
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class); @Override public User showUsers(String uid){ //从缓存中获取信息 ValueOperations<String,User> valueOperations=redisTemplate.opsForValue(); //判断缓存是否有记录,如果有记录就直接从缓存中获取信息 boolean hasKey=redisTemplate.hasKey(uid); if(hasKey) { User user= valueOperations.get(uid); logger.debug("====================>从缓存中获取了用户id为"+uid+"的用户信息."); return user; } User user =userDao.selectByPrimaryKey(uid); //如果缓存中不存在信息,在查询过后,就将信息插入缓存中 if(user!=null) { valueOperations.set(uid,user); logger.debug("====================>将用户id为"+uid+"的用户信息插入缓存中."); } return user; } }
分类:
springBoot
, A1--redis
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2016-08-08 python的range函数与切片操作符
2016-08-08 python简单基础代码