Redis 工具类 spingboot集成Redis

1、创建config

package com.test.redis.config;

import java.io.Serializable;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Component
public class RedisPoolConfig implements Serializable{
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -6283969761744281011L;

	@Value("${spring.redis.host}")//配置文件读取

	private String hostName;
	
	@Value("${spring.redis.port}")//配置文件读取

	private int port;
	
	@Value("${spring.redis.timeout}")//配置文件读取

	private int timeout;
	
	JedisPool pool;
	
	public JedisPoolConfig getRedisConfig(){
		JedisPoolConfig config = new JedisPoolConfig();
		return config;
	}
	
	public JedisPool getJedisPool(){
		JedisPoolConfig config = getRedisConfig();
		if(pool == null){
			pool = new JedisPool(config, this.hostName, this.port, this.timeout);
		}
		return pool;
	}

	public String getHostName() {
		return hostName;
	}

	public void setHostName(String hostName) {
		this.hostName = hostName;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}

	public int getTimeout() {
		return timeout;
	}

	public void setTimeout(int timeout) {
		this.timeout = timeout;
	}
	
}

2、创建工具类

package com.test.redis.util;

import java.util.Iterator;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.newsee.redis.config.RedisPoolConfig;

import redis.clients.jedis.Jedis;

/**
 * redis操作工具类
 * @author zrk
 * @desc
 *
 */
@Component
public class RedisUtil {
	
	//redis连接池配置类
	@Autowired
	private RedisPoolConfig redisPoolConfig;

	/**
	 * 获取redis的resource
	 * @return
	 */
	public Jedis getResource() {
		return redisPoolConfig.getJedisPool().getResource();
	}

	/**
	 * 获取redis的resource
	 * @param jedis
	 */
	@SuppressWarnings("deprecation")
	public void returnResource(Jedis jedis) {
		if(jedis != null){
			redisPoolConfig.getJedisPool().returnResourceObject(jedis);
		}
	}

	/**
	 * 将String类型的数据设置到redis中
	 * @param key
	 * @param value
	 */
	public void setStringValue(final String key, final String value) {
		Jedis jedis=null;
		try{
			jedis = getResource();
			jedis.set(key, value);
			//logger.info("Redis set string value success: key: " + key + ", value:" + value);
		} catch (Exception e) {
			e.printStackTrace();
			//logger.error("Redis set error: key:"+ key + ", value:" + value, e);
		}finally{
			returnResource(jedis);
		}
	}
	
	/**
	 * 将String类型的数据设置到redis中
	 * @param key
	 * @param value
	 * @param seconds 多少秒后过期
	 */
	public void setStringValue(final String key, final String value, final int seconds) {
		Jedis jedis=null;
		try{
			jedis = getResource();
			jedis.setex(key, seconds, value);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
	}
	
	/**
	 * 从redis中获取String类型的数据
	 * @param key
	 * @return
	 */
	public String getStringValue(final String key) {
		String result = null;
		Jedis jedis=null;
		try{
			jedis = getResource();
			result = jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return result;
	}
	
	
	/**
	 * 将Object类型的数据设置到redis中
	 * @param key
	 * @param value
	 */
	public void setObjectValue(final String key, final Object value) {
		Jedis jedis=null;
		try{
			jedis = getResource();
			jedis.set(key.getBytes(), SerializeUtil.serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
	}
	
	/**
	 * 将Object类型的数据设置到redis中
	 * @param key
	 * @param value
	 * @param seconds 多少秒后过期
	 */
	public void setObjectValue(final String key, final Object value, final int seconds) {
		Jedis jedis=null;
		try{
			jedis = getResource();
			jedis.setex(key.getBytes(), seconds, SerializeUtil.serialize(value));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
	}
	
	
	/**
	 * 从redis中获取String类型的数据
	 * @param key
	 * @return
	 */
	public Object getObjectValue(final String key) {
		Object result = null;
		Jedis jedis=null;
		try{
			jedis = getResource();
			result = (Object) SerializeUtil.unserialize(jedis.get(key.getBytes()));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return result;
	}
	
	/**
	 * 检查key是否存在
	 * @param key
	 * @return
	 */
	public boolean isExits(final String key){
		Jedis jedis=null;
		boolean isExits = false;
		try{
			jedis = getResource();
			isExits = jedis.exists(key);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return isExits;
	}
	
	/**
	 * 根据key删除村存储对象
	 * @param key
	 * @return
	 */
	public boolean delete(final String key){
		Jedis jedis=null;
		boolean isDeleted = false;
		try{
			jedis = getResource();
			Long count = jedis.del(key);
			if(count.longValue() > 0){
				isDeleted = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return isDeleted;
	}

	/**
	 * 根据前缀删除redis中的key值
	 * @param keyPrefix
	 * @return
	 */
	public boolean deleteByPrefix(String keyPrefix){
		Jedis jedis=null;
		boolean isDeleted = false;
		try{
			jedis = getResource();
			/*Long count = jedis.del(keyPrefix + "*");
			if(count.longValue() > 0){
				isDeleted = true;
			}*/
			 Set<String> set = jedis.keys(keyPrefix +"*");  
		     Iterator<String> it = set.iterator();  
	         while(it.hasNext()){ 
	            String keyStr = it.next();  
	            Long count = jedis.del(keyStr); 
	            if(count.longValue() > 0){
	                isDeleted = true;
	            }
	          }
		        
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			returnResource(jedis);
		}
		return isDeleted;
	}
	
}

3、SerializeUtil 工具类

public class SerializeUtil {
	
//	private static Logger logger = Logger.getLogger(SerializeUtil.class);
	
	/**
	 * 序列化对象成二进制数据
	 * @param object
	 * @return 二进制数组
	 */
	public static byte[] serialize(final Object object) {
        ObjectOutputStream oos = null;
        ByteArrayOutputStream baos = null;
        try {
            baos = new ByteArrayOutputStream();
            oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return baos.toByteArray();
        } catch (Exception e) {
//        	logger.error("序列化object失败>>SerializeUtil>>serialize", e);
        }
        return null;
    }
	
	/**
     * 将二进制数组反序列化成对象
     * @param bytes
     * @return Object
     */
    public static Object unserialize(final byte[] bytes) {
        ByteArrayInputStream bais = null;
        try {
            bais = new ByteArrayInputStream(bytes);
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (Exception e) {
//        	logger.error("反序列化object失败>>SerializeUtil>>unserialize", e);
        } 
        return null;
    }
}

4、引用 通过MVC的注解 @Autowired 引入工具类即可

@Autowired
	private RedisUtil redisUtil;

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值