记录一次Jedis和Spring的原生整合
需要的jedis的jar包
<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
</dependency>
redis.properties
#########################redis缓存配置文件###########################
#访问ip
redis.host=127.0.0.1
#访问端口
redis.port=6379
#访问密码
redis.password=""
#超时时间
redis.timeout=10000
#最大闲置链接数
redis.maxIdle=8
#最大连接数
redis.maxTotal=16
#最大等待时间
redis.maxWaitMillis=1000
#连接失败时候等待 true等待到超时 false直接报错
redis.blockWhenExhausted=false
#得到连接后是否检测是否可用
redis.testOnBorrow=true
连接池数据配置
<!--jedis配置-->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!--最大空闲数-->
<property name="maxIdle" value="${redis.maxIdle}"/>
<!--最大连接数-->
<property name="maxTotal" value="${redis.maxTotal}"/>
<!--最大等待时间-->
<property name="maxWaitMillis" value="${redis.maxWaitMillis}"/>
<!--链接超时时是否阻塞,false报错,true阻塞到超时默认true-->
<property name="blockWhenExhausted" value="${redis.blockWhenExhausted}"/>
<!--返回链接时,检测链接是否从成功-->
<property name="testOnBorrow" value="${redis.testOnBorrow}"/>
</bean>
采用ShardedJedisPool集群方式可以配置多个redis-server
<!--spring 分布式jedis的连接池工厂-->
<bean id="jedisPool" class="redis.clients.jedis.ShardedJedisPool">
<constructor-arg index="0" ref="jedisPoolConfig"/>
<constructor-arg index="1">
<list>
<!--集群就是多个bean -->
<bean class="redis.clients.jedis.JedisShardInfo">
<constructor-arg name="host" value="${redis.host}"/>
<constructor-arg name="port" value="${redis.port}"/>
<property name="soTimeout" value="${redis.timeout}"/>
</bean>
</list>
</constructor-arg>
</bean>
在项目中存储象我使用序列化方式所以我先简单封装一下举个例子,记得把连接放回连接池不然多了会报错
/**
* @author yanghs
* @Description:对redis简单封装
* @date 2018/3/21 21:11
*/
public class RedisDao {
private static final Logger log = LoggerFactory.getLogger(RedisDao.class);
private ShardedJedisPool jedisPool;
public ShardedJedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(ShardedJedisPool jedisPool) {
this.jedisPool = jedisPool;
}
public ShardedJedis getJedis(){
ShardedJedis jedis = null;
try {
jedis = getJedisPool().getResource();
}catch (JedisException e){
log.debug("从redis连接池得到连接出错");
e.printStackTrace();
}
return jedis;
}
public byte[] getValueByKey(byte[] key) throws Exception {
ShardedJedis jedis = null;
byte[] result = null;
try {
jedis = getJedis();
result = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
return result;
}
public void saveValueByKey( byte[] key, byte[] value, int expireTime)throws Exception {
ShardedJedis jedis = null;
byte[] result = null;
try {
jedis = getJedis();
jedis.set(key, value);
if (expireTime > 0)
jedis.expire(key, expireTime);
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
public void deleteByKey(byte[] key) throws Exception {
ShardedJedis jedis = null;
try {
jedis = getJedis();
Long result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
jedis.close();
}
}
}