spring-data整合redis提供通用接口

spring-data与redis整合的步骤,网上很多了,我这就简单说明下,主要是编写提供一个通用的接口,方便使用

1.整合步骤


spring配置文件配置


<context:property-placeholder ignore-resource-not-found="true" location="classpath*:/jedis.properties" />
    <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
		<property name="maxTotal" value="1024" />
		<property name="maxIdle" value="200" />
		<property name="testOnBorrow" value="true" />
	</bean>     				  
	<!-- Jedis ConnectionFactory -->
	<bean id="jedisConnectionFactory"
		class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
		<!-- p:host-name="123.56.207.99" p:port="6379" -->
		<property name="hostName" value="${redis.ip}" />
		<property name="port" value="${redis.port}" />
		<property name="password" value="${redis.pass}" />
		<property name="poolConfig" ref="jedisPoolConfig" />
	</bean>



jedis.properties配置

redis.pool.maxActive=1024
redis.pool.maxIdle=200
redis.pool.maxWait=1000
redis.pool.testOnBorrow=true
redis.ip=redis地址
redis.port=端口号
redis.pass=密码


2.通用接口

package com.utils.redis;

import java.util.Set;

/**
 * redis通用工具缓存类
 * 
 * @author satisfy
 * 
 */
public interface RedisCommonDao {
	/**
	 * 得到value
	 * 
	 * @param key
	 */
	public Object getValue(String key) throws Exception;

	/**
	 * 添加key value
	 * 
	 * @param key
	 * @param value
	 */
	public void setValue(String key, Object value) throws Exception;

	/**
	 * 添加key value (字节)(序列化)
	 * SerializeUtil
	 * @param key
	 * @param value
	 */
	public void setValue(byte[] key, byte[] value) throws Exception;

	/**
	 * 添加key value 并且设置存活时间(byte)
	 * 
	 * @param key
	 * @param value
	 * @param liveTime
	 */
	public void setValue(byte[] key, byte[] value, long liveTime)
			throws Exception;

	/**
	 * 添加key value 并且设置存活时间
	 * 
	 * @param key
	 * @param value
	 * @param liveTime
	 *            单位秒
	 */
	public void setValue(String key, Object value, long liveTime)
			throws Exception;

	/**
	 * @param key
	 */
	public void delValue(String... keys) throws Exception;

	/**
	 * @param 获取所有匹配的key
	 * @return
	 */
	public Set<String> getKeys(String key) throws Exception;

	/**
	 * 清除缓存
	 * 
	 * @throws Exception
	 */
	public void clear() throws Exception;

	/**
	 * 相同key叠加
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public long incr(String key) throws Exception;
	
	/**
	 * 相同key叠加
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public long hincrby(String hashkey,String field,long incr) throws Exception;

	/**
	 * 验证是否存在
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public boolean exists(String key) throws Exception;

	/**
	 * 清空
	 * @return
	 * @throws Exception
	 */
	public String flushDB() throws Exception;

	 /**
     * 查看redis里有多少数据
     */
	public long dbSize() throws Exception;

	 /**
     * 检查是否连接成功
     * 
     * @return
     */
	public String ping() throws Exception;

}

这里主要是提供一个设置key-value,String-Object的通用接口


具体实现

package com.utils.redis.impl;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;

import com.utils.redis.RedisCommonDao;
import com.utils.redis.util.SerializeUtil;

public class RedisCommonDaoImpl implements RedisCommonDao {

	private static final Logger curr_logger = LoggerFactory
			.getLogger(RedisCommonDaoImpl.class);

	@Autowired
	RedisTemplate<Serializable, Serializable> redisTemplate;

	@Override
	public Object getValue(final String key) {
		return redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				Object value = null;
				try {

					byte[] obj = connection.get(key.getBytes());
					if (obj != null) {
						value = SerializeUtil.unserialize(obj);
					}
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl getValue "
									+ e);
					throw (DataAccessException)e;
				}
				return value;
			}
		});
	}

	@Override
	public void setValue(final String key, final Object value) {
		this.setValue(key.getBytes(), SerializeUtil.serialize(value), 0L);
	}

	@Override
	public void setValue(final byte[] key, final byte[] value) {
		this.setValue(key, value, 0L);

	}

	@Override
	public void setValue(String key, Object value, long liveTime) {
		this.setValue(key.getBytes(), SerializeUtil.serialize(value), liveTime);
	}

	@Override
	public void setValue(final byte[] key, final byte[] value,
			final long liveTime) {
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				try {
					connection.multi();
					connection.set(key, value);
					if (liveTime > 0) {
						connection.expire(key, liveTime);
					}
					connection.exec();
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl setValue "
									+ e);
					throw (DataAccessException)e;
				}
				return null;
			}
		});

	}

	@Override
	public void delValue(final String... keys) {
		redisTemplate.execute(new RedisCallback<Object>() {
			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				try {
					connection.multi();
					for (String key : keys) {
						connection.del(key.getBytes());
						
					}
					connection.exec();
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl delValue "
									+ e);
					throw (DataAccessException)e;
				}
				return null;
			}
		});
	}

	/**
	 * 搜索与key匹配的的所有的key
	 */
	@Override
	public Set<String> getKeys(final String key) {

		return redisTemplate.execute(new RedisCallback<Set<String>>() {

			@Override
			public Set<String> doInRedis(RedisConnection connection)
					throws DataAccessException {
				Set<String> result = new HashSet<String>();
				try {
					Set<byte[]> keys = connection.keys(key.getBytes());
					if (keys != null && keys.size() != 0) {
						for (byte[] key : keys) {
							result.add((String) SerializeUtil.unserialize(key));
						}
					}
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl getKeys "
									+ e);
					throw (DataAccessException)e;
				}
				return result;
			}
		});
	}

	@Override
	public void clear() {
		redisTemplate.execute(new RedisCallback<Object>() {

			@Override
			public Object doInRedis(RedisConnection connection)
					throws DataAccessException {
				try {
					Set<byte[]> keys = connection.keys("*".getBytes());
					connection.multi();
					for (byte[] key : keys) {
						connection.del(key);
						
					}
					connection.exec();
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl clear "
									+ e);
					throw (DataAccessException)e;
				}
				return null;
			}
		});
	}

	@Override
	public long incr(final String key) {

		return redisTemplate.execute(new RedisCallback<Long>() {

			@Override
			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {

				Long incr = 0L;
				try {
					incr = connection.incr(key.getBytes());
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl incr "
									+ e);
					throw (DataAccessException)e;
				}
				return incr;
			}
		});
	}

	@Override
	public boolean exists(final String key) {
		return redisTemplate.execute(new RedisCallback<Boolean>() {

			@Override
			public Boolean doInRedis(RedisConnection connection)
					throws DataAccessException {
				Boolean result = false;
				try {
					result = connection.exists(key.getBytes());
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl exists "
									+ e);
					throw (DataAccessException)e;
				}
				return result;
			}
		});
	}

	@Override
	public String flushDB() {
		return redisTemplate.execute(new RedisCallback<String>() {
			public String doInRedis(RedisConnection connection)
					throws DataAccessException {
				connection.flushDb();
				return "ok";
			}
		});
	}

	@Override
	public long dbSize() {
		return redisTemplate.execute(new RedisCallback<Long>() {
			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.dbSize();
			}
		});
	}

	@Override
	public String ping() {
		return redisTemplate.execute(new RedisCallback<String>() {
			public String doInRedis(RedisConnection connection)
					throws DataAccessException {
				return connection.ping();
			}
		});
	}

	@Override
	public long hincrby(final String hashkey,final String field, long incr)
			throws Exception {
		return redisTemplate.execute(new RedisCallback<Long>() {

			@Override
			public Long doInRedis(RedisConnection connection)
					throws DataAccessException {

				Long incr = 0L;
				try {
					incr = connection.hIncrBy(hashkey.getBytes(), field.getBytes(), incr);
				} catch (Exception e) {
					curr_logger
							.error("com.utils.redis.impl.RedisCommonDaoImpl hincrby "
									+ e);
					throw (DataAccessException)e;
				}
				return incr;
			}
		});
	}

}
</pre><p>这里因为写的比较匆忙,所以全都使用的excute的api,但是使用redistemplete获取redisCallback回调操作的话,可以进行更多的redis操作,比如事务控制等等<span style="color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Tahoma,Arial,STXihei,'Microsoft YaHei',微软雅黑,sans-serif; font-size:16px; line-height:27.2px; text-indent:16px; background-color:rgb(254,254,254)">,</span></p><p><span style="color:rgb(51,51,51); font-family:'Helvetica Neue',Helvetica,Tahoma,Arial,STXihei,'Microsoft YaHei',微软雅黑,sans-serif; font-size:16px; line-height:27.2px; text-indent:16px; background-color:rgb(254,254,254)"></span>spring提供了更方便的api</p><pre name="code" class="java">redisTemplate.opsForValue();//操作键值对的,
redisTemplate.opsForList();//redis list操作
redisTemplate.opsForHash();//redis hash操作
redisTemplate.opsForSet();//redis set操作
redisTemplate.opsForZSet();//redis sort set操作


但是在使用过程中,遇到了问题是,需要redis的链接是从连接池里获取,但是每一次操作redis获取或者存放值得时候,都会有一次redisConnection的开关操作,也就是说每一次都会取连接,然后关闭连接,这样对性能是否有影响,影响有多大,还未做测试,下篇文章会做具体测试,并解决这个问题。






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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值