"spring框架使用Redis的方法:在pom.xml中导入redis的相关依赖,例如:<dependency><groupId>redis.clients</groupId><arti
在pom.xml中导入redis的相关依赖,例如:
<dependency><groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.1.0</version>
</dependency>
在applicationContext.xml中添加redis相关配置,例如:
<!--redis 配置 开始--><bean id=""jedisPoolConfig"" class=""redis.clients.jedis.JedisPoolConfig"">
<property name=""maxActive"" value=""300""/>
<property name=""maxIdle"" value=""100""/>
<property name=""maxWait"" value=""1000""/>
<property name=""testOnBorrow"" value=""true""/>
</bean>
<!-- Config poolConfig, String host, int port, int timeout, String passWord, int database-->
<bean id=""jedisPool"" class=""redis.clients.jedis.JedisPool"" destroy-method=""destroy"">
<constructor-arg ref=""jedisPoolConfig""/>
<constructor-arg value=""127.0.0.1""/>
<constructor-arg value=""6379""/>
<constructor-arg value=""3000""/>
<constructor-arg value=""123456""/>
<constructor-arg value=""0""/>
</bean>
<bean id=""redisapi"" class=""com.xc.util.RedisAPI"">
<property name=""jedisPool"" ref=""jedisPool""/>
</bean>
最后创建redis的工具类即可。代码如下:
public class RedisAPI {public static JedisPool jedisPool;
public JedisPool getJedisPool() {
return jedisPool;
}
public void setJedisPool(JedisPool jedisPool) {
RedisAPI.jedisPool = jedisPool;
}
public static boolean set(String key,String value){
try{
Jedis jedis = jedisPool.getResource();
jedis.set(key, value);
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public static boolean set(String key,int seconds,String value){
try{
Jedis jedis = jedisPool.getResource();
jedis.setex(key, seconds, value);
return true;
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public boolean exist(String key){
try{
Jedis jedis = jedisPool.getResource();
return jedis.exists(key);
}catch(Exception e){
e.printStackTrace();
}
return false;
}
public static void returnResource(JedisPool pool,Jedis redis){
if(redis != null){
pool.returnResource(redis);
}
}
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;
}
public Long ttl(String key){
try{
Jedis jedis = jedisPool.getResource();
return jedis.ttl(key);
}catch(Exception e){
e.printStackTrace();
}
return (long) -2;
}
public void delete(String key){
try{
Jedis jedis = jedisPool.getResource();
jedis.del(key);
}catch(Exception e){
e.printStackTrace();
}
}
}
--结束END--
本文标题: spring框架怎么使用redis
本文链接: https://www.lsjlt.com/news/116495.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
2024-05-09
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0