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;

 

回答: 在Spring Boot项目中集成Redis,并封装Redis工具类可以简化操作并提高代码的可读性。首先,我们需要在项目的pom.xml文件中引入相关依赖,如下所示: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 这将会自动引入Spring Data Redis的依赖,使我们能够轻松地使用RedisTemplate进行操作。接下来,我们需要创建一个Redis工具类,该类封装了一系列对Redis的常用操作方法,例如设置值、获取值、删除值等。通过封装,我们可以将Redis的操作统一放在工具类中,提高代码的可维护性和可读性。最后,我们还需要解决Redis在存储中文时可能出现的乱码问题。可以通过在Redis配置文件中设置编码方式来解决这个问题,例如在application.properties中添加以下配置: ``` spring.redis.charset=UTF-8 ``` 这样就可以确保在Redis存储中文时不会出现乱码的情况。总之,通过集成Redis和封装Redis工具类,我们可以方便地在Spring Boot项目中使用Redis进行数据缓存和持久化操作。<span class="em">1</span> #### 引用[.reference_title] - *1* [redis工具类(springboot)](https://blog.csdn.net/qq_37140416/article/details/106572815)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值