您的位置:首页 > 数据库 > Redis

ssm开发使用redis作为缓存,使用步骤

2017-12-06 19:58 441 查看
转自:https://www.cnblogs.com/wiseroll/p/7258863.html

1、关于spring配置文件中对于redis的配置



<!-- redis配置 -->
<bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig">
<!-- <property name="maxActive" value="90"/> -->
<property name="maxIdle" value="5"/>
<!-- <property name="maxWait" value="1000"/> -->
<property name="testOnBorrow" value="true"/>
</bean>
    <!--配置redis数据源-->
<bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy">
<constructor-arg ref="jedisPoolConfig"/>
<constructor-arg value="192.168.21.195"/>
<constructor-arg value="6379"/>
</bean>
    <!--配置自定义的RedisAPI工具类-->
<bean id="redisAPI" class="org.slsale.common.RedisAPI">
<property name="jedisPool" ref="jedisPool"/>
</bean>




2、配置自定义的RedisAPI,对redis数据库的管理
package org.slsale.common;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

/**
* jedisAPI
*/
public class RedisAPI {
public JedisPool jedisPool;// redis连接池对象

public JedisPool getJedisPool() {
return jedisPool;
}

public void setJedisPool(JedisPool jedisPool) {
this.jedisPool = jedisPool;
}

/**
* set key and value tp redis
* @param key
* @param value
* @return
*/
public boolean set(String key, String value) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();// 获取jedis对象
jedis.set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
// 返还到连接池
returnResource(jedisPool, jedis);
}
return false;
}

/**
* 判断某个key是否存在
* @param key
* @return
*/
public boolean exist(String key) {
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
return jedis.exists(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 返还到连接池
returnResource(jedisPool, jedis);
}
return false;
}

/**
* 通过key获取value
* @param key
* @return
*/
public String get(String key) {
String value = null;
Jedis jedis = null;
try {
jedis = jedisPool.getResource();
value = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
// 返还到连接池
returnResource(jedisPool, jedis);
}
return value;
}

/**
* 返还到连接池
* @param jedisPool
* @param jedis
*/
public static void returnResource(JedisPool jedisPool, Jedis jedis) {
if (jedis != null) {
jedisPool.returnResource(jedis);
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Redis