springboot集成jedis

本文档展示了如何配置Redis连接池Jedis,包括创建连接池配置、建立Jedis连接以及提供一系列的Redis操作方法,如设置、获取、删除键值对,操作list、set、zset等数据结构。
1 配置文件
# redis依赖
jedis:
  pool:
    host: 127.0.0.1
    port: 6379
    password: 123456
    timeout: 7200
    ssl: false
    config:
      maxIdle: 100
      maxTotal: 1000
      minIdle: 50
      maxWaitMillis: 1000
      testOnBorrow: true
2 创建jedis连接池
package com.bigdata.admin.util.redis;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Author: g's'c
 * @Description: redis连接池
 * @Date: 2022/6/16 9:32
 * @Version: 1.0
 */
@Component
@Slf4j
public class JedisService {
   
   

    @Bean
    public JedisPoolConfig jedisPoolConfig(@Value("${jedis.pool.config.maxTotal}") int maxActive,
                                           @Value("${jedis.pool.config.maxIdle}") int maxIdle,
                                           @Value("${jedis.pool.config.minIdle}") int minIdle,
                                           @Value("${jedis.pool.config.maxWaitMillis}") long maxWaitMillis,
                                           @Value("${jedis.pool.config.testOnBorrow}") boolean testOnBorrow) {
   
   
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(maxActive);
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMinIdle(minIdle);
        jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
        jedisPoolConfig.setTestOnBorrow(testOnBorrow);
        return jedisPoolConfig;
    }

    @Bean
    public JedisPool jedisPool(@Value("${jedis.pool.host}") String host,
                               @Value("${jedis.pool.password}") String password,
                               @Value("${jedis.pool.port}") int port,
                               @Value("${jedis.pool.timeout}") int timeout, JedisPoolConfig jedisPoolConfig) {
   
   

        log.info("=====创建JedisPool连接池=====");
        if (StringUtils.isNotEmpty(password)) {
   
   
            return new JedisPool(jedisPoolConfig, host, port, timeout, password);
        }
        return new JedisPool(jedisPoolConfig, host, port, timeout);
    }
}

3 创建工具类
package com.bigdata.admin.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * redis
 */
@Component
@Slf4j
public class RedisUtil {
   
   

    @Autowired
    private JedisPool jedisPool;

    /**
     * 通过key获取储存在redis中的value
     * @param key
     * @return 成功返回value 失败返回null
     */
    public String get(String key) {
   
   
        Jedis jedis = null;
        String value = null;
        try {
   
   
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        } catch (Exception e) {
   
   
            log.error("redis get", e);
        } finally {
   
   
            returnResource(jedis);
        }
        return value;
    }
    
    /**
     * 向redis存入key和value,并释放连接资源
     * @param key
     * @param value
     * @return 成功 返回OK 失败返回 0
     */
    public String set(String key, String value) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.set(key, value);
        } catch (Exception e) {
   
   
            log.error("redis set", e);
            return null;
        } finally {
   
   
            returnResource(jedis);
        }
    }
    
    /**
     * 删除指定的key,也可以传入一个包含key的数组
     * @param keys 一个key 也可以使 string 数组
     * @return 返回删除成功的个数
     */
    public Long del(String... keys) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.del(keys);
        } catch (Exception e) {
   
   
            log.error("redis del", e);
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
    }
    
    /**
     * 通过key向指定的value值追加值
     * @param key
     * @param str
     * @return 成功返回 添加后value的长度 失败 返回 添加的 value 的长度 异常返回0L
     */
    public Long append(String key, String str) {
   
   
        Jedis jedis = null;
        Long res = null;
        try {
   
   
            jedis = jedisPool.getResource();
            res = jedis.append(key, str);
        } catch (Exception e) {
   
   
            log.error("redis append", e);
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
        return res;
    }

    /**
     * 判断key是否存在
     * @param key
     * @return true OR false
     */
    public Boolean exists(String key) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.exists(key);
        } catch (Exception e) {
   
   
            log.error("redis exists", e);
            return false;
        } finally {
   
   
            returnResource(jedis);
        }
    }

    /**
     * 清空当前数据库中的所有 key,此命令从不失败。
     * @return 总是返回 OK
     */
    public String flushDB() {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.flushDB();
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
        } finally {
   
   
            returnResource(jedis);
        }
        return null;
    }

    /**
     * 为给定 key 设置生存时间,当 key 过期时(生存时间为 0 ),它会被自动删除。
     * @param key
     * @param value
     *            过期时间,单位:秒
     * @return 成功返回1 如果存在 和 发生异常 返回 0
     */
    public Long expire(String key, int value) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.expire(key, value);
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
    }

    /**
     * 以秒为单位,返回给定 key 的剩余生存时间
     * @param key
     * @return 当 key 不存在时,返回 -2 。当 key 存在但没有设置剩余生存时间时,返回 -1 。否则,以秒为单位,返回 key
     *         的剩余生存时间。 发生异常 返回 0
     */
    public Long ttl(String key) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.ttl(key);
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
    }

    /**
     * 新增key,并将 key 的生存时间 (以秒为单位)
     * @param key
     * @param seconds
     *            生存时间 单位:秒
     * @param value
     * @return 设置成功时返回 OK 。当 seconds 参数不合法时,返回一个错误。
     */
    public String setex(String key, int seconds, String value) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.setex(key, seconds, value);
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
        } finally {
   
   
            returnResource(jedis);
        }
        return null;
    }

    /**
     * <p>
     * 设置key value,如果key已经存在则返回0,nx==> not exist
     * </p>
     *
     * @param key
     * @param value
     * @return 成功返回1 如果存在 和 发生异常 返回 0
     */
    public Long setnx(String key, String value) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.setnx(key, value);
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
    }

    /**
     * <p>
     * 将给定 key 的值设为 value ,并返回 key 的旧值(old value)。
     * </p>
     * <p>
     * 当 key 存在但不是字符串类型时,返回一个错误。
     * </p>
     *
     * @param key
     * @param value
     * @return 返回给定 key 的旧值。当 key 没有旧值时,也即是, key 不存在时,返回 nil
     */
    public String getSet(String key, String value) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.getSet(key, value);
        } catch (Exception e) {
   
   

            log.error(e.getMessage());
        } finally {
   
   
            returnResource(jedis);
        }
        return null;
    }

    /**
     * <p>
     * 设置key value并制定这个键值的有效期
     * </p>
     *
     * @param key
     * @param value
     * @param seconds
     *            单位:秒
     * @return 成功返回OK 失败和异常返回null
     */
    public String setex(String key, String value, int seconds) {
   
   
        Jedis jedis = null;
        String res = null;
        try {
   
   
            jedis = jedisPool.getResource();
            res = jedis.setex(key, seconds, value);
        } catch (Exception e) {
   
   
            log.error(e.getMessage());
        } finally {
   
   
            returnResource(jedis);
        }
        return res;
    }

    /**
     * <p>
     * 通过key 和offset 从指定的位置开始将原先value替换
     * </p>
     * <p>
     * 下标从0开始,offset表示从offset下标开始替换
     * </p>
     * <p>
     * 如果替换的字符串长度过小则会这样
     * </p>
     * <p>
     * example:
     * </p>
     * <p>
     * value : bigsea@zto.cn
     * </p>
     * <p>
     * str : abc
     * </p>
     * <P>
     * 从下标7开始替换 则结果为
     * </p>
     * <p>
     * RES : bigsea.abc.cn
     * </p>
     *
     * @param key
     * @param str
     * @param offset
     *            下标位置
     * @return 返回替换后 value 的长度
     */
    public Long setrange(String key, String str, int offset) {
   
   
        Jedis jedis = null;
        try {
   
   
            jedis = jedisPool.getResource();
            return jedis.setrange(key, offset, str);
        } catch (Exception e) {
   
   

            log.error(e.getMessage());
            return 0L;
        } finally {
   
   
            returnResource(jedis);
        }
    }

    /**
     * <p>
     * 通过批量的key获取批量的value
     * </p>
     *
     * @param keys
     *            string数组 也可以是一个key
     * @return 成功返回value的集合, 失败返回null的集合 ,异常返回空
     */
    public List<String> mget(
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值