spring集成redis详解

最近工作需要用到redis替代以前的ehcache作为缓存工具,所以就研究了一下。如果你不知道redis怎么安装和使用,请参考我的另外一篇文章点击打开链接

一、引包

项目内引入文件jedis-2.1.0.jar、spring-data-redis-1.0.2.RELEASE.jar,如果启动报错,请再引入commons-pool-1.5.5.jar、commons-pool2-2.2.jar。

二、工作目录下创建配置文件redis.properties

  1. #访问地址  
  2. redis_addr=192.168.1.254  
  3. #访问端口  
  4. redis_port=6379  
  5. #授权密码,有没有这一项取决于要连接的redis服务是否设置了此项  
  6. redis_auth=test123  
  7. #连接池的最大数据库连接数。设为0表示无限制  
  8. redis_max_active=1024  
  9. #最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。  
  10. redis_max_idle=200  
  11. #最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。  
  12. redis_max_wait=10000  
  13. #在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;  
  14. redis_test_on_borrow=true  


三、修改spring配置文件applicationContext.xml

  1. <!-- redis配置 -->  
  2.     <!-- redis配置文件 -->  
  3.     <context:property-placeholder location="classpath*:/redis.properties" ignore-unresolvable="true" />  
  4.       
  5.     <!-- redis连接池 -->  
  6.     <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">   
  7.         <property name="maxActive" value="${redis_max_active}"></property>  
  8.         <property name="maxIdle" value="${redis_max_idle}"></property>  
  9.         <property name="maxWait" value="${redis_max_wait}"></property>  
  10.         <property name="testOnBorrow" value="${redis_test_on_borrow}"></property>  
  11.     </bean>  
  12.     <!-- redis连接工厂 -->  
  13.     <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
  14.         <property name="hostName" value="${redis_addr}"></property>  
  15.         <property name="port" value="${redis_port}"></property>  
  16.         <property name="password" value="${redis_auth}"></property>  
  17.         <property name="poolConfig" ref="jedisConfig"></property>  
  18.     </bean>  
  19.     <!-- redis操作模板,这里采用尽量面向对象的模板 -->  
  20.     <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
  21.         <property name="connectionFactory" ref="connectionFactory" />  
  22.     <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  
  23.         <property name="keySerializer">  
  24.             <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
  25.         </property>  
  26.         <property name="valueSerializer">  
  27.             <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
  28.         </property>  
  29.     </bean>     

四、注入redisTemplate,封装缓存管理类,其接口就不往上贴了。

  1. package com.segerp.lms.web.servlet;  
  2.   
  3. import java.util.List;  
  4. import java.util.concurrent.TimeUnit;  
  5.   
  6. import org.springframework.beans.factory.annotation.Autowired;  
  7. import org.springframework.data.redis.core.StringRedisTemplate;  
  8. import org.springframework.stereotype.Component;  
  9. import com.google.gson.Gson;  
  10.   
  11. @Component("cacheUtil")  
  12. public class CacheUtilImpl implements CacheUtil {  
  13.       
  14.     @Autowired  
  15.     private StringRedisTemplate redisTemplate;//redis操作模板  
  16.       
  17.           
  18.     public void put(String key, String value) {  
  19.         if (key==null || "".equals(key)) {  
  20.             return;  
  21.         }  
  22.         redisTemplate.opsForHash().put(key, key, value);  
  23.           
  24.     }  
  25.   
  26.       
  27.     public void put(String key, Object value) {  
  28.         if (key==null || "".equals(key)) {  
  29.             return;  
  30.         }  
  31.         redisTemplate.opsForHash().put(key, key, new Gson().toJson(value));  
  32.           
  33.     }  
  34.   
  35.       
  36.     public <T> T get(String key, Class<T> className) {  
  37.         Object obj = redisTemplate.opsForHash().get(key, key);  
  38.         if(obj == null){  
  39.             return null;  
  40.         }  
  41.         return new Gson().fromJson(""+obj, className);  
  42.     }  
  43.   
  44.       
  45.     public String get(String key) {  
  46.         Object obj = redisTemplate.opsForHash().get(key, key);  
  47.         if(obj == null){  
  48.             return null;  
  49.         }else{  
  50.             return String.valueOf(obj);  
  51.         }  
  52.     }  
  53.       
  54. }  
其实看的懂上述代码的人能够看出来:我这里是用的google包的Gson把对象转换成json字符串往redis进行存储的,取值时,再通过Gson().fromJson()转换成对象。用此功能时时需要引入gson-2.1.jar


五、测试

编写测试方法,下面对对象的操作,基本上满足了平时工作的需要。

  1. public void testRedis(){  
  2.     //简单字符串处理  
  3.     cacheUtil.put("name""test");  
  4.     System.out.println("String---name--"+cacheUtil.get("name"));  
  5.       
  6.     //map  
  7.     Map<String,Object> map = new HashMap<String,Object>();  
  8.     map.put("key""value");  
  9.     map.put("key1""value1");  
  10.     cacheUtil.put("map", map);  
  11.     //第一种取值方式  
  12.     Map map1 = cacheUtil.get("map",Map.class);  
  13.     if(map1 != null){  
  14.         System.out.println("first map---"+map1.get("key"));  
  15.     }  
  16.     //第二种取值方式  
  17.     Map map2 = new Gson().fromJson(cacheUtil.get("map"), new TypeToken<Map<String,Object>>() {}.getType());  
  18.     if(map2 != null){  
  19.         System.out.println("second map---"+map2.get("key1"));  
  20.     }  
  21.       
  22.       
  23.     //JavaBean处理  
  24.     TUser user = new TUser();  
  25.     user.setUserName("test");  
  26.     cacheUtil.put("user",user);  
  27.     TUser user1 = cacheUtil.get("user",TUser.class);  
  28.     System.out.println("javaBean--name--"+user1.getUserName());  
  29.       
  30.     //List<JavaBean>处理  
  31.     List<TUser> list = new ArrayList<TUser>();  
  32.     list.add(user);  
  33.     cacheUtil.put("list", list);  
  34.     List<TUser> list1 = new Gson().fromJson(cacheUtil.get("list"), new TypeToken<List<TUser>>() {}.getType());  
  35.     if(list1 != null){  
  36.         System.out.println("List<JavaBean>--"+list1.get(0).getUserName());  
  37.     }  
  38.       
  39.       
  40.     //list<String>  
  41.     List<String> newlist = new ArrayList<String>();  
  42.     newlist.add("str1");  
  43.     newlist.add("sr2");  
  44.     cacheUtil.put("newlist", newlist);  
  45.     List<String> newlist1 =  new Gson().fromJson(cacheUtil.get("newlist"), new TypeToken<List<String>>(){}.getType());  
  46.     System.out.println("list<String>--"+newlist1);  
  47.       
  48.     //List<Map<String,Object>>  
  49.     List<Map<String,Object>> nowlist = new ArrayList<Map<String,Object>>();  
  50.     Map<String,Object> newmap = new HashMap<String,Object>();  
  51.     newmap.put("key1""value1");  
  52.     newmap.put("key2""value2");  
  53.     nowlist.add(newmap);  
  54.     cacheUtil.put("nowlist", nowlist);  
  55.     List<Map<String,Object>> nowlist1 =  new Gson().fromJson(cacheUtil.get("nowlist"), new TypeToken<List<Map<String,Object>>>(){}.getType());  
  56.     if(nowlist1 !=null ){  
  57.         System.out.println(nowlist1.get(0).get("key1"));  
  58.     }  
  59.     System.out.println("List<Map<String,Object>>--"+nowlist1);  
  60.       
  61.     //List<Map<String,TUser>>  
  62.     List<Map<String,TUser>> lastList = new ArrayList<Map<String,TUser>>();  
  63.     Map<String,TUser> lastMap = new HashMap<String, TUser>();  
  64.     lastMap.put("user", user);  
  65.     lastList.add(lastMap);  
  66.     cacheUtil.put("lastList", lastList);  
  67.     List<Map<String,TUser>> lastList1 =  new Gson().fromJson(cacheUtil.get("lastList"), new TypeToken<List<Map<String,TUser>>>(){}.getType());  
  68.     if(lastList1 != null){  
  69.         System.out.println("List<Map<String,TUser>>---"+lastList1.get(0).get("user").getUserName());  
  70.     }  
  71.     System.out.println(lastList1);  
  72. }  

输出结果:

  1. String---name--test  
  2. first map---value  
  3. second map---value1  
  4. javaBean--name--test  
  5. List<JavaBean>--test  
  6. list<String>--[str1, sr2]  
  7. value1  
  8. List<Map<String,Object>>--[{key2=value2, key1=value1}]  
  9. List<Map<String,TUser>>---test  
  10. [{[email protected]}]  

spring集成redis详解


最后,上述需要的jar包在这里