1、關於spring配置文件中對於redis的配置 2、配置自定義的RedisAPI,對redis資料庫的管理 3、redis相關依賴 ...
1、關於spring配置文件中對於redis的配置
1 <!-- redis配置 --> 2 <bean id="jedisPoolConfig" class="redis.clients.jedis.JedisPoolConfig"> 3 <!-- <property name="maxActive" value="90"/> --> 4 <property name="maxIdle" value="5"/> 5 <!-- <property name="maxWait" value="1000"/> --> 6 <property name="testOnBorrow" value="true"/> 7 </bean>
<!--配置redis數據源--> 8 <bean id="jedisPool" class="redis.clients.jedis.JedisPool" destroy-method="destroy"> 9 <constructor-arg ref="jedisPoolConfig"/> 10 <constructor-arg value="192.168.21.195"/> 11 <constructor-arg value="6379"/> 12 </bean>
<!--配置自定義的RedisAPI工具類--> 13 <bean id="redisAPI" class="org.slsale.common.RedisAPI"> 14 <property name="jedisPool" ref="jedisPool"/> 15 </bean>
2、配置自定義的RedisAPI,對redis資料庫的管理
1 package org.slsale.common; 2 3 import redis.clients.jedis.Jedis; 4 import redis.clients.jedis.JedisPool; 5 6 /** 7 * jedisAPI 8 * @author luzhewu 9 * 10 */ 11 public class RedisAPI { 12 public JedisPool jedisPool;// redis連接池對象 13 14 public JedisPool getJedisPool() { 15 return jedisPool; 16 } 17 18 public void setJedisPool(JedisPool jedisPool) { 19 this.jedisPool = jedisPool; 20 } 21 22 /** 23 * set key and value tp redis 24 * @param key 25 * @param value 26 * @return 27 */ 28 public boolean set(String key, String value) { 29 Jedis jedis = null; 30 try { 31 jedis = jedisPool.getResource();// 獲取jedis對象 32 jedis.set(key, value); 33 return true; 34 } catch (Exception e) { 35 e.printStackTrace(); 36 } finally { 37 // 返還到連接池 38 returnResource(jedisPool, jedis); 39 } 40 return false; 41 } 42 43 /** 44 * 判斷某個key是否存在 45 * @param key 46 * @return 47 */ 48 public boolean exist(String key) { 49 Jedis jedis = null; 50 try { 51 jedis = jedisPool.getResource(); 52 return jedis.exists(key); 53 } catch (Exception e) { 54 e.printStackTrace(); 55 } finally { 56 // 返還到連接池 57 returnResource(jedisPool, jedis); 58 } 59 return false; 60 } 61 62 /** 63 * 通過key獲取value 64 * @param key 65 * @return 66 */ 67 public String get(String key) { 68 String value = null; 69 Jedis jedis = null; 70 try { 71 jedis = jedisPool.getResource(); 72 value = jedis.get(key); 73 } catch (Exception e) { 74 e.printStackTrace(); 75 } finally { 76 // 返還到連接池 77 returnResource(jedisPool, jedis); 78 } 79 return value; 80 } 81 82 /** 83 * 返還到連接池 84 * @param jedisPool 85 * @param jedis 86 */ 87 public static void returnResource(JedisPool jedisPool, Jedis jedis) { 88 if (jedis != null) { 89 jedisPool.returnResource(jedis); 90 } 91 } 92 }
3、redis相關依賴
1 <!-- redis相關依賴jedis --> 2 <dependency> 3 <groupId>redis.clients</groupId> 4 <artifactId>jedis</artifactId> 5 <version>2.6.1</version>