Redis工具类的实现

使用 Spring Data Redis 来实现一个详细的 Redis 工具类,其中包括了常见的 Redis 操作,比如字符串操作、哈希操作、列表操作、集合操作,以及分布式锁的实现等。

1. 添加依赖

在你的 pom.xml 中添加 Spring Data Redis 的依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
    <version>3.1.0</version> <!-- 版本可以根据需要调整 -->
</dependency>

2. 配置 Redis 连接

首先,需要在 Spring Boot 的配置文件中配置 Redis 的连接信息。通常在 application.propertiesapplication.yml 中配置:

# application.properties
spring.redis.host=localhost
spring.redis.port=6379
spring.redis.password=yourpassword  # 如果没有密码,可以省略这行
spring.redis.timeout=60000          # 超时时间(单位:毫秒)
# application.yml
spring:
  redis:
    host: localhost
    port: 6379
    password: yourpassword  # 如果没有密码,可以省略这行
    timeout: 60000          # 超时时间(单位:毫秒)

3. Redis 工具类实现

Spring Data Redis 工具类实现,涵盖了字符串、哈希、列表、集合操作和分布式锁的基本用法:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Component;

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

@Component
public class RedisUtil {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

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

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

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key, String value) {
        try {
            stringRedisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 带过期时间的普通缓存放入
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key, String value, long time) {
        try {
            if (time > 0) {
                stringRedisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
            } else {
                set(key, value);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

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

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

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

    /**
     * 向一张哈希表中放入数据, 如果不存在将创建
     * @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;
        }
    }

    // ============================= 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 键
     * @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;
        }
    }

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

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

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

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

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

    // ============================= Distributed Lock =============================

    /**
     * 获取分布式锁
     * @param key 锁的键
     * @param value 锁的唯一值
     * @param expireTime 锁的过期时间
     * @return true获取锁成功 false获取锁失败
     */
    public boolean tryGetDistributedLock(String key, String value, long expireTime) {
        try {
            Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(key, value, expireTime, TimeUnit.SECONDS);
            return Boolean.TRUE.equals(success);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 释放分布式锁
     * @param key 锁的键
     * @param value 锁的唯一值
     * @return true释放锁成功 false释放锁失败
     */
    public boolean releaseDistributedLock(String key, String value) {
        try {
            String currentValue = get(key);
            if (value.equals(currentValue)) {
                stringRedisTemplate.delete(key);
                return true;
            }
            return false;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

4. 代码详解

  • String 操作: setget 方法用来操作 Redis 中的字符串键值对。set 方法允许设置键的过期时间。
  • Hash 操作: 提供了 hSethGet 等方法来操作 Redis 的哈希表数据结构。
  • List 操作: 通过 lSetlGet 可以操作 Redis 中的列表数据结构。lSet 方法可以指定列表的过期时间。
  • Set 操作: sSetsGet 用于操作 Redis 的集合数据结构。
  • 分布式锁: tryGetDistributedLockreleaseDistributedLock 方法实现了分布式锁的获取和释放。

5. 如何使用

你可以将这个工具类注入到需要

使用 Redis 的服务类中,像这样:

@Service
public class MyService {

    @Autowired
    private RedisUtil redisUtil;

    public void someMethod() {
        // 使用 Redis 工具类
        redisUtil.set("myKey", "myValue");
        String value = redisUtil.get("myKey");
        System.out.println(value);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愿时光不负.

爱意随风起,风止意难平。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值