springboot集成redis缓存的操作过程

发布时间:2021-09-29 17:33:04 作者:柒染
来源:亿速云 阅读:140
# 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>

三、基础配置步骤

1. 配置文件设置

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

2. 配置类编写

创建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;
    }
}

四、缓存操作实现

1. 启用缓存支持

在启动类添加注解:

@SpringBootApplication
@EnableCaching
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

2. 基本缓存注解使用

1) @Cacheable

@Cacheable(value = "userCache", key = "#id")
public User getUserById(Long id) {
    return userRepository.findById(id).orElse(null);
}

2) @CachePut

@CachePut(value = "userCache", key = "#user.id")
public User updateUser(User user) {
    return userRepository.save(user);
}

3) @CacheEvict

@CacheEvict(value = "userCache", key = "#id")
public void deleteUser(Long id) {
    userRepository.deleteById(id);
}

3. 手动操作RedisTemplate

@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);
}

五、高级功能实现

1. 自定义缓存管理器

@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();
}

2. 分布式锁实现

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;
}

六、常见问题解决方案

1. 缓存穿透

@Cacheable(value = "userCache", key = "#id", unless = "#result == null")
public User getUserWithNullCache(Long id) {
    // ...
}

2. 缓存雪崩

@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
    // 随机过期时间
    long randomExpire = new Random().nextInt(600) + 1800;
    RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
            .entryTtl(Duration.ofSeconds(randomExpire));
    // ...
}

3. 缓存击穿

public User getWithMutex(Long id) {
    // 尝试获取锁
    while (!tryLock("user_lock_" + id, "req_" + id, 10)) {
        Thread.sleep(100);
    }
    try {
        // 查询逻辑
    } finally {
        releaseLock("user_lock_" + id, "req_" + id);
    }
}

七、性能优化建议

  1. 合理设置过期时间
  2. 对大对象进行压缩
  3. 使用Pipeline批量操作
  4. 避免使用KEYS命令
  5. 监控缓存命中率

八、总结

本文详细介绍了SpringBoot集成Redis的完整流程,包括: - 基础环境搭建 - 缓存注解的使用 - 高级功能的实现 - 常见问题的解决方案

通过合理使用Redis缓存,可以有效提升系统性能,建议在实际项目中根据业务场景选择合适的缓存策略。 “`

注:本文实际约1300字,可根据需要增减具体实现细节或补充更多案例。建议在实际开发时结合Spring Cache抽象层和Redis特性进行深度优化。

推荐阅读:
  1. springboot redis缓存配置
  2. SpringBoot怎么整合Redis缓存

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

spring boot redis

上一篇:如何实现禁用IE10的密码明文显示和快速清除功能

下一篇:如何解决Google Chrome浏览器无法显示hover样式

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》