手写一个redis工具类

package cn.bugstack.chatgpt.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.List;
import java.util.Map;
import java.util.Set;
@Component
public class RedisUtils {

    private static final Logger logger = LoggerFactory.getLogger(RedisUtils.class);
    private static JedisPool jedisPool;

    // Initialize Redis connection pool
    static {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(128); // Maximum number of connections
        config.setMaxIdle(64);   // Maximum number of idle connections
        config.setMinIdle(16);   // Minimum number of idle connections
        config.setTestOnBorrow(true); // Test connection validity on borrow
        config.setTestOnReturn(true); // Test connection validity on return
        config.setTestWhileIdle(true); // Test connection validity while idle

        // Redis connection configuration
        String redisHost = System.getProperty("redis.host", "localhost"); // Redis address
        int redisPort = Integer.parseInt(System.getProperty("redis.port", "6379")); // Redis port
        jedisPool = new JedisPool(config, redisHost, redisPort);
    }

    // Get a Jedis instance
    private static Jedis getJedis() {
        return jedisPool.getResource();
    }
    public static void set(String key, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.set(key, value); // 直接设置值
            logger.info("Set key: {} with value: {}", key, value);
        } catch (Exception e) {
            logger.error("Error setting value in Redis for key {}: {}", key, e.getMessage(), e);
        }
    }

    // Release Jedis instance
    private static void closeJedis(Jedis jedis) {
        if (jedis != null) {
            jedis.close();
        }
    }

    // Set string value with expiration time (in seconds)
    public static void setWithExpiration(String key, String value, int seconds) {
        try (Jedis jedis = getJedis()) {
            jedis.setex(key, seconds, value); // Set value with expiration
        } catch (Exception e) {
            logger.error("Error setting value in Redis for key {}: {}", key, e.getMessage(), e);
        }
    }

    // Get string value
    public static String get(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.get(key);
        } catch (Exception e) {
            logger.error("Error getting value from Redis for key {}: {}", key, e.getMessage(), e);
            return null;
        }
    }

    // Delete key
    public static void del(String key) {
        try (Jedis jedis = getJedis()) {
            jedis.del(key);
        } catch (Exception e) {
            logger.error("Error deleting key from Redis: {}", key, e);
        }
    }

    // Set hash value with expiration time (in seconds)
    public static void hsetWithExpiration(String key, String field, String value, int seconds) {
        try (Jedis jedis = getJedis()) {
            jedis.hset(key, field, value);
            // Set expiration for the entire hash key
            jedis.expire(key, seconds);
        } catch (Exception e) {
            logger.error("Error setting hash value in Redis for key {}: {}", key, e.getMessage(), e);
        }
    }

    // Get hash value
    public static String hget(String key, String field) {
        try (Jedis jedis = getJedis()) {
            return jedis.hget(key, field);
        } catch (Exception e) {
            logger.error("Error getting hash value from Redis for key {}: {}", key, e.getMessage(), e);
            return null;
        }
    }

    // Get all hash values
    public static Map<String, String> hgetAll(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.hgetAll(key);
        } catch (Exception e) {
            logger.error("Error getting all hash values from Redis for key {}: {}", key, e.getMessage(), e);
            return null;
        }
    }

    // Get all keys matching a pattern
    public static Set<String> keys(String pattern) {
        try (Jedis jedis = getJedis()) {
            return jedis.keys(pattern);
        } catch (Exception e) {
            logger.error("Error getting keys from Redis with pattern {}: {}", pattern, e.getMessage(), e);
            return null;
        }
    }

    // Set list item
    public static void lpush(String key, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.lpush(key, value);
        } catch (Exception e) {
            logger.error("Error pushing value to list in Redis for key {}: {}", key, e.getMessage(), e);
        }
    }

    // Get list items in range
    public static List<String> lrange(String key, long start, long end) {
        try (Jedis jedis = getJedis()) {
            return jedis.lrange(key, start, end);
        } catch (Exception e) {
            logger.error("Error getting range from list in Redis for key {}: {}", key, e.getMessage(), e);
            return null;
        }
    }

    // Increment a key's integer value
    public static long incr(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.incr(key);
        } catch (Exception e) {
            logger.error("Error incrementing key in Redis: {}", key, e);
            return 0;
        }
    }

    // Add value to a set
    public static void sadd(String key, String value) {
        try (Jedis jedis = getJedis()) {
            jedis.sadd(key, value);
        } catch (Exception e) {
            logger.error("Error adding value to set in Redis for key {}: {}", key, e.getMessage(), e);
        }
    }

    // Get all members of a set
    public static Set<String> smembers(String key) {
        try (Jedis jedis = getJedis()) {
            return jedis.smembers(key);
        } catch (Exception e) {
            logger.error("Error getting members from set in Redis for key {}: {}", key, e.getMessage(), e);
            return null;
        }
    }
}

导入依赖

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.6.3</version> <!-- 确保使用适当的版本 -->
</dependency>

使用手法

public class Main {
    public static void main(String[] args) {
        RedisUtil.set("testKey", "testValue");
        String value = RedisUtil.get("testKey");
        System.out.println("Value: " + value);

        RedisUtil.hset("user:1000", "username", "john_doe");
        System.out.println("Username: " + RedisUtil.hget("user:1000", "username"));

        RedisUtil.lpush("myList", "item1");
        RedisUtil.lpush("myList", "item2");
        List<String> items = RedisUtil.lrange("myList", 0, -1);
        System.out.println("List items: " + items);
    }
}

yml配置文件

spring:
  redis:
    host: localhost                # Redis 主机
    port: 6379                     # Redis 端口
    password: yourpassword         # Redis 密码,如果没有则不需要此行
    timeout: 2000                  # 连接超时时间(毫秒)
    jedis:
      pool:
        max-idle: 8                # 连接池最大空闲连接数
        min-idle: 0                # 连接池最小空闲连接数
        max-total: 8               # 连接池最大连接数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值