Redis公共方法详解

一、引言

在现代企业级应用开发中,Redis作为高性能的内存数据库,已经成为Spring Boot项目中不可或缺的技术组件。它不仅能够显著提升系统性能,还能有效解决缓存、分布式锁、会话管理等复杂场景问题。

然而,在实际开发中,直接使用StringRedisTemplateRedisTemplate进行Redis操作存在以下痛点:

  • 代码冗余: 每次操作都需要重复编写模板代码
  • 类型不安全: 需要手动处理序列化和反序列化
  • 缺乏封装: 业务代码与Redis操作耦合度过高

本文将带你从零开始,一步步构建一个完善的Redis工具类,实现String、Hash、List、Set等常用数据类型的CRUD操作,让Redis操作变得简洁、高效、安全。

二、环境准备

2.1 开发环境配置

本文基于以下版本环境进行演示:

组件 版本 说明
JDK JDK 1.8 企业级开发主流版本
Spring Boot 2.7.18 Spring Boot 2.x稳定版本
Redis 7.x 兼容Redis 6.x及以上版本
Spring Data Redis 2.7.18 与Spring Boot版本对应

2.2 Maven依赖配置

pom.xml中添加以下核心依赖:

xml 复制代码
<!-- Spring Boot Starter Data Redis -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<!-- Jedis客户端 (推荐使用Jedis而非Lettuce) -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
</dependency>

<!-- Jackson序列化支持 -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
</dependency>

<!-- Lombok简化代码 (可选) -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <scope>provided</scope>
</dependency>

2.3 配置文件

application.yml中添加Redis连接配置:

yaml 复制代码
spring:
  data:
    redis:
      host: localhost
      port: 6379
      password: # 如果有密码则配置
      database: 0
      timeout: 3000ms
      jedis:
        pool:
          max-active: 8
          max-idle: 8
          min-idle: 0
          max-wait: -1ms

三、核心实现

3.1 Redis配置类

首先创建Redis配置类,配置连接池和序列化方式:

java 复制代码
package com.example.redis.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis配置类
 * 配置RedisTemplate的序列化方式和连接池
 */
@Configuration
public class RedisConfig {

    /**
     * 配置RedisTemplate
     * 使用Jackson2JsonRedisSerializer进行值序列化
     * 使用StringRedisSerializer进行键序列化
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);

        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = 
            new Jackson2JsonRedisSerializer<>(Object.class);
        
        ObjectMapper objectMapper = new ObjectMapper();
        // 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型,类就是非final修饰的,类型信息也作为对象的一部分
        objectMapper.activateDefaultTyping(
            LaissezFaireSubTypeValidator.instance,
            ObjectMapper.DefaultTyping.NON_FINAL,
            JsonTypeInfo.As.PROPERTY
        );
        
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();

        // key采用String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采用String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采用jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采用jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        
        template.afterPropertiesSet();
        return template;
    }
}

3.2 Redis工具类设计

接下来创建一个功能完善的Redis工具类,封装常用操作:

java 复制代码
package com.example.redis.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis工具类
 * 封装常用的Redis操作方法
 * 
 * @author Your Name
 * @since 2024-01-22
 */
@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // =============================String============================

    /**
     * 设置缓存
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 设置缓存并设置过期时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean set(String key, Object value, long time) {
        try {
            if (time > 0) {
                redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 获取缓存
     * @param key 键
     * @return 值
     */
    public Object get(String key) {
        return key == null ? null : redisTemplate.opsForValue().get(key);
    }

    /**
     * 递增
     * @param key 键
     * @param delta 要增加几(大于0)
     * @return 增加后的值
     */
    public long incr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递增因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, delta);
    }

    /**
     * 递减
     * @param key 键
     * @param delta 要减少几(小于0)
     * @return 减少后的值
     */
    public long decr(String key, long delta) {
        if (delta < 0) {
            throw new RuntimeException("递减因子必须大于0");
        }
        return redisTemplate.opsForValue().increment(key, -delta);
    }

    // =============================Hash============================

    /**
     * HashGet
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }

    /**
     * 获取hashKey对应的所有键值
     * @param key 键
     * @return 对应的多个键值
     */
    public Map<Object, Object> hmget(String key) {
        return redisTemplate.opsForHash().entries(key);
    }

    /**
     * HashSet
     * @param key 键
     * @param map 对应多个键值
     * @return true 成功 false 失败
     */
    public boolean hmset(String key, Map<String, Object> map) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * HashSet 并设置时间
     * @param key 键
     * @param map 对应多个键值
     * @param time 时间(秒)
     * @return true成功 false失败
     */
    public boolean hmset(String key, Map<String, Object> map, long time) {
        try {
            redisTemplate.opsForHash().putAll(key, map);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 向一张hash表中放入数据,如果不存在将创建
     * @param key 键
     * @param item 项
     * @param value 值
     * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
     * @return true 成功 false失败
     */
    public boolean hset(String key, String item, Object value, long time) {
        try {
            redisTemplate.opsForHash().put(key, item, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除hash表中的值
     * @param key 键 不能为null
     * @param item 项 可以使多个 不能为null
     */
    public void hdel(String key, Object... item) {
        redisTemplate.opsForHash().delete(key, item);
    }

    /**
     * 判断hash表中是否有该项的值
     * @param key 键 不能为null
     * @param item 项 不能为null
     * @return true 存在 false不存在
     */
    public boolean hHasKey(String key, String item) {
        return redisTemplate.opsForHash().hasKey(key, item);
    }

    // =============================List============================

    /**
     * 获取list缓存的内容
     * @param key 键
     * @param start 开始
     * @param end 结束 0 到 -1代表所有值
     * @return 列表内容
     */
    public List<Object> lGet(String key, long start, long end) {
        try {
            return redisTemplate.opsForList().range(key, start, end);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 获取list缓存的长度
     * @param key 键
     * @return 长度
     */
    public long lGetListSize(String key) {
        try {
            return redisTemplate.opsForList().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 通过索引 获取list中的值
     * @param key 键
     * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
     * @return 值
     */
    public Object lGetIndex(String key, long index) {
        try {
            return redisTemplate.opsForList().index(key, index);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean lSet(String key, Object value) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return true 成功 false失败
     */
    public boolean lSet(String key, Object value, long time) {
        try {
            redisTemplate.opsForList().rightPush(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean lSet(String key, List<Object> value) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将list放入缓存
     * @param key 键
     * @param value 值
     * @param time 时间(秒)
     * @return true 成功 false失败
     */
    public boolean lSet(String key, List<Object> value, long time) {
        try {
            redisTemplate.opsForList().rightPushAll(key, value);
            if (time > 0) {
                expire(key, time);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据索引修改list中的某条数据
     * @param key 键
     * @param index 索引
     * @param value 值
     * @return true 成功 false失败
     */
    public boolean lUpdateIndex(String key, long index, Object value) {
        try {
            redisTemplate.opsForList().set(key, index, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 移除N个值为value
     * @param key 键
     * @param count 移除多少个
     * @param value 值
     * @return 移除的个数
     */
    public long lRemove(String key, long count, Object value) {
        try {
            Long remove = redisTemplate.opsForList().remove(key, count, value);
            return remove;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // =============================Set============================

    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return Set集合
     */
    public Set<Object> sGet(String key) {
        try {
            return redisTemplate.opsForSet().members(key);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据value从一个set中查询,是否存在
     * @param key 键
     * @param value 值
     * @return true 存在 false不存在
     */
    public boolean sHasKey(String key, Object value) {
        try {
            return redisTemplate.opsForSet().isMember(key, value);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSet(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key, long time, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().add(key, values);
            if (time > 0) {
                expire(key, time);
            }
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 获取set缓存的长度
     * @param key 键
     * @return 长度
     */
    public long sGetSetSize(String key) {
        try {
            return redisTemplate.opsForSet().size(key);
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 移除值为value的
     * @param key 键
     * @param values 值 可以是多个
     * @return 移除的个数
     */
    public long setRemove(String key, Object... values) {
        try {
            Long count = redisTemplate.opsForSet().remove(key, values);
            return count;
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }

    // =============================通用============================

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return true 成功 false失败
     */
    public boolean expire(String key, long time) {
        try {
            if (time > 0) {
                redisTemplate.expire(key, time, TimeUnit.SECONDS);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key) {
        return redisTemplate.getExpire(key, TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key) {
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(key));
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    public void del(String... key) {
        if (key != null && key.length > 0) {
            if (key.length == 1) {
                redisTemplate.delete(key[0]);
            } else {
                redisTemplate.delete((Collection<String>) List.of(key));
            }
        }
    }

    /**
     * 模糊查询获取key值
     * @param pattern 匹配模式
     * @return 匹配的key集合
     */
    public Set<String> keys(String pattern) {
        return redisTemplate.keys(pattern);
    }
}

四、使用示例

4.1 注入工具类

在需要使用Redis的Service类中注入RedisUtil:

java 复制代码
package com.example.redis.service.impl;

import com.example.redis.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Redis使用示例Service
 */
@Service
public class RedisExampleService {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * String类型操作示例
     */
    public void stringExample() {
        // 1. 设置缓存
        redisUtil.set("user:1001", "张三");
        redisUtil.set("user:1002", "李四", 60); // 设置60秒过期时间

        // 2. 获取缓存
        String user1 = (String) redisUtil.get("user:1001");
        System.out.println("用户信息: " + user1);

        // 3. 递增操作(适用于计数器场景)
        long viewCount = redisUtil.incr("article:view:1001", 1);
        System.out.println("文章浏览量: " + viewCount);
    }

    /**
     * Hash类型操作示例
     */
    public void hashExample() {
        // 1. 设置单个Hash字段
        redisUtil.hset("user:profile:1001", "name", "张三");
        redisUtil.hset("user:profile:1001", "age", 25);
        redisUtil.hset("user:profile:1001", "email", "zhangsan@example.com");

        // 2. 批量设置Hash字段
        Map<String, Object> userMap = new HashMap<>();
        userMap.put("name", "李四");
        userMap.put("age", 30);
        userMap.put("email", "lisi@example.com");
        redisUtil.hmset("user:profile:1002", userMap);

        // 3. 获取Hash值
        String name = (String) redisUtil.hget("user:profile:1001", "name");
        System.out.println("用户名: " + name);

        // 4. 获取整个Hash
        Map<Object, Object> userProfile = redisUtil.hmget("user:profile:1001");
        System.out.println("用户完整信息: " + userProfile);
    }

    /**
     * List类型操作示例
     */
    public void listExample() {
        // 1. 添加元素到列表
        redisUtil.lSet("message:queue:1", "消息1");
        redisUtil.lSet("message:queue:1", "消息2");
        redisUtil.lSet("message:queue:1", "消息3");

        // 2. 批量添加
        List<Object> messages = Arrays.asList("消息4", "消息5", "消息6");
        redisUtil.lSet("message:queue:1", messages);

        // 3. 获取列表内容
        List<Object> messageList = redisUtil.lGet("message:queue:1", 0, -1);
        System.out.println("消息队列: " + messageList);

        // 4. 获取列表长度
        long size = redisUtil.lGetListSize("message:queue:1");
        System.out.println("消息数量: " + size);

        // 5. 根据索引获取元素
        Object firstMessage = redisUtil.lGetIndex("message:queue:1", 0);
        System.out.println("第一条消息: " + firstMessage);
    }

    /**
     * Set类型操作示例
     */
    public void setExample() {
        // 1. 添加元素到Set
        redisUtil.sSet("article:tags:1", "Java", "Spring", "Redis", "微服务");

        // 2. 判断元素是否存在
        boolean hasJava = redisUtil.sHasKey("article:tags:1", "Java");
        System.out.println("包含Java标签: " + hasJava);

        // 3. 获取Set所有元素
        Set<Object> tags = redisUtil.sGet("article:tags:1");
        System.out.println("文章标签: " + tags);

        // 4. 获取Set大小
        long tagCount = redisUtil.sGetSetSize("article:tags:1");
        System.out.println("标签数量: " + tagCount);
    }

    /**
     * 通用操作示例
     */
    public void commonExample() {
        // 1. 判断key是否存在
        boolean exists = redisUtil.hasKey("user:1001");
        System.out.println("Key是否存在: " + exists);

        // 2. 设置过期时间
        redisUtil.expire("user:1001", 300); // 5分钟后过期

        // 3. 获取过期时间
        long expireTime = redisUtil.getExpire("user:1001");
        System.out.println("剩余过期时间(秒): " + expireTime);

        // 4. 删除key
        redisUtil.del("user:1001", "user:1002");

        // 5. 模糊查询key
        Set<String> keys = redisUtil.keys("user:*");
        System.out.println("匹配的Keys: " + keys);
    }

    /**
     * 实际业务场景示例 - 缓存用户信息
     */
    public User getUserWithCache(Long userId) {
        String cacheKey = "user:info:" + userId;

        // 1. 先从缓存获取
        User cachedUser = (User) redisUtil.get(cacheKey);
        if (cachedUser != null) {
            System.out.println("从缓存获取用户信息");
            return cachedUser;
        }

        // 2. 缓存不存在,从数据库查询(模拟)
        User user = getUserFromDatabase(userId);
        if (user != null) {
            // 3. 写入缓存,设置30分钟过期
            redisUtil.set(cacheKey, user, 1800);
            System.out.println("从数据库查询并缓存用户信息");
        }

        return user;
    }

    /**
     * 实际业务场景示例 - 购物车
     */
    public void addToCart(Long userId, Long productId, int quantity) {
        String cartKey = "cart:user:" + userId;

        // 使用Hash存储购物车: field为productId, value为数量
        redisUtil.hset(cartKey, productId.toString(), quantity);
        // 设置购物车7天过期
        redisUtil.expire(cartKey, 7 * 24 * 3600);
    }

    // 模拟从数据库查询用户
    private User getUserFromDatabase(Long userId) {
        // 实际项目中这里会调用Mapper查询数据库
        User user = new User();
        user.setId(userId);
        user.setName("张三");
        user.setAge(25);
        return user;
    }
}

// 用户实体类
class User {
    private Long id;
    private String name;
    private Integer age;

    // getter和setter方法
    public Long getId() { return id; }
    public void setId(Long id) { this.id = id; }
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public Integer getAge() { return age; }
    public void setAge(Integer age) { this.age = age; }
}

4.2 运行效果说明

启动Spring Boot应用后,可以通过Redis Desktop Manager或redis-cli查看数据:

bash 复制代码
# 连接Redis
redis-cli

# 查看所有key
keys *

# 查看String类型数据
get user:1001

# 查看Hash类型数据
hgetall user:profile:1001

# 查看List类型数据
lrange message:queue:1 0 -1

# 查看Set类型数据
smembers article:tags:1

# 查看key的过期时间
ttl user:info:1001

五、注意事项

5.1 序列化方式选择建议

在实际项目中,序列化方式的选择直接影响性能和兼容性:

序列化方式 优点 缺点 适用场景
StringRedisSerializer 可读性强,可直接在redis-cli查看 仅支持String类型 简单String数据
Jackson2JsonRedisSerializer 性能好,支持复杂对象,可读性尚可 需要额外依赖,类型信息占用空间 复杂对象缓存
JdkSerializationRedisSerializer 无需额外依赖 可读性差,占用空间大 不推荐使用
GenericJackson2JsonRedisSerializer 支持泛型,类型信息完整 性能略低于Jackson 需要保留类型信息的场景

推荐配置:

  • 键(Key): 使用StringRedisSerializer
  • 值(Value): 使用Jackson2JsonRedisSerializer
  • Hash的键和值: 与上述保持一致

5.2 分布式环境注意事项

在分布式环境下使用Redis,需要特别注意以下几点:

1. 连接池配置

yaml 复制代码
spring:
  data:
    redis:
      jedis:
        pool:
          max-active: 8        # 最大连接数
          max-idle: 8           # 最大空闲连接
          min-idle: 0           # 最小空闲连接
          max-wait: -1ms        # 最大等待时间

2. 网络超时配置

yaml 复制代码
spring:
  data:
    redis:
      timeout: 3000ms           # 命令执行超时时间
      lettuce:
        shutdown-timeout: 200ms # 关闭超时时间

3. 集群模式配置

如果使用Redis集群,需要额外配置:

yaml 复制代码
spring:
  data:
    redis:
      cluster:
        nodes:
          - 192.168.1.100:7000
          - 192.168.1.100:7001
          - 192.168.1.100:7002
        max-redirects: 3         # 最大重定向次数

4. 分布式锁场景

在实现分布式锁时,建议使用Redisson框架,它提供了完善的分布式锁实现:

java 复制代码
@Autowired
private RedissonClient redissonClient;

public void distributedLockExample() {
    RLock lock = redissonClient.getLock("myLock");
    try {
        // 尝试加锁,最多等待3秒,锁定10秒后自动释放
        if (lock.tryLock(3, 10, TimeUnit.SECONDS)) {
            // 执行业务逻辑
        }
    } catch (InterruptedException e) {
        Thread.currentThread().interrupt();
    } finally {
        if (lock.isHeldByCurrentThread()) {
            lock.unlock();
        }
    }
}

5.3 性能优化建议

1. 合理使用Pipeline

批量操作时使用Pipeline可以大幅提升性能:

java 复制代码
public void pipelineExample() {
    redisTemplate.executePipelined((RedisCallback<Object>) connection -> {
        for (int i = 0; i < 1000; i++) {
            connection.set(("key:" + i).getBytes(), ("value:" + i).getBytes());
        }
        return null;
    });
}

2. 避免大Key

  • 单个Key的Value大小不应超过1MB
  • Hash/Set/List的元素数量不宜过多
  • 大Key会阻塞Redis线程,影响整体性能

3. 设置合理的过期时间

  • 根据业务特性设置合理的过期时间
  • 避免大量Key同时过期,可以给过期时间增加随机值
  • 示例: redisUtil.set(key, value, 3600 + new Random().nextInt(600));

4. 使用Lua脚本

复杂操作建议使用Lua脚本,保证原子性:

java 复制代码
DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/limit.lua")));
redisScript.setResultType(Long.class);

Long result = redisTemplate.execute(redisScript, Collections.singletonList("limit:user:1001"), "10", "60");

5. 监控和告警

  • 监控Redis的内存使用率、连接数、QPS等指标
  • 设置慢查询日志,及时发现性能问题
  • 配置告警规则,在异常情况下及时通知
相关推荐
Coder_Boy_5 小时前
基于SpringAI的在线考试系统-试卷管理与考试管理模块联合回归测试文档
人工智能·spring boot·架构·领域驱动
小北方城市网5 小时前
生产级 Spring Boot + MyBatis 核心配置模板
java·spring boot·redis·后端·spring·性能优化·mybatis
卓怡学长5 小时前
m119在线购书商城系统
java·数据库·spring boot·spring·汽车
yuankunliu5 小时前
【redis】4、Redis的过期策略和淘汰策略
数据库·redis·缓存
a努力。5 小时前
蚂蚁Java面试被问:流批一体架构的实现和状态管理
java·后端·websocket·spring·面试·职场和发展·架构
虹科网络安全5 小时前
艾体宝洞察 | 缓存策略深度解析:从内存缓存到 Redis 分布式缓存
redis·分布式·缓存
计算机学姐5 小时前
基于SpringBoot的在线骑行网站系统
java·vue.js·spring boot·后端·mysql·spring·tomcat
半路_出家ren5 小时前
23.Python处理SSH和Redis
运维·网络·redis·python·网络安全·ssh·paramiko
optimistic_chen5 小时前
【Redis系列】Redis缓存
linux·数据库·redis·mysql·缓存·火山引擎