您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# SpringBoot集成Redis缓存的操作过程
## 一、Redis简介与集成背景
Redis(Remote Dictionary Server)是一个开源的基于内存的键值对存储系统,常用作数据库、缓存和消息中间件。在SpringBoot项目中集成Redis可以显著提升系统性能,主要体现在:
1. 减轻数据库压力
2. 提高高频访问数据的响应速度
3. 支持分布式缓存
4. 提供丰富的数据结构支持
## 二、环境准备
### 1. 开发环境要求
- JDK 1.8+
- SpringBoot 2.x
- Maven 3.x
- Redis 5.0+(服务端)
### 2. 项目依赖配置
在`pom.xml`中添加必要依赖:
```xml
<!-- Spring Data Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<!-- 对象池依赖 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
在application.yml
中配置Redis连接:
spring:
redis:
host: 127.0.0.1
port: 6379
password: 123456 # 无密码可省略
database: 0
lettuce:
pool:
max-active: 8
max-wait: -1ms
max-idle: 8
min-idle: 0
创建Redis配置类定制序列化方式:
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson2JsonRedisSerializer序列化value
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
// 使用StringRedisSerializer序列化key
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(serializer);
template.setHashKeySerializer(new StringRedisSerializer());
template.setHashValueSerializer(serializer);
template.afterPropertiesSet();
return template;
}
}
在启动类添加注解:
@SpringBootApplication
@EnableCaching
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
@Cacheable(value = "userCache", key = "#id")
public User getUserById(Long id) {
return userRepository.findById(id).orElse(null);
}
@CachePut(value = "userCache", key = "#user.id")
public User updateUser(User user) {
return userRepository.save(user);
}
@CacheEvict(value = "userCache", key = "#id")
public void deleteUser(Long id) {
userRepository.deleteById(id);
}
@Autowired
private RedisTemplate<String, Object> redisTemplate;
// 存储数据
public void setValue(String key, Object value) {
redisTemplate.opsForValue().set(key, value);
// 设置过期时间
redisTemplate.expire(key, 1, TimeUnit.HOURS);
}
// 获取数据
public Object getValue(String key) {
return redisTemplate.opsForValue().get(key);
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
.serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
.entryTtl(Duration.ofMinutes(30));
return RedisCacheManager.builder(factory)
.cacheDefaults(config)
.build();
}
public boolean tryLock(String lockKey, String requestId, long expireTime) {
return redisTemplate.opsForValue().setIfAbsent(lockKey, requestId, expireTime, TimeUnit.SECONDS);
}
public boolean releaseLock(String lockKey, String requestId) {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Long result = redisTemplate.execute(new DefaultRedisScript<>(script, Long.class),
Collections.singletonList(lockKey), requestId);
return result != null && result == 1;
}
@Cacheable(value = "userCache", key = "#id", unless = "#result == null")
public User getUserWithNullCache(Long id) {
// ...
}
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
// 随机过期时间
long randomExpire = new Random().nextInt(600) + 1800;
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(randomExpire));
// ...
}
public User getWithMutex(Long id) {
// 尝试获取锁
while (!tryLock("user_lock_" + id, "req_" + id, 10)) {
Thread.sleep(100);
}
try {
// 查询逻辑
} finally {
releaseLock("user_lock_" + id, "req_" + id);
}
}
本文详细介绍了SpringBoot集成Redis的完整流程,包括: - 基础环境搭建 - 缓存注解的使用 - 高级功能的实现 - 常见问题的解决方案
通过合理使用Redis缓存,可以有效提升系统性能,建议在实际项目中根据业务场景选择合适的缓存策略。 “`
注:本文实际约1300字,可根据需要增减具体实现细节或补充更多案例。建议在实际开发时结合Spring Cache抽象层和Redis特性进行深度优化。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。