SpringBoot使用Redis
0. 导入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
1. 配置yml
spring:
data:
redis:
port: 6379
host: {redis.ip}
database: 0
2. 编写RedisTemplate配置类设置序列化
@Configuration
public class RedisConfiguration {
@Bean
public RedisTemplate<String, Object> stringObjectRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(redisConnectionFactory);
template.setKeySerializer(RedisSerializer.string());
template.setValueSerializer(RedisSerializer.java());
return template;
}
}
3. 使用RedisTemplate
@Autowired
private RedisTemplate<String, Object> redisTemplate;
根据Redis的数据类型,RedisTemplate对各种交互方法做了分组,以下是常用的几个分组:
分组 | 说明 |
---|---|
redisTemplate.opsForValue() |
操作string类型的方法 |
redisTemplate.opsForList() |
操作list类型的方法 |
redisTemplate.opsForSet() |
操作set类型的方法 |
redisTemplate.opsForHash() |
操作hash类型的方法 |
redisTemplate.opsForZSet() |
操作zset类型的方法 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了