spring集成redis详解

第一步 引入jar包

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属性文件

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

第三步 修改spring配置文件applicationContext.xml

<!-- redis配置 -->  
    <!-- redis配置文件 -->  
    <context:property-placeholder location="classpath*:/redis.properties" ignore-unresolvable="true" />  

    <!-- redis连接池 -->  
    <bean id="jedisConfig" class="redis.clients.jedis.JedisPoolConfig">   
        <property name="maxActive" value="${redis_max_active}"></property>  
        <property name="maxIdle" value="${redis_max_idle}"></property>  
        <property name="maxWait" value="${redis_max_wait}"></property>  
        <property name="testOnBorrow" value="${redis_test_on_borrow}"></property>  
    </bean>  
    <!-- redis连接工厂 -->  
    <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">  
        <property name="hostName" value="${redis_addr}"></property>  
        <property name="port" value="${redis_port}"></property>  
        <property name="password" value="${redis_auth}"></property>  
        <property name="poolConfig" ref="jedisConfig"></property>  
    </bean>  
    <!-- redis操作模板,这里采用尽量面向对象的模板 -->  
    <bean id="redisTemplate" class="org.springframework.data.redis.core.StringRedisTemplate">  
        <property name="connectionFactory" ref="connectionFactory" />  
    <!--     如果不配置Serializer,那么存储的时候只能使用String,如果用对象类型存储,那么会提示错误 can't cast to String!!!-->  
        <property name="keySerializer">  
            <bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />  
        </property>  
        <property name="valueSerializer">  
            <bean class="org.springframework.data.redis.serializer.JdkSerializationRedisSerializer" />  
        </property>  
    </bean>     

第四步 注入redisTemplate,封装缓存管理类.

package com.segerp.lms.web.servlet;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import com.google.gson.Gson;

@Component("cacheUtil")
public class CacheUtilImpl implements CacheUtil {

    @Autowired
    private StringRedisTemplate redisTemplate;//redis操作模板


    public void put(String key, String value) {
        if (key==null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, key, value);

    }


    public void put(String key, Object value) {
        if (key==null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, key, new Gson().toJson(value));

    }


    public <T> T get(String key, Class<T> className) {
        Object obj = redisTemplate.opsForHash().get(key, key);
        if(obj == null){
            return null;
        }
        return new Gson().fromJson(""+obj, className);
    }


    public String get(String key) {
        Object obj = redisTemplate.opsForHash().get(key, key);
        if(obj == null){
            return null;
        }else{
            return String.valueOf(obj);
        }
    }

}

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

public void testRedis(){  
    //简单字符串处理  
    cacheUtil.put("name", "test");  
    System.out.println("String---name--"+cacheUtil.get("name"));  

    //map  
    Map<String,Object> map = new HashMap<String,Object>();  
    map.put("key", "value");  
    map.put("key1", "value1");  
    cacheUtil.put("map", map);  
    //第一种取值方式  
    Map map1 = cacheUtil.get("map",Map.class);  
    if(map1 != null){  
        System.out.println("first map---"+map1.get("key"));  
    }  
    //第二种取值方式  
    Map map2 = new Gson().fromJson(cacheUtil.get("map"), new TypeToken<Map<String,Object>>() {}.getType());  
    if(map2 != null){  
        System.out.println("second map---"+map2.get("key1"));  
    }  


    //JavaBean处理  
    TUser user = new TUser();  
    user.setUserName("test");  
    cacheUtil.put("user",user);  
    TUser user1 = cacheUtil.get("user",TUser.class);  
    System.out.println("javaBean--name--"+user1.getUserName());  

    //List<JavaBean>处理  
    List<TUser> list = new ArrayList<TUser>();  
    list.add(user);  
    cacheUtil.put("list", list);  
    List<TUser> list1 = new Gson().fromJson(cacheUtil.get("list"), new TypeToken<List<TUser>>() {}.getType());  
    if(list1 != null){  
        System.out.println("List<JavaBean>--"+list1.get(0).getUserName());  
    }  


    //list<String>  
    List<String> newlist = new ArrayList<String>();  
    newlist.add("str1");  
    newlist.add("sr2");  
    cacheUtil.put("newlist", newlist);  
    List<String> newlist1 =  new Gson().fromJson(cacheUtil.get("newlist"), new TypeToken<List<String>>(){}.getType());  
    System.out.println("list<String>--"+newlist1);  

    //List<Map<String,Object>>  
    List<Map<String,Object>> nowlist = new ArrayList<Map<String,Object>>();  
    Map<String,Object> newmap = new HashMap<String,Object>();  
    newmap.put("key1", "value1");  
    newmap.put("key2", "value2");  
    nowlist.add(newmap);  
    cacheUtil.put("nowlist", nowlist);  
    List<Map<String,Object>> nowlist1 =  new Gson().fromJson(cacheUtil.get("nowlist"), new TypeToken<List<Map<String,Object>>>(){}.getType());  
    if(nowlist1 !=null ){  
        System.out.println(nowlist1.get(0).get("key1"));  
    }  
    System.out.println("List<Map<String,Object>>--"+nowlist1);  

    //List<Map<String,TUser>>  
    List<Map<String,TUser>> lastList = new ArrayList<Map<String,TUser>>();  
    Map<String,TUser> lastMap = new HashMap<String, TUser>();  
    lastMap.put("user", user);  
    lastList.add(lastMap);  
    cacheUtil.put("lastList", lastList);  
    List<Map<String,TUser>> lastList1 =  new Gson().fromJson(cacheUtil.get("lastList"), new TypeToken<List<Map<String,TUser>>>(){}.getType());  
    if(lastList1 != null){  
        System.out.println("List<Map<String,TUser>>---"+lastList1.get(0).get("user").getUserName());  
    }  
    System.out.println(lastList1);  
}  

第六步 输出结果

String---name--test
first map---value
second map---value1
javaBean--name--test
List<JavaBean>--test
list<String>--[str1, sr2]
value1
List<Map<String,Object>>--[{key2=value2, key1=value1}]
List<Map<String,TUser>>---test
[{user=com.segerp.lms.pojo.TUser@14f1541}]

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_33949836/article/details/80266969